8

我正在创建一个自定义过滤器 UsernamePasswordAuthenticationFilter 来处理身份验证过程。基本上,当用户通过 REST /login 执行登录 http post 时,自定义过滤器将执行并应响应包含用户详细信息和生成的令牌的 json 格式。

我的问题是我在哪里设置响应客户端的 json 响应?我正在考虑创建 SavedRequestAwareAuthenticationSuccessHandler 的子类并在那里设置 json 响应。这是一个好主意吗?

任何帮助将不胜感激 =)

谢谢

4

1 回答 1

6

You need to implement your own SuccessHandler and inject it into UsernamePasswordAuthenticationFilter:

public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

   public MyAuthenticationSuccessHandler() {
       super();
       setRedirectStrategy(new NoRedirectStrategy());
   }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {

           super.onAuthenticationSuccess(request, response, authentication);
           response.write("my JSON response");
    }


    protected class NoRedirectStrategy implements RedirectStrategy {

        @Override
        public void sendRedirect(HttpServletRequest request,
                HttpServletResponse response, String url) throws IOException {
            // no redirect

        }

    }

}

Note the NoRedirectStrategy: by default UsernamePassword filter will redirect after a successful logon which you probably dont want in this case. Also note that in the above implementation filter chain is terminated on authentication success - you have to make sure your filter renders the proper response, dont rely on underlying servlet to do it for you.

Alternatively you can leave the redirect in place and send client to another URL which in turn renders the JSON response you are looking for.

Sample security context:

    <!--  Security -->
    <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
        <sec:filter-chain-map path-type="ant">
            <sec:filter-chain pattern="/rest/login" filters="wsFilter"/>
        </sec>
    </bean>

    <bean id="wsFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
      <property name="authenticationManager" ref="myAuthenticationManager"/>
      <property name="authenticationSuccessHandler" ref="myAuthSuccessHandler"/>
      <property name="passwordParameter" value="pass"></property>
      <property name="usernameParameter" value="user"></property>
      <property name="postOnly" value="false"></property>
   </bean>

       <bean id="myAuthSuccessHandler" class="com.my.MyAuthenticationSuccessHandler"/>

    <sec:authentication-manager id="myAuthenticationManager" >
        <sec:authentication-provider user-service-ref="UserDetailsImpl">
            <sec:password-encoder hash="md5">
            </sec:password-encoder>
        </sec:authentication-provider>
    </sec:authentication-manager>
于 2013-01-29T20:06:51.283 回答