Keycloak JWT Validation using Java Spring Security + KC Adapter - java

I have gone through multiple blog posts and StackOverflow questions before writing my own. I have multiple queries and none of the posts answer them.
I am using Keycloak Spring Security Adapter to secure my legacy Spring application. I referred to the keycloak documentation here and was able to have OAuth flow running for me. I am using Client Id and Secret as Client Authenticator.
For eg: Access to localhost:8080/about.htm will redirect me to keycloak login screen and after successful authentication, I will be able to view my page. I am also using the below code to read the user details from the token,
KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) auth.getPrincipal();
IDToken idToken = kp.getKeycloakSecurityContext().getIdToken();
user.setUsername(idToken.getPreferredUsername());
Now when I test this application using postman and modify the generated access token, obviously the server gives an error. Ref : How to test application using postman.
However, this is the flow :
Client sends a request to the resource server, resource server checks for a token - if it exists, the client does the validation. If it doesn’t exist or is invalid, it redirects to the authorization server (KC).
My question is,
Who is validating this token? How does postman flow throw an error
if I fiddle with the token?
Do I really need to write a JwtTokenValidator in my application for
each request? Won't that be overkill?
If I use Client Authenticator as Signed Jwt with client secret, will this validation still be required? I am not using it as it introduces latency.
Please assist.

Answer to #1:
When you use any Keycloak adapters in your application (in your case the Spring adapter for Keycloak), that's the one who does the validation and redirects to the login if necessary. As part of the validation, it checks the signature of the token issued by Keycloak. So when you fiddle with the token, the signature doesn't match, hence it throws an error.
Answer to #2
No, you shouldn't need to implement a JwtTokenValidator. The adapter does it for you and a request should reach your endpoint/URL only if it has a valid token. You may only need to do that if you have a special requirements about validating the token (e.g. checking specific claim in the token against some service). Otherwise, you can safely use the claims in the token you received from the KeycloakSecurityContext. You can even setup authorization based on your URL patterns and Keycloak will enforce them too and allow the request to pass if user has necessary roles (like this example).
Answer to #3:
That option only changes the method used to authenticate your app to the Keycloak and has nothing to do with the user's token validation inside your app. In your current setup, when your app wants to communicate with Keycloak (e.g. to exchange auth code with auth token), it authenticate itself to Keycloak with a client-id/client-secret pair (otherwise Keycloak would not know it's your app and will reject the request).
If you choose the "Signed Jwt with Client Secret" option, your client can not just use a client-secret to authenticate to Keycloak. It should support the RFC7523 specification. So it's quite complex in compare with a simple clien-secret approach. In an environment in which you trust your clients (e.g. they're all known apps developed inside the company and you're not going to support public clients to join your Keycloak and use its services) it's quite common and safe to use client-secret approach.

Related

Best way to integrate openid connect for SPA application

I need to integrate OpenId connect for SPA application, without having token id in the URL, can we do that?
I'm assuming you have some security concerns with having the ID Token in the URL...
I can see two ways to mitigate risks in this case:
Make sure the OIDC provider redirects to your app using URL fragments instead of via the query string. This ensures that the parameters aren't sent to a server where they might end up in the logs, and should already be the provider's default response mode for implicit flows. If needed you can use response_mode=fragment to enforce it.
You could register a "public" client, but still use the authorization code flow to fetch the ID Token from the token endpoint. In this case you do not present a client_secret to the token endpoint (since the client is public). You could consider using PKCE in this flow as well.

Parse ADFS token in Java

I set up login in web application with ADFS.
Authorization request looks like:
https://sso.company.net/adfs/oauth2/authorize?response_type=code&client_id=ruleman&resource=urn:ruleman:1&redirect_uri=http://ruleman.net/authorize
ADFS performs authorization and redirects to the app:
http://ruleman.net/authorize?code=aaaaaaaa.bbbbbbbbb.ccccccccc
One knows that the token from code parameter contains claims such as username etc. How to decode the token and extract the claims?
The Postman flow for this - refer Postman : Authorisation Code Grant on Server 2016 - ADFS 4.0.
This code grant is the flow you have described.
As per the other answers:
Use the authorize endpoint
Get the code
Send the code to the token endpoint
Get the JWT
Use jwt.io to examine the JWT.
The flow follows the OAuth 2.0 standard. Please note I am not expert in ADFS, however I know OAuth 2.0 well.
The authorization flow consists of multiple options with different steps. In your case you are using the code profile (specifying response_type=code). The authorization step you did is only first step, there are a few steps to follow
you can search on "OAuth 2.0 with ADFS" e.g. http://blog.scottlogic.com/2015/03/09/OAUTH2-Authentication-with-ADFS-3.0.html
Authorization request
../authorize?response_type=code&client_id=ruleman
&resource=urn:ruleman:1&redirect_uri=http://ruleman.net/authorize
you will receive an OAuth code (usually not aving any information value, it is only a code)
http://ruleman.net/authorize?code=aaaaaaaa.bbbbbbbbb.ccccccccc
code parameter contains claims such as username etc
This is wrong assumption
Using this code you need to call a token service from backend to receive an access token (e.g. using HttpClient).
POST /adfs/oauth2/token HTTP/1.1
grant_type=authorization_code&client_id=some-uid-or-
other&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2FgetAToken&code=thecode
you will receive an access token. This step ensures you application is really authenticated with the identity provider it knows.
According to the post linked above:
The interesting bit is the itself, it is in fact a JSON Web Token (JWT). That’s to say a signed representation of the user’s identity and other grants.
I am unable to confirm that, but you can try. Usually (with other identity providers) the token is only a token and the client neeeds to call a "user information" service to get any user identity claims, however seems the ADFS gives you some shortcut.
Then you can use any JWT library to decode/validate the jwt token (com.auth0/java-jwt/3.0.1)
com.auth0.jwt.interfaces.DecodedJWT jwt = com.auth0.jwt.JWT.decode(token);

Secure Rest-Service before user authentification

I have a web application that provides several rest services (Jersey). Most of the endpoints are secured by BASIC authentification. Further more I use SSL for transport and demand POSTs for every call.
The clients/consumers are android apps.
So far so good. The only service that seems to be vulnerable is the registration. It's the 'first' service to call and a user does not exist yet. So I cannot use OAuth, etc. I also have to keep the endpoint easy accessible to enable the user to regster.
How do I secure this service, so it's not spammed by a bot flooding my database?
How about these?
Use a registration link with a token in the request parameter. Ensure that the tokens expire after sometime. You could create a token endpoint url as well for a client to get a valid token.
Use a custom header or a dynamic custom header in your request. Additionally, you could check for a dynamic custom header to validate the request's authenticity.
Use registration confirmation workflows, such as an email / text verification as soon the registration is done. Run a process every day to delete any user accounts, which are not validated in say x days.
I do not think you can really secure the registration URL in a HTTP way. IMHO, anyone who has the registration url can be a right guy trying to register. So if you ask me, option 3 is better than others.

HTML5 mobile app security

I'm developing a html5+jquery+phonegap application. Server side is written in java and Spring MVC.And I hope to implement an authentication model as follows.
client signs up using his email which would be used as his userID.
A token is sent to his email.
He is given a screen to enter the token.
That token is stored in the local storage of the client.
everytime the client calls a webservice, his userID and token is sent by the app over https.
Server authenticates him and responds.
What are the options available to implment this kind of security from the server side? can Spring-security be used in this way? I tried to find any implmentation with Spring-security, but couldn't find any implmentation other than basic authentication.
You can use PreAuthenticationProcessingFilter to achieve this requirement, have a look similar case and spring security doc

Secured authentication in web service

I am developing a web service using Spring framework for Java and deploy on JBoss AS. This web service needs authentication and authorization and security solution so that some method user A can execute and some other user B can execute. At client side, there will be an application calling to the web service and people may log in using either user account A or B.
I have been digging out the Internet, searching for web service authentication, researching on WS-Security but all that I can see is using WS-Security. WS-Security generally supplies 4 kinds of authentication:
UsernameToken
X.509 Token
SAML Token
Kerberos Token
But all those things are usually pre-configured and I find no example that suggest I should provide login/logout methods in the web service (by using stateful web service). Note that in case we use login methods then there are security risks even if the underlying is SSL transport.
So my question is:
What should I do to satisfy my requirements?
If using UsernameToken or Kerberos Token ... and we provide some privileges per user, i.e authorization, then for each incoming request, we must get the user information and get all its privileges. This process seems take time and decrease performance of the system. Do you agree? So I guess this is not recommended?
I would thank you so much for any response and will vote for any reasonable answer.
Your scenario mirrors that of EBay Trading API's.
Basically, it works as follow.
Provide a intial WS call (Ebay case: FetchToken) which confirms user's identity and return back authorization key (unique key for each logged in user). Store the authorization key along with user profile information in a cache/distributed cache .
Any subsequent call required client to pass the authorization key along with the data for the call. You will use the authorization key to get user profile information.
Provide the log out WS call. This invalidates the authorization key.
All the WS invocations should happen over SSL for security.
If your service is point to point, ssl is enough. Mutual ssl (Mutual_authentication) is widely used for client authN and authZ.
If you concert about performance of system, looking at SAML. SAML is a signed XML document that contains authN and authZ for client, that means you do not need to loop up on the server for client authN and authZ.

Categories

Resources