2

spring mvc にある既存のコード ベースに spring security を統合しようとしています。

私の既存のコードベースでは、私はWebプロジェクトのクライアントデリゲートであり、サービスプロジェクトのサービスデリゲートとやり取りし、サービスプロジェクトはバックエンドレイヤーのサービスインターフェイスとやり取りします.これは、バックエンドレイヤーのサービスインターフェイスimplです. m UserDetailsS​​ervice インターフェイスを実装します。

PS - モデル、DO、DTO、リクエスト、レスポンスなど、すべてのレイヤーでさまざまなオブジェクトを作成/変換/渡しています。

だから今、送信をクリックすると、コントロールがデリゲートを介して Web からバックエンド層に移動し、UserDetailsS​​ervice インターフェイスを実装するクラスに到達します。どうすればこれを達成できますか?

[更新]:このリンクを通過した後、セキュリティ xml を以下のように変更しました。

     <security:http auto-config="true" use-expressions="true">
    <security:intercept-url pattern="/welcome.html" access="hasRole('ROLE_USER')" />
    <security:form-login login-page="/portalLogin.html" login-processing-url="/signIn" always-use-default-target="true"
    username-parameter="username" password-parameter="password"
        default-target-url="/welcome.html" authentication-failure-url="/loginfailed.html" />
    <security:logout logout-success-url="/logout.html" />
</security:http> 

私の LoginController は次のようなものです:

      @RequestMapping("/signIn")
        public ModelAndView onClickLogin(@ModelAttribute("dashboard")
        LoginModel loginModel,Model model){
        try{
        delegate.clickLogin(loginModel);
        if(null != loginModel.getError()){
            // return new ModelAndView("error");
        }       
        }catch(Exception exception){
        }
        return new ModelAndView("redirect:welcome.html");

        }

[更新]:非常に遅い更新で申し訳ありません。コントローラー マッピングの問題は解決されました。現在、UsernamePasswordAuthenticationFilter が原因で問題に直面しています。上記のコードによって生成されたログを適切に機能するコード ログと比較した後、Spring セキュリティが 'UsernamePasswordAuthenticationFilter を起動していないことがわかりました。 ' 私の場合、何らかの理由で.'UsernamePasswordAuthenticationFilter' はユーザーを認証するものです。

            //Logs when authentication is done 
            [while using spring's default /j_spring_security_check].

    DEBUG FilterChainProxy - /j_spring_security_check at position 3 of 10 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
    DEBUG UsernamePasswordAuthenticationFilter - Request is to process authentication
    DEBUG ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
    session created
    DEBUG SessionImpl - Opened session at timestamp: 13661947944
    SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])
    After openSession
    DEBUG SessionImpl - Opened session at timestamp: 13661947944
    Criteria before eq::this::CriteriaImpl(com.infy.itrade.core.entity.LoginDO:this[][])::CriteriaImpl(com.infy.itrade.core.entity.LoginDO:this[][])...

    //Logs when authentication is not done [while using custom login processing url : /signIn.html].
    DEBUG FilterChainProxy - /signIn.html at position 3 of 10 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' //UsernamePasswordAuthenticationFilter is not doing authentication process instead it skips to next filter.
    DEBUG FilterChainProxy - /signIn.html at position 4 of 10 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
    DEBUG FilterChainProxy - /signIn.html at position 5 of 10 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'

「AbstractAuthenticationProcessingFilter」を拡張するカスタム フィルター「MyFilter」を作成しました。ただし、ログに次のように表示されるため、「MyFilter」は認証を行いません。

    DEBUG FilterChainProxy - /signIn.html at position 2 of 9 in additional filter chain; firing Filter: 'LogoutFilter'
    DEBUG FilterChainProxy - /signIn.html at position 3 of 9 in additional filter chain; firing Filter: 'MyFilter'
    DEBUG FilterChainProxy - /signIn.html at position 4 of 9 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'

マイフィルター:

    public class MyFilter extends AbstractAuthenticationProcessingFilter {

    private static final String DEFAULT_FILTER_PROCESSES_URL = "/signIn";
    private static final String POST = "POST";
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
    public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";

    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;

    public MyFilter() {
        super(DEFAULT_FILTER_PROCESSES_URL);
    }

    public MyFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
        // TODO Auto-generated constructor stub
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse arg1) throws AuthenticationException,
            IOException, ServletException {
        // TODO Auto-generated method stub
        String username = obtainUsername(request);
        String password = obtainPassword(request);

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);
        HttpSession session = request.getSession(false);
        if (session != null || getAllowSessionCreation()) {
            request.getSession().setAttribute(
                    SPRING_SECURITY_LAST_USERNAME_KEY,
                    TextEscapeUtils.escapeEntities(username));
        }
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        if (request.getMethod().equals(POST)) {
            // If the incoming request is a POST, then we send it up
            // to the AbstractAuthenticationProcessingFilter.
            super.doFilter(request, response, chain);
        } else {
            // If it's a GET, we ignore this request and send it
            // to the next filter in the chain. In this case, that
            // pretty much means the request will hit the /login
            // controller which will process the request to show the
            // login page.
            chain.doFilter(request, response);
        }
    }
    ...
    }

コンテキスト xml:

    <bean id="loginUrlAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
    <property name="loginFormUrl" value="/portalLogin.html"/>
    </bean>

    <bean id="MyFilter" class="com.infosys.itrade.core.dao.security.MyFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationSuccessHandler" ref="successHandler"></property>
        <property name="authenticationFailureHandler" ref="failureHandler"></property>
        <property name="filterProcessesUrl" value="/signIn"></property>
    </bean>

    <bean id="successHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
        <property name="defaultTargetUrl" value="/welcome.html" />
    </bean>

    <bean id="failureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
        <property name="defaultFailureUrl" value="/loginfailed.html" />
    </bean>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider
            user-service-ref="LoginUserDetailsService">
        </security:authentication-provider>
    </security:authentication-manager>

    <bean id="LoginUserDetailsService"
        class="com.infy.itrade.core.service.login.LoginServiceImpl">
        <property name="logindao" ref="loginDAOImpl" />
    </bean>

    <bean id="loginDAOImpl" class="com.infy.itrade.core.dao.login.LoginDAODBImpl">
        <property name="sessionFactory"> <ref bean ="sessionFactory"/> </property>
    </bean>
</beans>

ここで何が欠けていますか?

[更新]: これを機能させることができなかったので、ここで他の人が提案したようにアプローチを変更しました。つまり、ログイン モジュールだけのアーキテクチャ フローを避けています。しかし、現在、私は別の質問をする新しいアプローチで別の問題に直面しています。ありがとう。

4

0 に答える 0