Where should manual authentication logic be implemented in spring security - service level or presentation level?

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 for manually authenticating the user in spring security. My question is where should I put this code? Putting this in the service layer forces me to bring the HttpSession object to the service level, which AFAIK is bad. I'm not sure how good it is to place authentication logic in the presentation layer. Anyone have any ideas?

Thanks in advance.

+7
java spring spring-security
source share
1 answer

Refer to Luke Taylor for Best Practice for Getting Active User-Defined UserDetails? to justify the design, to create a custom interface for performing such operations when saving, your code is disconnected from Spring Security. For example, you can write an interface called MyAuthenticator and write an implementation and enter it into your application.

In addition, if your Spring security filters are standard, you do not need to access the HttpSession object. Frame filters take care of this. You should simply write the 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.

+14
source share

All Articles