JWT and Spring Security - spring

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).

Related

Mobile app authentication for existing API

I have application with Spring security. It's REST api for Angular SPA. It uses session and cookie mechanism. Now I want to access this api from mobile application (Nativescript). I spent some time searching for best way to authenticate mobile app user. In the most cases oauth2 and jwt tokens are advised. So I've done reasearch on this and decided to add additional (seperate) authentication only for mobile application. So Angular app still will be using session with path api/... and mobile app will be using token mechanism with path /api/mobile/... (underneath it will be the same api but with different prefix).
I've decided to use OAuth2 and its Spring integration. I've read documentation and I'm consfused. Why they always mention about authentication provider (Google, Github, Facebook)? I don't want to force my users to login via other service. I want to allow them login with credentials they already registered with in my application. How this social login even related with oAuth authorization server? All examples they've provided use some other services.
I've also tried to add my authorization server in my existing app. I've successfully retrieved token. But now I don't understand all this relationships. There is authorization server that keeps client id and client server. But why /auth/token endpoint needs another authentication? So mobile app needs to provide 3 different credentials - user credentials, client id and secret and token endpoint credentials.
Did I miss something? I know that OAuth is only specification and Spring is implementation of it. But I'm under impression that Spring overcomplicates this. And do I need oauth at all since I have only 1 type of resource?
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
configurer
.inMemory()
.withClient(clientId)
.secret(passwordEncoder.encode(clientSecret))
.authorizedGrantTypes("refresh_token", "authorization_code", "password", "implicit")
.scopes(scopeRead, scopeWrite)
.resourceIds(resourceIds);
}
}

Spring Boot OAuth2 when implicit JWT is created?

How can I get details from the OAuth2 SSO Principal into my JWT? (instance of OAuth2Authentication getDetails as OAuth2AuthenticationDetails getDecodedDetails returns null)
I have...
Angular 6 client w/ implicit login as acme client (using angular-oauth2-oidc)
Spring Boot OAuth2 Authorization Server with JWT TokenService configuration w/ 3rd party SSO to GitHub
Auth server is configured with acme as implicit and GitHub client for SSO
Auth server exposes a /login/github
Auth server exposes a /me (protected by ResourceServer config)
When I login...
Angular app redirects to Auth service login
Auth service redirects to GitHub
[User Authenticates]
GitHub redirects to Auth Service
Auth Service initiates a session and issues a token
Auth Service redirects to Angular
The browser token is a proper JWT
Now, when I communicate with Auth Service /me:
Directly, I get a Principal that contains ALL of the details from GitHub (yay)
Indirectly from the Angular application passing the token via Authorization: Bearer ... header, I get a Principal that contains bare minimum OAuth client info for acme client (ugh)
I've tried a custom TokenEnhancer, but the OAuth2Authentication instance is already the bare minimum with no details. And, when the call is initiated from Angular, it doesn't have the same session cookie as when I call it directly (I don't want to share session - I want to put the details in the JWT).
[Update #1]
I tried a custom JwtAccessTokenConverter and used it in both of the #EnableAuthorizationServer and #EnableResourceServer (secures the /me endpoint) configuration classes. However it didn't work. I still get null details from OAuth2Authentication.
final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setAccessTokenConverter(new CustomTokenConverter());
The way Spring Lemon does this is replacing the OAuth2 and OpenID connect user services (see spring security docs). See LemonOAuth2UserService and LemonOidcUserService for details. For statelessness, it passes the client a shortlived JWT token as a param to targetUrl, as you can see in its OAuth2AuthenticationSuccessHandler class. It uses some cookies mechanism for doing all this statelessly, which can be further understood by looking at its HttpCookieOAuth2AuthorizationRequestRepository and how it's configured.
Here is an article explaining this in more details: https://www.naturalprogrammer.com/blog/1681261/spring-security-5-oauth2-login-signup-stateless-restful-web-services .

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.

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.

How does Spring Security/OAuth figure out the AuthenticationPrincipal

I have a spring project that uses spring-oauth2 and spring-security for authentication using an LDAP auth provider.
In controllers I can access the current principal's UserDetails using the #AuthenticationPrincipal annotation.
However, when I hit the endpoint with a client_credential token the #AuthenticationPrincipal is a String which is the OAuth client id. I understand that there's no notion of user when you authenticate with client_credentials, but I would like to have my Principal be a richer datatype. How does spring decide to set my principal as a String and can I override that behavior?
From the Oauth2 specs
The client credentials (or other forms of client authentication) can
be used as an authorization grant when the authorization scope is
limited to the protected resources under the control of the client,
or to protected resources previously arranged with the authorization
server. Client credentials are used as an authorization grant
typically when the client is acting on its own behalf (the client is
also the resource owner) or is requesting access to protected
resources based on an authorization previously arranged with the
authorization server.
because client can also be a resource owner, therefore spring will create authentication based on your client information.
I assume that you have setup org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter which is used to create authentication for the client.
You can create your own custom org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService or create your own org.springframework.security.authentication.AuthenticationProvider to override how the authentication object is created, but I prefer to use org.springframework.security.oauth2.provider.token.TokenEnhancer to add additional information to the token generated.

Resources