Is this use-case supported for Spring Security 5, or something else, where we don't have to reinvent the wheel? Thoughts on how to (re)implement this better?
Details are as follows. 3rd party vendor supplied endpoints. We pull info from upstream source then forward to the downstream vendor. Only 2 APIs are required:
Request Access Token
Save Info
Both are actually being called via a gateway. We've been given specifics:
(A)
The token request requires Basic Auth (standard header - usual base64 encoded). Gateway User and Gateway Password are provided.
Credentials for request token are provided to us:
Grant Type = password
Consumer Id
Consumer Secret
Account User
Account Password
It responds with an access token and few other details we don't really care about and of zero value to our use-case.
There is no expires_in info in the response. But I've tested it multiple times to know it does expire. Not sure how long right now, I could do more tests to determine that.
(B)
The save request requires a different custom header for the same Gateway User / Password, then a Bearer Authorization header in the call to the Save Info API.
Right now, all implementations for above are using RestTemplate. Working fine already. But a token is requested for each save which is costly. Before writing any caching, or some other logic to wait XY minutes before another token request is made, I would appreciate any other options which may already be possibly handled via Spring-specific libraries or further advise on how to handle this scenario.
Apologies if this is not the right place to ask this, or it has already been asked before. Been searching for a similar use-case but can't seem to find one.
Thanks.
Try any one of the option
You can use OAuth2ClientContext which stores your access token.
final OAuth2RestTemplate restTemplate=new OAuth2RestTemplate(resourceDetails, clientContext);
You can create session & store your token & user details inside it.
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, null,null);
SecurityContextHolder.getContext().setAuthentication(authToken);
from option 1 Or option 2 you can then fetch existing token for each request at your Filter e.g. PRE_AUTH_FILTER
Then check if token expired - if yes request new token Or call refresh token
Check Oauth2 expires_in in below :-
https://www.rfc-editor.org/rfc/rfc6749?
In Spring, to verify the user credentials, 'authorization' header is used. Usually, user name and password are encoded using some algorithm(commonly base 64) and passed in this header. But, validating user name and password comes under authentication, does n't it? It means, this 'authorization' header is not appropriate. It should have been called 'authentication' header.
Read https://howtodoinjava.com/spring-boot2/security-rest-basic-auth-example/
With OAuth the Authorization header is used to send a JSON Web Token (jwt).
This token is the result of a authentication process and holds user's data like username, the issuer of the token and roles like admin. It should never contain sensitive data like password. Furthermore the token is signed by the issuer with a rsa key.
Spring uses this token for authorization. The signature is verified, so no one can claim roles by creating a fake token.
The roles eg can than be uses grant/deny access to certain methods.
This article shows an example application that might help you understand the concept:
https://www.baeldung.com/rest-api-spring-oauth2-angular
I have some questions regarding an API JWT refresh token workflow using Java Spring.
I have this so far:
User logs in to /users/login - if successful a response with 2 headers is returned Authorization and Refresh. Which contain 2 tokens - one with short 30 mins expiration and one with longer 4 hours expiration.
He can then access all other endpoints using the Authorization header.
If at some point accessing an endpoint his token is expired he receives an error (UNAUTHORIZED).
And has to do a request to /token/refresh with the refresh token he was given.
Questions:
I have set it up so authorization token has a claim: type=auth and
the refresh token has a claim: type=refresh. What is the best way to
distinguish the two tokens.
What should be the error in step 3 (instead of unauthorized) to distinguish it from a request without a valid token
/token/refresh doesn't ask for authentication currently. Should it?
Should the /token/refresh endpoint be a POST with header, POST with parameters or a GET with header.
What is the best way to distinguish the two tokens.
Refresh token does not have to be a JWT at all. I prefer to simply generate a random alphanumeric string. Refresh token does not carry any additional information. It requires a lookup to database to confirm validity of refresh token. You distinguish them by where they appear in your request. Authorization token (access token) should appear in a header of your choice.
What should be the error in step 3 (instead of unauthorized) to distinguish it from a request without a valid token
Sending 401 Unauthorized is exactly the way to do it. 401 tells the client, that he cannot access the resource now, but he can take actions so that he can access the resource again (login/refresh token). 403 on the other side would tell the client, that the resource does not belong to him and he will have to ask for permissions, e.g. by contacting an admin
/token/refresh doesn't ask for authentication currently. Should it?
No, there is no need for authentication.
Should the /token/refresh endpoint be a POST with header, POST with parameters or a GET with header.
Generally a GET endpoint should be read only and not mutate any resources. POST and PUT endpoints are intended for mutations. In this, I'd use a POST with parameters and a dedicated URL, e.g. /token/refresh
I am writing a REST client in Java using the HttpCLient , the REST API that I access needs an auth token for every REST action. This token is valid for 24 hours.
The way I am handling this now is calling a "getAuth()" method everytime I need to make a REST call which seems like an overhead on the auth server.
How can I conveniently store this auth token and manage its life cycle?
Are there any documented best practices?
I thought of the following solution
public class MySession {
String user;
String pass;
public MySession(String user, String pass) {
this.user = user;
this.pass = pass;
}
public getAuth() {
//user user, pass to get auth token
}
}
and then pass the sessions object to any class that nees the token. If the token is expired, just call this method again
For brevity I'll assuming you're calling an endpoint that you can't change. How you should implement will heavily depend on whether the token is app or user based (one token for all users on a shared app instance or one token per user).
If it's one auth token for the entire app:
Store it in memory along with a time-to-live timestamp (or alternatively catch the token expired error, request a new token and retry the original request), refresh it if it doesn't exist/is expired
If you're concerned about re-requesting API tokens after an application restart also store it in the database and load it at startup if it exists
If it's one token per user:
Store it in your user session, it's exactly what sessions are used for, if you're authing users then they'll have a session and the overhead is already there
If you don't want to re-request a token everytime they login store their current token in the DB and and load it into their session when they login
I'm assuming you are using OAuth for authorization. Whether you are using JWT or other tokens is irrelevant to this situation.
When performing authorization you will be issued an access_token with an expiration and, depending on the grant type you are requesting (Client credentials, Authorization code, Implicit, Resource owner), a refresh_token.
The client should keep the access_token and the expiration. The refresh_token, if issued, must be kept secret (beware of using the correct grant for your use case).
In subsequent calls, your client should not request new tokens on each call, it should use the stored access_token.
Once the API starts returning 401 Unauthorized, the access_token has probably expired. Your client should try to refresh the access_token using the refresh_token if you got one.
If you have no refresh_token or the refresh request also failed, because the refresh_token is no longer valid, you can perform a new authorization flow.
You can use the expiration time as a clue to know when to get a new access_token either through refresh or through a new full authorization flow. This will avoid the 401 Unauthorized. In any case, your client should have a fall back policy when this response is received after having used a valid access_token for some calls.
You can create a manager and store the auth-cookie during login in thread local like the code below. You can get the cookie from getAuth() as long as the thread lives.
public class Manager {
private static final ThreadLocal<String> SECURITY_CONTEXT = new ThreadLocal<>();
public static void setAuth(String auth) {
SECURITY_CONTEXT.set(auth);
}
public static String getAuth() {
return SECURITY_CONTEXT.get();
}
public static void clear(){
SECURITY_CONTEXT.remove();
}
}
I suggest you to use the following scenario:
1) First, call auth(username, password) rest api to get the auth token.
If the given credentials are okay then just send back the auth cookie to the client with HTTP 200 response code.
2) Then, you can call protected rest apis. You need to send auth cookie with your request each time.
3) Servlet filter (or something similar) checks each incoming request and validates the token. If the token is valid then the request goes forward to the rest method, if not you need to generate an http 401/403 response.
I suggest you not to write your own authentication layer. Instead of install and use an existing one. I suggest you OpenAM. It is a superb open source access management system.
I also suggest you not to open session on the server side for authentication purpose. If you have 10 clients then 10 sessions needs to be managed by server. It is not a big issue. But if you have 100 or 1000 or millions different clients than you need more memory to store sessions on the server.
If you are worried about too many hits to the database, then i'm assuming there is a lot of web activity.
I would not recommend using Session in your case, but rather store the token in a cookie on the client.
In a high traffic environment(which i'm assuming yours is), the use of Session can consume a lot of server memory, and scalability can be a concern as well, having to keep sessions in sync within a cluster.
As #Cássio Mazzochi Molin also mentioned, you can use an in-memory cache to store any user specific data and tokens. This will reduce the hits to the database, and also allow you to scale the application easier, when the need arises.
The de-facto standard is not implementing your own solution (basic rule in security: don't implement your own stuff!), but use the de-facto standard solution, namely JSON Web Tokens.
Documentation on the site, but the basic idea is, that you only need to store one value (the server's private key), and then you can verify every claim, issued originally by the server (which will in your case contain an expiry time).
You should use JsonWebToken (JWT in short) for this kind of stuff. JWT has build in support to set the expiration date. There are plenty of libraries to use this method and you can read more here
There are currenlty 4 java implementations and all of them can check if the token is still valid (exp check)
So if I'm understanding correctly you are using the same token for all of your requests (which means as long as your app is up and running and you refreshing the tokens, you should be ok. I literally had the same problem and this is how I've resolved it. I have a singleton class, which is initialized at the app start for once and refreshes the token when its invalidated. I'm using C#, Asp.NET MVC5 and AutoFac for DI, but I'm sure you can do the same with Java and Spring.
Updating property of a singleton with Thread Safety
Use json web tokens , to exchange information between two clients. The token will only alive for the 24 hours period, after that time all consequent calls in the header will be rejected.
Auth Token for each request is correct approach, Consider auth server scaling for performance issue.
On first successful authentication (username and password), generate private public keypair. Store private key as Session Security Token (SST) and send public key as Public Security Client Key (PSCK) to client
In all request other than login (or authentication) client will send PSCK to protect theft of username and password and server can verify PSCK for expiry internally at regular intervals saving processing time.
If system is having performance issue on authentication side, setup seperate auth server with scalability.
No token or password to be cached, exchanged unencrypted and send outside security zone. Do not post using URL parameters.
Current Scenario
A Spring project have REST API's protected using Spring Security and JWT. These API's produces JSON response. A UsernamePasswordAuthenticationFilter is implemented for validating JWT sent in Authorization header. Both authenticated and unauthenticated API's are working as intended.
Requirement
Now I need to sent an image in HTTP response for logged in user.
Solution1
Sent a byte[], representing the image as the value to an "image" key along with other information.
But, this may take some time for the full JSON response, if the image is large.
Solution2
Sent a link as the value to an "image" key along with other information. The client can assign <img src=the_link>, which will supposed to fetch the large image in a separate request. Then create a request with #RequestMapping, corresponding to that link, which produces a byte[].
My Problem
I prefer Solution2. But it will produce UNAUTHORIZED exception as there is no valid Authorization token. Also, this API must be authenticated.
After some search, found out this, which is the same as my requirement. The accepted answer says,
The OAuth Bearer Token spec supports sending the token as a query parameter.
Is this what I must do?
In my Spring filter, get JWT from Authorization header, if it is
empty, get it from request.getParameter()
In JSON response of first
API, send "image":"http://ip/getImage?token=dbscsbCXV"
Create an API #GetMapping("getImage") byte[] getImage()
Or is there any better approach?
Please guide me.
Your suggestion to include the token in seems to be okay, if you:
Use HTTPS for your server, otherwise the JWT token in the request headers are expose (same goes for the Authorization headers).
Don't mind the image URL no longer working, when the token changes
Another approach may be to generate a random key with sufficient entropy (eg. combine 3 UUID's into a single string) and store this along with your Image entity, returning it from your REST services, eg:
https://ip/images/824b6854-edcc-11e6-bc64-92361f0026713567fef0-549a-4cdb-9264-5e15166dfd6f/the-file-name.pdf
Make sure you disable the Spring security filter for these "public" paths.
Advantages of this approach:
No need to check authentication for this resource
(if the image doesn't change alot) You can have this cached or serve the content through CDN, not hitting your servers every time for just streaming images.
URL will keep working, even if JWT token for auth changes
You might think this is less secure than the using a per-call authentication, but if the ID's have enough entropy, it's waterproof. Facebook also uses this concept (https://www.quora.com/Are-Facebook-pictures-really-private-and-are-they-hosted-on-Facebook-servers, https://en.wikipedia.org/wiki/Capability-based_security)