通过REST端点进行Spring Security身份验证/授权

ale*_*oid 7 authentication spring spring-mvc spring-security spring-social

在我使用RESTful webservices的Spring Boot应用程序中,我已将Spring Security与Spring Social和SpringSocialConfigurer.

现在我有两种身份验证/授权方式 - 通过用户名/密码和社交网络,例如Twitter.

为了在我的Spring MVC REST控制器中通过我自己的RESTful端点实现身份验证/授权,我添加了以下方法:

@RequestMapping(value = "/login", method = RequestMethod.POST)
public Authentication login(@RequestBody LoginUserRequest userRequest) {
    Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userRequest.getUsername(), userRequest.getPassword()));
    boolean isAuthenticated = isAuthenticated(authentication);
    if (isAuthenticated) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    return authentication;
}

private boolean isAuthenticated(Authentication authentication) {
    return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
}
Run Code Online (Sandbox Code Playgroud)

但是我不确定在成功的/login 端点调用之后必须返回到客户端的确切内容.我认为返回完整的身份验证对象是多余的.

在成功验证的情况下应该返回给客户什么?

你能告诉我如何正确实现这个登录方法吗?

此外,在RESTfull登录的情况下,我将有,UsernamePasswordAuthenticationToken并且如果通过Twitter登录我将有SocialAuthenticationToken 可能在同一个应用程序中有不同的令牌吗?

Akh*_*dla 6

您可以通过覆盖中的方法来配置成功身份验证时返回的内容SimpleUrlAuthenticationSuccessHandler


public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

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

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

        super.onAuthenticationSuccess(request, response, authentication);
        ObjectMapper mapper = new ObjectMapper();

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(mapper.writeValueAsString(objectToBereturned);
        response.getWriter().flush();
    }

    protected class NoRedirectStrategy implements RedirectStrategy {

        @Override
        public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
                throws IOException {
            // any redirect if required. leave the implementation black if not needed
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

此外,您还可以处理失败响应:


public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
Run Code Online (Sandbox Code Playgroud)