How to store custom information in SecurityContext of spring-security?

一个人想着一个人 提交于 2019-12-04 09:53:22

问题


In my application I'm using LDAP authentication. But i'm also have 2 remote services which requires authentication via method login(username, password). The method returns security token which makes me able to invoke another methods, i.e. I should pass security token to service methods as first argument.
So I'd like to get these security tokens immediately after successful login using LDAP and store them in SecurityContext. I tried to use authentication-success-handler-ref of form-login element. Using the handler I replace Authentication object in the SecurityContext with custom AuthenticationToken that holds not only password but also security tokens. But in this case I have an exception that no authentication provider supports this class of token. I know it's also possible to store tokens in the HTTP session but in this case I have to pass session to service object, so I'd like to store the tokens in SecurityContext.

What is the best approach to handle service security token?


回答1:


I often use the Authentication.getDetails() object to store additional info that may not be directly linked to the user per say. So you can store any object you want in that field (a HashMap for instance) and it shares the Authentication object life cycle.

HashMap<String, Object> info = new HashMap<String, Object>();
info.put("extraInfo", "info");
auth.setDetails(info);
...
Map<String, Object> i = (Map<String, Object>)SecurityContextHolder.getContext().getAuthentication.getDetails();



回答2:


Your implementation of 'UserDetails' may hold any additional data. This is what gets stored in the SecurityContext which is later accessible after successful login.

You can later access it as (Assumes MyUserDetails implements UserDetails)

Object principal = SecurityContextHolder.getContext().getAuthentication();
if (principal instanceof MyUserDetails) {
  MyUserDetails mud = (MyUserDetails) principal;
  mud.getMyData(); //Extract your additional data here
}


来源:https://stackoverflow.com/questions/3287667/how-to-store-custom-information-in-securitycontext-of-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!