Reputation: 897
I'm new to Spring Security. I've implemented UserDetails to create my own user. I also have my custom userDetailsService. And everything works now, but I neen to update information about my user without log in. How this can be done? How can I receive information from context and then change it? Thanks in advance
Upvotes: 4
Views: 3860
Reputation:
If the user isn't logged in, then you can't get it from the SecurityContext. It's the login process that puts the user on the context.
Just use the UserDetailsService to load the user (the UDS is after all just a DAO) and then modify and save it as necessary. This would be useful e.g. in administrative use cases (e.g. admin corrects a misspelling in the user's name).
Let me know if that's not what you're asking.
EDIT:
OK, in response to your comment (and I'm doing this from memory, so it may not be 100%):
SecurityContext context = SecurityContextHolder.getContext();
Authentication auth = context.getAuthentication();
CustomUser user = (CustomUser) auth.getPrincipal();
Something very close to that if that's not exactly right. Be careful though because you will get a ClassCastException if the user isn't actually logged in--the call to getPrincipal() will return a String "anonymousUser" if the Spring Security anonymous filter is activated. You can of course easily update the code to handle that possibility.
Upvotes: 4