I have this piece of code
UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(email);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
This is to manually authenticate a user in spring security. My question is where should I place this code? Putting this in service layer forces me to bring the HttpSession object to service layer which AFAIK is bad. I am not sure about how good it is to place the authentication logic in presentation layer either. Anyone with any insights??
Thanks in advance.
Refer to Luke Taylor's answer to the question Best practice for getting active user's UserDetails? for the design rationale for creating a custom interface to do this type of things while keeping your code decoupled from the Spring Security. For example, you can write an interface called MyAuthenticator
and write the implementation and inject it in your application.
Also if your spring security filters are standard then you don't need to access HttpSession object. Framework filters will take care of it. You have to just write following in your implementation:
UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(email);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
I would not recommend using "SPRING_SECURITY_CONTEXT" (HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY
) as it may change in future versions of the framework.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With