Recommended methods for jwt to kick people offline - spring

I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
I once used a method:
When generating the JWT token, add a fixed parameter as the salt generated by the token. If you want to kick a user offline, you only need to regenerate the value of the salt, and then verify the salt generated in the interceptor every time Whether the token is consistent with the token passed by the client! It can be judged whether this token has been hacked.
However, this method still stores certain data on the server side, which violates its statelessness. Is there any better way to implement it?

JWT's are not a great option when you need the ability to end a user session or log them out. In order to do that you need to track some sort of state.
https://developer.okta.com/blog/2017/08/17/why-jwts-suck-as-session-tokens
You can take a hybrid option though, and use a "stateless" option (JWT validation) for less critical operations, and do some sort of a "stateful" validation for others:
https://developer.okta.com/blog/2020/08/07/spring-boot-remote-vs-local-tokens
This post might not be what you are looking for, as this is more about a client validating tokens issued from an IdP, but it shows using JWT's for "read" requests (GET, HEAD, OPTIONS), and remote validation (OAuth 2) of the token for all other requests.

Related

Spring Boot JWT - How to implement Refresh Token and Logout REST-API

We decided to switch from Basic-Auth to JWT because of the session-ids that were stored in the memory and which leads sometimes to over-memory consumption in shoot-down of our Spring-Boot server that serves an Android mobile app like Twitter.
But we have some questions about JWT for our mobile use-case:
How long should an access token lives ?
How long should the refresh token lives ?
How to logout a User by invalidating his access-token and refresh token ? (For the logout we already delete the tokens on the mobile app side, but what if the tokens have being stolen by somebody and are still valid ?)
I will try to answer your queries
How long should an access token live?
You can easily configure expiry time so it depends on your requirement.
In general, try to keep it short.
How long should the refresh token live?
Above goes for refresh token with a condition that refresh token generally lives longer than access token for obvious reasons.
How to logout a User by invalidating his access-token and refresh token?
This part can be a little tricky.
You cannot manually expire a token after it has been created. So, you cannot log out with JWT on the server-side, as you do with sessions.
Can implement a few options like
When a user performs logout action or compromised. Have a blacklist which stores invalid tokens until their initial expiry date. You will need to lookup DB for every request but storage should be less as you will be storing tokens that were between logout & expiry time. You can make the blacklist efficient by keeping it in memory instead of DB.
Store Client IP Address in the claims objects JWT. When validating the token you can check with this client's IP address if it is the same source or not. You can refine it based on need like use User-Agent along with Client IP.
Worst of all reset user credentials or JWT token components to generate a new one which automatically invalidates all existing ones.
Adding a few links for more in-depth detail
Invalidate JWT Token
Destroy JWT Token
I mean it looks more like you should just be using sessions.
JWTs are not a simple replacement. They have a specific function and for some reason they have become embedded as some sort of automatic go to for any auth system.
From what you have described (the lifting of a basic auth to a more secure and modern auth system) you should be using sessions.
Good ol' Cookie sessions.
I'd go in to why more but to sum up:
A) You can control the session without odd stick on "banlist" tables and extra architecture for the JWTs for users that are banned/logged out for a system that doesn't actually need these if you just used traditional cookie based sessions.
B) They are tried and tested and the browser will keep them safe! Session cookies can be made "secure" and "http-only". There are many odd places people put JWTs including the local/session storage of a browser just waiting for a naughty js injected advert to suck them up. JWTs,just like SessionIDs, should
be in an Http-Only, Secure and Same-Site strict Cookie.
So you may as well just use a session ID and get on with life without strange front end state management when the browser is quite happy and doing that securely for you when using a Session Cookie.
C) Traditional sessions are easy to implement. Harder to understand how/why they work with all the SameSite/HttpOnly/CORS/Secure parts going on...but to implement when once understood is 99x easier and require less code when there is the Spring Framework already doing that 99% for you.
I mean sure it isn't hard to write your own JWTAuthTokenAuthFilter and implement a JWTAuthenticationProvider and a JWTCreationService and a `JWTAutoRefreshFilter...and whatever else you dream of...but why bother if you just need a session. Spring does it in like 20 lines of well tested code.
To sum up:
I mean of course properly implemented JWTs are secure...it is just maybe they are not always the best fit tool for a job.
Have a read of:
Stop Using JWTs for Sessions
Of course JWTs have a use. They are for letting a 3rd party know "yes, this is someone I know" before the client hits their API end points. Or for say having one of your servers talk to another of yours...or having client's servers talk to yours or even your servers talk to another companies:
JWT Auth - Best Practices

Best practice checking token validation

I'm currently fiddling with loopback and I was wondering what is the best solution to check if an user is loggedIn.
I can check the validation of the token simply via REST. But I was wondering, if it would be useful to implement an heartbeat. If yes, what would be an good value? For example, check every 10sec if the token is still valid. Or is it better just to check when needed?
This is mostly done by checking the validity of access token provided in request headers for every API. You can then implement an automatic session recovery interceptor at the client side which detects when token expiry error comes in any API and then uses refresh token provided earlier to generate new set of tokens. I dont think it has got anything to do with loopback though. Its mostly on client side implementation.

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.

Blocking specific user JWT tokens?

Say a user logged in multiple times from different devices, and then they decide they want to logout of device a, we have no way of deleting the JWT which was provided to that device right?
Here is what I've implemented, I'm not sure if this is how other sites do it or if it's a decent way of doing it.
User logs in
I create a redis session token, which has the userId + device name associated to it
I store this redis token as the subject of the JWT
I pass back the JWT.
Now that the user has a JWT, they can now access secured api endpoints. Lets say the user wanted to remove this session, here is what I've done.
User fetches * redis session tokens for the particular userId (of course they need a valid jwt to fetch this data)
They choose the redis session token which they want to destroy.
They send that token to a /destroy/{token} endpoint
The jwt which uses that has that token as the subject will not work anymore.
Doing it this way means on each request, I'll have to decompile the jwt, grab the redis token, and see if it still exists. I guess this isn't expensive todo at all using redis, or any other in memory DB.
Is this a solid/efficient way of doing this? Are there any better/easier ways of doing this?
While implementing JWT authentication/authorization in several apps I also had this same question and reached the same solution if not a very similar one:
In my case, I would store the JWT + UserID + DeviceName in the database, and then I would have an HTTP Request
DELETE /logout/DeviceName with a header Authorization: JWTGoesHere.
This gives me two benefits:
I can now logout a user from any device using a valid JWT (it does not need to be exactly the same JWT, it only needs to be a JWT for that user).
Makes possible the implementation of "Logout all sessions except this one".
In terms of speed, the applications we've developed receive hundreds of requests per second.
More than 90% of these requests need to be authorized, which means checking that the JWT is syntactically valid, checking existence against the database and last but not least check if it's expired.
All these checks (using Redis as the database) take less than 10ms.
Bottom line is: Benchmark it, and if it doesn't take really long then it doesn't need any optimization.
Hope it helps!

Securing AJAX Requests via GUID

I'm writing a web app that will be making requests via AJAX and would like to lock down those calls. After a little research, I am considering using some form of random token (string) to be passed back along with the request (GUID?). Here's the important parts of my algorithm:
Assign a token to a JavaScript variable (generated server-side).
Also, store that token in a DB and give it a valid time period (i.e. 10 minutes).
If the token has still not been used and is within it's valid time window, allow the call.
Return requested information if valid, otherwise, log the request and ignore it.
With an eye toward security, does this make sense? For the token, would a GUID work - should it be something else? Is there a good way to encrypt variables in the request?
EDIT:
I understand that these AJAX requests wouldn't be truly "secure" but I would like to add basic security in the sense that I would like to prevent others from using the service I intend to write. This random token would be a basic, front-line defense against abusive calls. The data that would be requested (and even submitted to generate such data) would is HIGHLY unlikely to be repeated.
Maybe I'm wrong in using a GUID... how about a randomly generated string (token)?
If you are doing this to trust code that you sent to the client browser, then change direction. You really don't want to trust user input, which includes calls from js that you sent to the browser. The logic on the server should be made so that nothing wrong can be done through there. That said, asp.net uses a signed field, you might want to go that way if absolutely necessary.
Expanding a bit:
Asp.net tamper-proofs the viewstate, which is sent as a html hidden field (depending on the configuration). I am sure there are better links as reference, but at least it is mentioned on this one: http://msdn.microsoft.com/en-us/library/ms998288.aspx
validation. This specifies the hashing
algorithm used to generate HMACs to
make ViewState and forms
authentication tickets tamper proof.
This attribute is also used to specify
the encryption algorithm used for
ViewState encryption. This attribute
supports the following options:
SHA1–SHA1 is used to tamper proof
ViewState and, if configured, the
forms authentication ticket. When SHA1
is selected for the validation
attribute, the algorithm used is
HMACSHA1.
A link for the .net class for that algorithm http://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha1.hmacsha1.aspx.
Update 2:
For tamper-proofing you want to sign the data (not encrypt it). Note that when using cryptography in general, you should really avoid using a custom implementation or algorithm. Regarding the steps, I would stick to:
Assign a token to a JavaScript variable (generated server-side). You include info to identify the request and the exact date&time where it was issued. The signature will validate the server side application issued the data.
Identify double submits if appropriate.
That said, the reason asp.net validates the viewstate by default, is because devs rely on info coming in there as being handled only by the application when they shouldn't. The same probably applies for your scenario, don't rely on this mechanism. If you want to evaluate whether someone can do something use authentication+authorization. If you want to know the ajax call is sending only valid options, validate them. Don't expose an API at granularity level than the one where you can appropriately authorize the actions. This mechanism is just an extra measure, in case something slipped, not a real protection.
Ps. with the HMACSHA1 above, you would instantiate it with a fixed key
It really depends on what you're trying to accomplish by security. If you mean prevent unauthorized use of the HTTP endpoints there is very little you can do about it since the user will have full access to the HTML and JavaScript used to make the calls.
If you mean preventing someone from sniffing the data in the AJAX requests then I would just use SSL.
A GUID used in the way that you're suggesting is really just reinventing a session id cookie.
"Securing" is kind of a vague term. What exactly are you trying to accomplish? Using a GUID is a perfectly fine way to prevent duplicate submissions of the same request, but that is all.
If the information being passed between the client and server is truly sensitive, you should do it over HTTPS. That's really the only answer as far as securing the actual communication is concerned.
Edit: To answer your question regarding whether a GUID is the "right" way - there is no right way to do what you're suggesting. Using any token, whether it's a GUID or something of your own creation, will not have any effect other than preventing duplicate submissions of the same request. That's it.

Resources