How to implement Logout feature using jwt tokens in spring boot backend(using rest end points) Implementation - spring

Iam new to spring security and i was going through spring boot jwt and the process but i dont know how to use logout feature through jwt .
For example when a user click logout at after that time using that token we can not access the secured Rest end points.
Now i want is implementation of logout functionality using JWT(Spring Boot Rest Api)that is used in real time projects and the code for it.
Please if any one can provide me the github link to the solution
or can send me the code at
ag.rajat113#gmail.com
and anything related to latest spring security projects real time (Backend)
and also of oAuth2 material please send me i need this
Thanks.

On logout, you can perform the following actions
Remove the token from the client
You can remove the token from Client (Local storage, Session/Cookie). Note that it will not prevent the client access as you removing from only client side and for server, it is still valid Token
Maintain Token blacklist
When a client performs logout action. Add that token to blacklist and for next request check token is in a blacklist. If yes then prevent the access. As you have to check for every request it will be costly for large applications
Short expiry time
If you keep the token expiry times at short enough intervals and have the running client keep track and request updates when necessary, It will be working as a complete logout system. The problem with this method is that it makes it impossible to keep the user logged in between closes of the client code (depending on how long you make the expiry interval).
You can also refer this for Details

Related

Oauth2 and OpenId Connect Implementation

We are trying to implement an application where UI is in angular and backend is in Spring boot.
We need to implement openId and oauth2 in our application.
Backend api's needs to be more secure.
I am just confusing which oauth flow to be used either authorization grant flow and password grant flow.
Can any one suggest me which one need to use in this scenario and why?
Storing tokens in the front end is not recommended. It also distributes token handling logic across FE and BE because BE will have to validate tokens on each request anyway.
Therefore to avoid handling and refreshing tokens in the frontend and to simplify the overall architecture, you can implement authorization code flow in Spring Boot. This will also reduce the risk of XSS exposure in the FE.
You could implement a dedicated endpoint that initiates the flow and receives code from identity server. It then exchanges this code for id token and stores it. Then it creates an HttpOnly, strict SameOrigin session cookie for the front end. From that point onwards all calls to the API inside your Spring Boot will automatically carry this cookie without any additional code on the FE.
To eliminate token storage on the BE, you could even put token inside the cookie. However, the token may be quite large and may need to be broken into chunks. This would not affect FE in any way.
You will need to check token expiry on each API call inside the BE and refresh token in the backend as well. This will keep user session seamless. If token can not be refreshed due to revocation or refresh token expiry, the API would have to return 401 and the FE would need to initiate re-login.

How to manage tokens in a spring boot application?

I'm setting up new Spring Boot REST APIs for already established backend of my application. As a part of this, I have to provide authorization for protected resources on my server after user logs in. User session will be valid if time between last 2 requests is less than specified time. But I am having problem in selecting strategy for managing authorization token as token should expire after that time. Please help.
This is for a new Project on Spring Boot 2 and running on Jboss Application Server. I have tried generating new tokens for every request with expiry set to 30mins after that. But this approach has posed security problems as single user would have many valid tokens with him. Also, I have considered keeping my tokens in a key value store on server with token as key and timestamp as value.
2 Solutions
If you are using custom tokens than save it to the database and mark it as inactive whenever you want. (Not a good way compared to next option)
Use JWT token with an expiry. (Do not create multiple tokens)

spring oauth 2 authorization server app share same security context with another app

I have two authorization server application ( spring boot 2.0.5 ).
The two authorization server application are similaire
When a user ask for a token, spring will register a session for that specific user and give back a token, with that token you can access to the resource of application 1 but you can't access to the resource of application 2.
My question is if there is a way to share the same security context in addion when you generate token from application 1 you can use to access of application 2 resource
What you can do is to make your applications stateless when it comes to security.
What does it mean?
Spring Security will no longer generate a session for a new logged in user. When the user logs in, you will issue him a token (e.g. JWT). Each time when the user accesses secured content, he/she will have to provide a token and your applications will verify that token with a public or private key (depending on which type of token encryption you will use - symmetric or asymmetric). In the end, you will not need to share anything, if both of your applications have same keys to verify incoming tokens.
Some tips:
A token you send upon each request to access secured resources is called "access token". Make it expirable and make it short lived (like 15 mins). Why? This token cannot be immediately invalidated unlike session which can be simply deleted. In case if someone hijacks it, it will be still able to access secured resources.
Since your "access token" is short lived, it would be annoying for a user to logs in every 15 minutes. To prolong its life, you can have another type of token called "refresh token" that can be stored in some database. This token can be immediately invalidated by simply deleting it from the database. Therefore, if someone even hijacks it, user will be able to revoke it and the hijacker will not be able to prolong his session.
References: Stateless authentication with JWT
We are also facing similar problem.
For web pages we are using SSO which cache token in clientContext and using Authorization-server-1
For making call to API-1 we are using token generated by Authorization-server-2. In this case we have create another session bean for clientContext and that is caching token (having its own oauth2RestTemplate and clientCredientialResource)
This is two legged scenario
We doing research, how to use three legged scenario for calling web/rest service, but we were not able to do so, as access token retrieval is two step process (using authorization code) and call back will execute the whole method again and not continue from line after call to rest api

Does custom security HTTP headers violate separation of concerns

Does custom application specific, security related HTTP headers violate separation of concerns, is it considered a bad practice? I realize using custom header to control the service would tightly couple the client with the service implementation. Or in this case, to control the security framework behavior. The context where I planned using the custom header is the following:
We are using token based authentication, where token has a fixed lifetime, and new token is issued each time authenticated client calls the web API. SPA client may call the server with AJAX in two contexts
User action (navigation and submit)
Automatic refresh (current view re-fetches data at fixed intervals)
Now, if user leaves the page open, the session never expires, as new token is generated for each automatic fetch. Somehow, we need to differentiate user action from automatic refresh in the server side, and issue new token only for user actions.
I realize Websocket based refresh would be one solution, but we have decided to stick with timed AJAX call due specific matters. Another solution would be to provide token refresh as a separate endpoint, but this would violate the DRY principle from client's perspective, and would be more cumbersome to setup with Spring Security.
Only remaining option is to embed the user/automated information in the request itself, and using a header seems a viable option here. A presence of certain header would prevent the token refresh. Easy to implement with a few lines of code.
I'm only concerned, if this couples the client too much with the service implementation. Technically, it doesn't couple client with the service, but the preceding security filter, thus leaking security concerns in the user interface. Ideally security stuff should be transparent to user interface, so new client could be coded without knowing anything about security (especially when cookies are used).
In the other hand, this solution isn't destructive or mutative. It's an optional feature. By client utilizing it, security is enhanced, but in either case never reduced (from the perspective of server, as it is). Now the question is, what principles using a optional header to enhance security is violating, and is it a valid solution in this context?
In my option the security should be maximized transparently, but I don't see how to not leak security concerns in the client in this situation.
It sounds like you're using your own home-built custom Token Authentication solution here. This is not a good idea.
I'll take a moment to explain WHY you don't want to do what you're proposing, and then what the better option is.
First off -- the problem that you're trying to solve here is that you don't want a user to remain logged into your site forever if they leave a tab open. The reason you need to fix this is because right now, you're assigning a new Access Token on EVERY REQUEST from the user.
The correct solution to handling the above problem is to have two types of token.
An Access Token that has a very short lifetime (let's say: 1 hour), and a Refresh Token that has a longer lifetime (let's say: 24 hours).
The way this should work is that:
When the user first authenticates to your service, the Access and Refresh tokens are generated with their respective timeouts.
These tokens are both set in HTTP cookies that the client-side JS cannot access.
From this point on, every time your user's browser makes a request to your service, you'll parse out the Access token from the cookie, check to see if it's valid, then allow the request.
If the Access token is no longer valid (if it has expired), you'll then parse out the Refresh token from the cookie, and see if that is valid.
If the Refresh token is valid, you'll generate a NEW Access token with another 1 hour lifetime, and override the old Access token cookie with the new on.
If the Refresh token is invalid, you'll simply return a 301 redirect to the login page of your app, forcing the user to manually re-authenticate again.
This flow has a number of benefits:
There is a maximum session length, which is technical (duration of Refresh token + duration of Access token) -- aka: 25 hours in this example.
Access tokens are short lived, which means that if a token is somehow compromised, attackers can't use it for very long to impersonate the user.
What's nice about the above flow is that it is a web authorization standard: OAuth2.
The OAuth2 Password Grant flow does EXACTLY what you're describing. It generates both types of tokens, handles 'refreshing' tokens, handles the entire thing from start to finish in a safe, standards-compliant way.
What I'd highly recommend you do is implement an OAuth2 library on both your server and client, which will take care of these needs for you.
Now -- regarding the tokens, most OAuth2 implementations now-a-days will generate tokens as JSON Web Tokens. These are cryptographically signed tokens that provide a number of security benefits.
Anyhow: I hope this was helpful! I author several popular authentication libraries in Python, Node, and Go -- so this comes from my direct experience working with these protocols over the last several years.

Spring4 Security - how to secure restful api with access token only, no login required

I have met a seemly easy, but actual pretty difficult situation for me, hope you can help.
WE need to provide secured rest api, but we have difference service, for example, authentication service, execution service. I now need to secure execution service.
I am using spring4 boot to boost, it seemed natural that using spring security, and then provide a customer userdetail service,but then when I start implement it, I met this big problem.
ExecutionService is not responsible for login purpose, so it won't provide a login form and consequently, it won't save token at all. What it needs to do is only checking header info, if it sees token in the header, it will use some decode algorithm to decode that token and then check if user is qualified to continue to not.
In all the posts on line regarding spring security, it all require a token storage, that means, user login first and then save token in memory, and then when user comes again, just check that token.
Can anyone help me to figure out,
1) how to use spring security to check request header info;
2) when see token in header, use a customized function to check validity of that header and then authenticate the user based on the checking result?
Thanks in advance

Resources