gpt4 book ai didi

java - Spring安全从更深层访问UserDetailsS​​ervice

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:55:58 26 4
gpt4 key购买 nike


我有以下 UserDetailsS​​ervice 实现。
到目前为止,身份验证过程运行良好。
如何将我的“MyUser bean”(成功登录)存储在“ session ”中,以便我可以在我的应用程序的其他区域访问它

谢谢。

@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {


private EmployeesApi employeesApi = new EmployeesApi();

/**
* Retrieves a user record containing the user's credentials and access.
*/
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException, DataAccessException {

// Declare a null Spring User
UserDetails user = null;

try {


MyUser employee = employeesApi.getByUserName(userName);



user = new User(
employee.getUserName(),
employee.getPassword().toLowerCase(),
true,
true,
true,
true,
getAuthorities(1) );

} catch (Exception e) {
logger.error("Error in retrieving user");
throw new UsernameNotFoundException("Error in retrieving user");
}


}
....

最佳答案

Spring Security 已经为您在 session 中存储了经过身份验证的用户的 UserDetails

因此,在 session 中存储 MyUser 的最简单方法是实现自定义 UserDetails,其中包含对 MyUser 的引用:

public class MyUserDetails extends User {
private MyUser myUser;
public MyUserDetails(..., MyUser myUser) {
super(...);
this.myUser = myUser;
}
public MyUser getMyUser() {
return myUser;
}
...
}

并从您的 UserDetailsS​​ervice 返回它:

MyUser employee = employeesApi.getByUserName(userName);
user = new MyUserDetails(..., myUser);

然后您可以通过安全上下文轻松访问MyUser:

MyUser myUser = ((MyUserDetails) SecurityContextHolder
.getContext().getAuthentication().getPrincipal()).getMyUser();

在 Spring MVC Controller 中:

@RequestMapping(...)
public ModelAndView someController(..., Authentication auth) {
MyUser myUser = ((MyUserDetails) auth.getPrincipal()).getMyUser();
...
}

在 JSP 中:

<security:authentication var = "myUser" property="principal.myUser" />

关于java - Spring安全从更深层访问UserDetailsS​​ervice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4913211/

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