spring boot security jwt access additional information in controller - spring

I'm currently using OAuth with the password grant type to manage the security of my Spring Boot application. Now I want to store a login id which is queried by the auth server from the database when the client has successfully requested an access token.
To realize this I thought of passing it with the JWT. I used a custom TokenEnhancer in combination with a TokenChain to add the additional login id, which works fine. My problem is that I couldn't find a way, other than parsing the token myself, to get that login id.
Another, but a very bad solution could be to just pass it as authority.

Related

What is the best way for implementing keycloak sso with existing spring-boot gateway service?

We're currently using jwt token based authentication in spring gateway service, where we generate token by providing username and passwords, then token is generated with required attributes.
Planning to integrate current login flow along with keycloak sso using IDP for this instance let's say azure-ad.
What would be better way to implement it, keeping the flow in sync with normal credential flow for generating JWT tokens at gateway?
As of now, We've tried the flow where user is sent to IDP's login screen, login event is captured on keycloak and sent to custom event handler (SPI), SPI fetches user attributes and generates token from project's user database and adds to keycloak specific db if it's not there.

What is the advantage of providing a Tokenized Authentication in an application with Spring Boot Backend over SecurityContextHolder?

I was getting started with Spring Boot and Angular 7 and I came across user authentication.
Let's assume the following: I have a frontend with Angular 7 and a Backend with Spring Boot that offers API's that can be accessed via HTTP.
So I know that usually the frontend authenticates the user with e.g. JWT that stores all necessary information about the user that might be needed. But I came across the SecurityContextHoler of Spring Boot Security:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
This allows me to simply access granted Authorities and so on. So I thought about the following:
Using JWT for the frontend grants the following advantages (as far as I know):
* Users can identify when using API's
* Users may be prevented from certain UI-Elements (based on roles stored in JWT)
* Modification prevention due to checksum (invalid token afterwards)
Now I could also add a check in my Controller in the Backend that checks the SecurityContextHolder for user permission (something like a Service that checks the current context permissions vs the needed permission and returns true/false). Wouldn't that be even more save, since it is in the backend (so in my inmagination everything that runs server-sided is always a little more save than what runs client-sided)?
I can store information in the frontend (like roles and a username) to use them for the UI-based-access prevention to still have the same advantages as JWT provides, but I do not have the "effort" of implementing the JWT creation.
But obviously it is not common to do it that way (at least I never saw it), so what is the advantage of the Tokenization?
They are not mutually exclusive. You would use what you call "Tokenized Authentication", like an oAuth2 Bearer token most likely in a JWT when the Authentication is performed by a separate system from your Spring Boot backend. For example, you may be using Okta, Keycloak, Google or Facebook to authenticate the user.
At a minimum, your Spring Boot backend stores the username extracted from the JWT in the Authentication. You can get Spring Boot to extract any roles in the token and add those to Authentication::grantedAuthorites. If your backend system, has it's own set of roles in addition to what's in the token, then the backend could implement a PrincipalExtractor to load a UserDetails object for this user from the database as the Principal and merge the roles in the token with those store in the local database.
You'll probably want to security certain methods in your backend with method security annotations like #PreAuthorize(), since you shouldn't trust the front end. The method security will check permissions, like hasRole("ADMIN") or hasPermission(object, 'READ') using the Principal object in SecurityContextHolder.getContext().getAuthentication();
In the end, the token assures the backend the user accessing it is who they say they are, i.e. Authentication, but does not necessarily tell the backend what they are Authorized to do. Yes, if you control the Authentication server you can include roles in the JWT, but roles don't usually provide as fine a grained control as is required.
Independent of what level of security you implement, the token is translated into an Authorization so you can use the Spring Security framework to manage access within your backend code.
There are 3 type of token in spring security OAuth2:
1. InMemory token Store
2.JWT token store
3.JDBC token store
So now you’re talking the JWT token store. The most powerful of JWT token store is prevent the authorization server load against to the database for checking such as role,token expired so it is related database load performance. Since all the information such as: role,username, token expire ,etc include in token itself. So the authorization server or other resource sever may using the public key to verify this token itself without invoke to data store.
Hope helpful! ☺️

How tune correct login for entity with spring-secuity, oauth2?

I created an entity with crud operations.
I have used spring-boot, spring-security, oauth2, jwt.
By this article http://sivatechlab.com/secure-rest-api-using-spring-security-oauth2-jwt/
Why do I need to create the table oauth_client_details?
When I want to login, first I need to enter login and password from oauth_client_details
And after that enter username and password for my user
How should I tune login for my entity and receive a token after success login?
If you use JdbcTokenStore, you need to setup oauth related table in database. In my template project, I use JwtTokenStore for oauth2 stateless.
So, you don't need any oauth related table. Here complete spring-boot-rest api sample project. You can reference the following thing
spring-boot
mybatic with mysql
ExceptionHandlerAspect
LoggingAspect with log4j2
ResponseBodyAdvice
ResponseEntityExceptionHandler
spring-security-5 with oauth2
Run DB.sql for database setup in src/main/resources.
When I want to login, first I need to enter login and password from oauth_client_details
If you use oauth, you have to know your application structure. Oauth2 have the following flow -
Authorization Code Grant
Implicit
Client Credential Grant
Password Grant
In my application, I use Implicit because of - We have
Server REST API (spring-boot)
Web Site (client)
Mobile App (client)
Customer/User (Actual User)
So according to oauth, client(web site or mobile app) need to authenticate itself.
Otherwise, you cannot get access_token. Read more here.

spring boot oauth2.0 and spring security: How to grant permission(authorities) to user login via facebook or slack

I have an auth server built using spring boot oauth2.0 and follows david_syer model.
My auth server does following -
Let user login via third party oauth provider like google or let user create his account on our server using username and password and generate token.
So, when user uses external oauth like google to login then I simply store the token and pass the same(google) token to my UI app for accessing resource api servers. I have an authentication filter that verifies token and allow api access.
When user uses username and password to get token we store user and his permissions and generate a token for him. Now UI uses our auth servers generated token to access resource api servers.
Now my question is
Is this the correct way of using token from external api and using the same to access our resource api server?
And how do I add authorities to user who are signing up using 3rd party oauth provider since I don't add user entry and authorities for them?
So, spring security which loads user and user authorities (loadUserByUsername() from UserDetailsService) will not have any thing if user came from eternal provider.
I have a suggestion for step 2:
After the user uses the google authentication, and gets redirected back to your application page, do the claims transformation on your server and generate your own token issued by the identity server that you have.
The reason is you will be able to provide specific claims and the claims names does not necessarily required to match up.
That way you keep verifying your own token all the time on the client app. So lets say the user uses Facebook instead of Google and even in that scenario as you will assign your own token, you need not to verify the token coming from different third party Identity servers.
That way, your identity server trusts Facebook, Google provided token and your application will trust only your identity server so your app doesn't need to know about what IDP is issuing the token.
And with the approach I suggested above, you will be able to even modify the claims for the user on your own and don't have to depend upon the third party identity server to provide claims.

External OAuth2 integration with own OAuth2 spring server

I'm trying to integrate Facebook OAuth2 authentication with my own OAuth2 server. Just to be clear the scenario is the following:
I have a OAuth2 Server that is responsible for authenticating our users. I implemented a custom AuthenticationProvider that checks for the credentials provided and builds a UserDetails object if successful.
I also have a rest-api that is also a ResourceServer (runs in a different application). So users after being authenticated they can access our rest-api providing therefore the token.
The token information is shared using JDBC.
Everything works fine as expected, but now I want to add external authentication providers such as Facebook.
My question is: what's the best way to do this? What's the expected flow? From the top of my head I would imagine something like:
User authenticates with facebook
Facebook provides a token
User sends the token to our OAuth2 server
I check the token validity with facebook
I authenticate the user using the authentication provider
The server gets back to the user with a new token issued by my OAuth2 server which the user will use from now on to ask for resources
Is this right? If so, how can I send the facebook token to my OAuth2 server? Is there some kind of standard? Should I make up new parameters for that? For instance I will be needing some way to differentiate facebook authentications from user/password ones.
Am I suppose to use my own AuthenticationProvider to validate this facebook user? It seems strange then return a UserDetails object that doesn't have a password...
Also, how to register users and auto log them in? Do I have to expose an endpoint of my own or is there some OAuth2 magic for that as well?
Any thoughts?
Facebook has some very good documentation on this with the correct flow and how you should handle the process.
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2
You are on the right track, and I think the facebook documentation should help clear up any questions you may be having.
Additional Information is here:
https://developers.facebook.com/docs/facebook-login/v2.2

Resources