我有一个配置如下 WebSecurityConfigurerAdapter 的 Spring Boot 应用程序 -
http.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/user/*", "/habbit/*").authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login")
.permitAll()
.usernameParameter("email")
.passwordParameter("pass")
.successHandler(authenticationSuccessHandler)
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
.and()
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true);
我可以添加类似我自己的 Controller 的东西,在成功认证后,返回一个自定义对象,其中包含有关已认证用户的一些详细信息?
更新:
为了清楚起见,我使用 Angular 应用程序作为客户端。
目前我需要从我的客户端向服务器发出 2 个请求:
1. POST 请求到/login URL 进行身份验证。
2. GET 请求以检索经过身份验证的用户数据。
我的目标是让第一个请求返回给我用户信息,这样我就不必提出 2dn 请求。
目前,第一个请求仅验证用户身份,在服务器上创建 session 并返回一个带有 的“200 OK”状态响应。没有数据 .我希望它返回成功响应 有数据关于登录的用户。
回答:
正确答案在评论中,所以我会写在这里:
我需要从我的 successHandler 重定向到我的 Controller ,该 Controller 又返回当前登录的用户信息(在我的情况下, Controller 在 url '/user/me' 中:
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
clearAuthenticationAttributes(request);
getRedirectStrategy().sendRedirect(request, response, "/user/me");
}
最佳答案
在接受的答案中,您需要两次调用才能获取所需的数据。
只需在自定义 AjaxAuthenticationSuccessHandler 中登录后返回数据
像这样。
@Bean
public AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler() {
return new AjaxAuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.getWriter().write(new ObjectMapper().writeValueAsString(new UserAuthenticationResponse(authentication.getName(), 123l)));
response.setStatus(200);
}
};
}
并注册成功处理程序:
http.successHandler(ajaxAuthenticationSuccessHandler())
关于Spring boot - 登录后返回用户对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35241182/