I need to programmatically login users that were authenticated through Facebook API. The reason for that is that there are number of items that are associated to each user (for example shopping cart), therefore once user is authenticated using Facebook API, I need to log the user in using spring security as well to be able to access his/her shopping cart.
Based on my research, there are many methods to implement it but I could not deploy any of them as I am sending log-in request from my code, also another problem is that some people created user object but they did not explain how to create it.
Those who created a user object but did not explain how.
From first example:this answer
Authentication auth =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
From second example: this one
34.User details = new User(username);
35.token.setDetails(details);
From third example: this one
Authentication authentication = new UsernamePasswordAuthenticationToken(user, null,
AuthorityUtils.createAuthorityList("ROLE_USER"));
Another example is here, it does not help because I need to log-in user from my own code not from browser; therefore I do not know how to populate HttpServletRequest object.
protected void automatedLogin(String username, String password, HttpServletRequest request) {
MyCode
...
if(isAuthenticatedByFB())
{
login(username);
return "success";
}
else{
return "failed";
}
Simply put, Spring Security hold the principal information of each authenticated user in a ThreadLocal – represented as an Authentication object. In order to construct and set this Authentication object – we need to use the same approach Spring Security typically uses to build the object on a standard authentication.
The UsernamePasswordAuthenticationToken is an implementation of interface Authentication which extends the interface Principal . Principal is defined in the JSE java. security . UsernamePasswordAuthenticationToken is a concept in Spring Security which implements the Principal interface.
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
Unfortunately it seems there is no "complete" support of programmatic login in Spring security. Here is how I've done it successfully:
@Autowired AuthenticationSuccessHandler successHandler;
@Autowired AuthenticationManager authenticationManager;
@Autowired AuthenticationFailureHandler failureHandler;
public void login(HttpServletRequest request, HttpServletResponse response, String username, String password) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
token.setDetails(new WebAuthenticationDetails(request));//if request is needed during authentication
Authentication auth;
try {
auth = authenticationManager.authenticate(token);
} catch (AuthenticationException e) {
//if failureHandler exists
try {
failureHandler.onAuthenticationFailure(request, response, e);
} catch (IOException | ServletException se) {
//ignore
}
throw e;
}
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(auth);
successHandler.onAuthenticationSuccess(request, response, auth);//if successHandler exists
//if user has a http session you need to save context in session for subsequent requests
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
}
UPDATE Essentially the same is done by Spring's RememberMeAuthenticationFilter.doFilter()
This code is from Grails' Spring Security Core -Plugin, which is released under the Apache 2.0 license. I've added the imports just to point out what the types are exactly. The original author is Burt Beckwith.
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
...
public static void reauthenticate(final String username, final String password) {
UserDetailsService userDetailsService = getBean("userDetailsService");
UserCache userCache = getBean("userCache");
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
userDetails, password == null ? userDetails.getPassword() : password, userDetails.getAuthorities()));
userCache.removeUserFromCache(username);
}
The getBean-method merely provides the bean from application context.
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