我有以下UserDetailsService实现
到目前为止,身份验证过程非常有效
如何在“会话”中存储我的“MyUser bean”(已成功登录),以便我可以在我的应用程序的其他区域访问它
感谢。
@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");
}
}
....
答案 0 :(得分:6)
Spring Security已将UserDetails
经过身份验证的用户存储在会话中。
因此,在会话中存储MyUser
的最简单方法是实现包含对UserDetails
的引用的自定义MyUser
:
public class MyUserDetails extends User {
private MyUser myUser;
public MyUserDetails(..., MyUser myUser) {
super(...);
this.myUser = myUser;
}
public MyUser getMyUser() {
return myUser;
}
...
}
从UserDetailsService
MyUser employee = employeesApi.getByUserName(userName);
user = new MyUserDetails(..., myUser);
然后,您可以通过安全上下文轻松访问MyUser
:
MyUser myUser = ((MyUserDetails) SecurityContextHolder
.getContext().getAuthentication().getPrincipal()).getMyUser();
在Spring MVC控制器中:
@RequestMapping(...)
public ModelAndView someController(..., Authentication auth) {
MyUser myUser = ((MyUserDetails) auth.getPrincipal()).getMyUser();
...
}
在JSP中:
<security:authentication var = "myUser" property="principal.myUser" />