Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should the manual authentication logic in spring security go - Service layer or presentation layer?

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.

like image 305
shazinltc Avatar asked Mar 18 '13 18:03

shazinltc


1 Answers

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.

like image 112
Ritesh Avatar answered Oct 10 '22 01:10

Ritesh