Spring Security login automatically after user creation - spring

I have successfully used spring security to login users. But the issue is, right now on my web page, when a new user is created, he/she has to again go back to sign in page to login which of course uses spring security. Is there a way to login the user automatically using Spring Security as soon as a new user is created?

do this
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken (userDetails, password2, userDetails.getAuthorities());
authenticationManager.authenticate(auth);
if(auth.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(auth);
}

I have never done it, but i think you should do what it is described in the doc.
Once the request has been authenticated, the Authentication will
usually be stored in a thread-local SecurityContext managed by the
SecurityContextHolder by the authentication mechanism which is being
used. An explicit authentication can be achieved, without using one of
Spring Security's authentication mechanisms, by creating an
Authentication instance and using the code:
SecurityContextHolder.getContext().setAuthentication(anAuthentication);
Note that unless the Authentication has the authenticated property set to true, it will still be authenticated by any security interceptor (for method or web invocations) which encounters it.

Related

Managing session authentication status with session attribute in Spring Security (5.7+)

Given a hypothetical application which uses Spring Session to store session information and:
There are more than one way of initiating a session and authenticating, i.e. different endpoints that can be hit depending on how the user is "logging in".
All of the endpoints a user can use for authentication result in a session attribute called "authenticated" being set to true.
Is it possible to configure Spring Security to determine whether a request is authenticated based on the presence and truthiness of that session variable?
The security filter chain might look something like this
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.cors()
.authorizeHttpRequests(
requests -> {
requests.antMatchers("/auth/login").permitAll();
requests.antMatchers("/auth/sso-login").permitAll();
requests.antMatchers("/auth/developer-login").permitAll();
requests.anyRequest().authenticated();
})
.build();
}
The idea would be that so long as a user has hit any of the login endpoints correctly, the application flags the session as authenticated, allowing the user to access other endpoints as an authenticated user.
Or is there a more integrated solution that allows the application to designate a particular session as authenticated, not using traditional mechanisms like BasicAuth? Specifically in the case of a developer utility being able to mock a login as a mocked user without providing credentials. Simply hitting the endpoint (in the environments where it is available) triggering a fully authenticated session as far as Spring Security is concerned.

Spring oauth2 Remotetokenservice

I have 2 microservices that I have created with spring boot. 1 microservice has a oauth2 authentication service and the other is an oauth2 resource server.
The resource server uses RemoteTokenService to check if the access token is valid. This works and when I create a rest endpoint and supply a Principal parameter the principal of the logged in user is supplied. Example:
#RequestMapping(method = RequestMethod.GET, value = "/api/user/{id:[0-9]+}")
#PreAuthorize("hasAnyAuthority('ROLE_USER')")
public User getUser(#PathVariable("id") long id, Principal principal) {
}
The thing is that the Principal contains the username and authorities of the logged in user and I also need the user info like id of the user.
I don't want to do an extra rest call to get the user data so I was wandering is there anyway to get the remotetokenservice to return more information?
The RemoteTokenServices makes nothing but calling CheckTokenEndpoint of Spring Security and return back the map values to the resources server.
If you want to get more information then you have to implement CheckTokenEndpoint::checkToken method in the Authentication server.
We managed to solve your problem by having spring-oauth2 with JWT integration. So the Authentication Server generates an access token as a claim (after authentication the user) which can hold more information that could be useful at the Resource server. The resource server in this case didn't need to have a remote call to check the token, but it verify the signature of the JWT to accept the claim.

JWT and Spring Security

I've built a REST Service using Spring Boot and Spring Security for authentication. I'm pretty new to both Spring Boot and Spring Security. I've made one authentication module in one JAR file. The front end client sends a request with username and password to the authentication module. The authentication module then authenticates the user's details against a DB. A JWT is created and then sent back to the client if the authentication is successful. The username and role is coded into the JWT. The JWT is then used to verify the user when resources are requested from the other REST Service endpoints that are built in separate JAR files. There are a few things I'm not sure about.
In Spring Security is there one authentication object created for each user so that several users can be authenticated at the same time or is one authentication done each time and only one user can be logged in?
How long is the authentication object in valid? Should I "logout"/remove the authentication successful when the JWT has been created in the authentication module or will it take care of it itself when the request is done? For the resource endpoints (not the authentication endpoint) is there a way to set authentication successful in the authentication object once I've verified the JWT? Similarly can I set the role in the authentication object once the JWT has been verified?
I've based my code on this example https://auth0.com/blog/securing-spring-boot-with-jwts/. I've split it into different JARs for authentication and verification of the JWT (I'm doing verification in resource endpoint). I've also added JDBC authentication instead of in memory authentication.
In Spring Security is there one authentication object created for each
user so that several users can be authenticated at the same time or is
one authentication done each time and only one user can be logged in?
Of course multiple users can be authenticated at the same time!
How long is the authentication object in valid? Should I
"logout"/remove the authentication successful when the JWT has been
created in the authentication module or will it take care of it itself
when the request is done?
You write your service is REST, and if you want to stay "puritan" REST you should configure the authentication to be stateless, which means that the Authentication object is removed when the request has been processed. This does not affect the validity of the JWT token, you can set an expiry of JWT token if you want.
How to make REST stateless with "Java config":
#Configuration
public static class RestHttpConfig extends WebSecurityConfigurerAdapter
{
#Override
protected void configure(HttpSecurity http) throws Exception
{
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// and the rest of security config after this
For the resource endpoints (not the authentication endpoint) is there
a way to set authentication successful in the authentication object
once I've verified the JWT? Similarly can I set the role in the
authentication object once the JWT has been verified?
I use code similar to below after verification of the token:
Collection<? extends GrantedAuthority> authorities = Collections.singleton(new SimpleGrantedAuthority("ROLE_JWT"));
Authentication authentication = new PreAuthenticatedAuthenticationToken(subject, token, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
By constructing the authentication object with at least one role (authority), it is marked as "successful" (authenticated).

How to get auth handler info in Spring Security

In my application I am using multiple authentication handlers like application DB, LDAP and SAML. Now after successful authentication I am using CustomAuthenticationSuccessHandler.java which extends SimpleUrlAuthenticationSuccessHandler class which will be called after successful authentication. My question is how to get information about which handler has a successful authentication. I need this information because if it is an external user (LDAP, SAML) then I have to write a logic to replicate the user in application DB.
My configuation in configure global method:
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
auth
.ldapAuthentication()
.ldapAuthoritiesPopulator(ldapAuthoritiesPopulator)
.userDnPatterns("uid={0},ou=people")
.userDetailsContextMapper(ldapUserDetailsContextMapper)
.contextSource(getLDAPContextSource());`
You can set the info to authentication detail when do authenticated, or you can use different Authentication instances, e.g UsernamePasswordAuthenticationToken for DB and LDAP(maybe need to create a new Authentication to separate them), SAMLAuthenticationToken for SAML.

Spring UserDetails and my User implementation in session

I'm developing my Spring application with the support of Security Model.
I configured everything and it seems to work fine, but I have a conceptual question.
In my controller I can retrieve the User Details generated by Spring like this:
UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Now, should I put this user in the Http session or it's useless?
And also, should I retrieve my User implementation on the basis of the UserDetails object and put it in the session?
What is the right way of thinking with security? I would need my user implementation to retrieve some information but I don't know to keep both around.
http://docs.spring.io/spring-security/site/docs/3.0.x/reference/technical-overview.html#d4e731 in this docks 5.3.1 you can see example.
Something like this:
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);

Resources