Spring Boot-登录后返回用户对象

我有一个配置为这样的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);

我是否可以添加类似我自己的控制器的东西,该东西在成功通过身份验证后将返回带有有关已身份验证用户的一些详细信息的自定义对象?

为清楚起见,我使用的是有角度的应用程序作为客户端。当前,我需要从客户端向服务器发出2个请求:1.向/ login

URL进行POST请求以进行身份​​验证。2. GET请求以检索经过身份验证的用户数据。

我的目标是让第一个请求返回给我用户信息,因此我不必发出第二个请求。当前,第一个请求仅对用户进行身份验证,在服务器上创建会话,并发送回“ 200

OK”状态响应,其中 。我希望它返回有关已登录用户的 的成功响应。

正确的答案是在注释中,因此我将在这里写下:我需要从successHandler重定向到我的控制器,该控制器又返回当前登录的用户信息(在我的情况下,控制器位于url’/

user / me’中:

 @Override

public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,

Authentication authentication) throws ServletException, IOException {

clearAuthenticationAttributes(request);

getRedirectStrategy().sendRedirect(request, response, "/user/me");

}

回答:

如果我正确理解了您的问题,则可以提出建议。

首先,您必须实现类,其中将包含用户信息。此类必须继承自org.springframework.security.core.userdetails.User

public class CustomUserDetails extends User {

public CustomUserDetails(String username, String password,

Collection<? extends GrantedAuthority> authorities) {

super(username, password, authorities);

}

//for example lets add some person data

private String firstName;

private String lastName;

//getters and setters

}

下一步,您将创建自己的接口实现org.springframework.security.core.userdetails.UserDetailsService

@Service

public class CustomUserDetailService implements UserDetailsService{

@Override

public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException{

if(StringUtils.isEmpty(userName))

throw new UsernameNotFoundException("User name is empty");

//if you don't use authority based security, just add empty set

Set<GrantedAuthority> authorities = new HashSet<>();

CustomUserDetails userDetails = new CustomUserDetails(userName, "", authorities);

//here you can load user's data from DB or from

//any other source and do:

//userDetails.setFirstName(firstName);

//userDetails.setLastName(lastName);

return userDetails;

}

}

如您所见,此类只有一个方法,您可以在其中加载和设置自定义用户详细信息。注意,我用@Service注释标记了该类。但是您可以在Java-

config或XML上下文中注册它。

现在,要在成功通过身份验证后访问用户数据,可以使用下一种方法,当Spring将自动通过控制器方法传递主体时:

@Controller

public class MyController{

@RequestMapping("/mapping")

public String myMethod(Principal principal, ModelMap model){

CustomUserDetails userDetails = (CustomUserDetails)principal;

model.addAttribute("firstName", userDetails.getFirstName());

model.addAttribute("lastName", userDetails.getLastName());

}

}

或另一种方式:

@Controller

public class MyController{

@RequestMapping("/mapping")

public String myMethod(ModelMap model){

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

CustomUserDetails userDetails = (CustomUserDetails)auth.getPrincipal();

model.addAttribute("firstName", userDetails.getFirstName());

model.addAttribute("lastName", userDetails.getLastName());

}

}

该方法可以在Spring不自动通过主体的其他地方使用。

要在成功通过身份验证后转到特定地址,可以使用SimpleUrlAuthenticationSuccessHandler。只需在您的配置中创建它:

@Bean

public SavedRequestAwareAuthenticationSuccessHandler successHandler() {

SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();

successHandler.setTargetUrlParameter("/succeslogin");

return successHandler;

}

并在您的配置中使用它:

http.formLogin()

.loginProcessingUrl("/login")

.permitAll()

.usernameParameter("email")

.passwordParameter("pass")

.successHandler(successHandler())

之后,您可以创建控制器,它将发送来自特定网址的响应:

@Controller

@RequestMapping("/sucesslogin")

public class SuccessLoginController{

@RequestMapping(method = RequestMethod.POST)

public String index(ModelMap model, Principal principal){

//here you can return view with response

}

}

当然,您不仅可以返回视图,还可以返回JSON响应(使用@ResponseBody批注)或其他方式,这取决于您的前端。希望这会有所帮助。

以上是 Spring Boot-登录后返回用户对象 的全部内容, 来源链接: utcz.com/qa/413473.html

回到顶部