gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:18:42 31 4
gpt4 key购买 nike

在带有RESTful Web服务的Spring Boot应用程序中,我已将Spring Security与Spring Social和SpringSocialConfigurer一起配置。

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

为了在Spring MVC REST Controller 中通过我自己的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();
}

但我不确定在成功调用 /login端点后必须向客户端完全返回什么。我认为返回完整的身份验证对象是多余的。

成功认证后应退还给客户什么?

您能否告诉我如何正确实现此登录方法?

另外,在使用RESTfull登录的情况下,我将具有 UsernamePasswordAuthenticationToken;在通过Twitter登录的情况下,我将具有 SocialAuthenticationToken在同一应用程序中可以具有不同的 token 吗?

最佳答案

您可以通过覆盖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
}

}
}

另外,您还可以处理故障响应:
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}

关于通过REST端点进行Spring Security身份验证/授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29794096/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com