How to manually set an authenticated user in Spring Security / SpringMVC
I had the same problem as you a while back. I can't remember the details but the following code got things working for me. This code is used within a Spring Webflow flow, hence the RequestContext and ExternalContext classes. But the part that is most relevant to you is the doAutoLogin method.
public String registerUser(UserRegistrationFormBean userRegistrationFormBean,
RequestContext requestContext,
ExternalContext externalContext) {
try {
Locale userLocale = requestContext.getExternalContext().getLocale();
this.userService.createNewUser(userRegistrationFormBean, userLocale, Constants.SYSTEM_USER_ID);
String emailAddress = userRegistrationFormBean.getChooseEmailAddressFormBean().getEmailAddress();
String password = userRegistrationFormBean.getChoosePasswordFormBean().getPassword();
doAutoLogin(emailAddress, password, (HttpServletRequest) externalContext.getNativeRequest());
return "success";
} catch (EmailAddressNotUniqueException e) {
MessageResolver messageResolvable
= new MessageBuilder().error()
.source(UserRegistrationFormBean.PROPERTYNAME_EMAIL_ADDRESS)
.code("userRegistration.emailAddress.not.unique")
.build();
requestContext.getMessageContext().addMessage(messageResolvable);
return "error";
}
}
private void doAutoLogin(String username, String password, HttpServletRequest request) {
try {
// Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = this.authenticationProvider.authenticate(token);
logger.debug("Logging in with [{}]", authentication.getPrincipal());
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (Exception e) {
SecurityContextHolder.getContext().setAuthentication(null);
logger.error("Failure in autoLogin", e);
}
}
How to set Manually Authenticate User with Spring boot Security
You can make user login into spring security like below.
public void login(HttpServletRequest req, String user, String pass) {
UsernamePasswordAuthenticationToken authReq
= new UsernamePasswordAuthenticationToken(user, pass);
Authentication auth = authManager.authenticate(authReq);
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(auth);
HttpSession session = req.getSession(true);
session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, sc);
}
Refer manually-set-user-authentication-spring-security
Spring Security: Authentication user manually
Something like this:
Authentication authentication = new UsernamePasswordAuthenticationToken(person, null, person.getAuthorities());
log.debug("Logging in with {}", authentication.getPrincipal());
SecurityContextHolder.getContext().setAuthentication(authentication);
Where person
is your UserDetailsBean object.
Spring security context manual authentication giving strange results
It is because SecurityContext
is stored in the ThreadLocal
and you have never clear it from the ThreadLocal
after the web service thread completes processing the request , which means if the same thread is used to process the next request , it still keeps SecurityContext
of the previous request.To be precise , it always keep the user who is the first to use that thread in your case.
The quick fix is that you have to clear SecurityContext
after completing each request :
SecurityContextHolder.clearContext();
Programmatically log-in a user using spring security
In my controller i have this, which logs user in as normal :
Authentication auth =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
Where user is my custom user object(implementing UserDetails) that is newly created. The getAuthorities()
method does this (just because all my users have the same role):
public Collection<GrantedAuthority> getAuthorities() {
//make everyone ROLE_USER
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
GrantedAuthority grantedAuthority = new GrantedAuthority() {
//anonymous inner type
public String getAuthority() {
return "ROLE_USER";
}
};
grantedAuthorities.add(grantedAuthority);
return grantedAuthorities;
}
spring security manual login best practice
For custom web authentication you should implement combination of a custom authentication filter (for example AbstractAuthenticationProcessingFilter
or just GenericFilterBean
), a custom authentication provider (AuthenticationProvider
) or/and custom authentication token (AbstractAuthenticationToken
).
For example, see source of Spring Security Kerberos.
See also:
- The AuthenticationManager, ProviderManager and AuthenticationProvider
Related Topics
Meaning of Delta or Epsilon Argument of Assertequals for Double Values
How to Check If a Date Object Equals Yesterday
Which Artifacts Should I Use for Jaxb Ri in My Maven Project
How Does Java Decide When to Import
How to Convert Date in to Yyyy-Mm-Dd Format
Check If a File Is Locked in Java
Open a JPAnel After Pressing a Button in a Jframe
How to Read a File from a Certain Offset in Java
Java Simpledateformat Timezone Offset with Minute Separated by Colon
Garbage Collection on a Local Variable
Throw Checked Exceptions from Mocks with Mockito
Java Local VS Instance Variable Access Speed