I have two services.
service1 generates one token and passes to client,
client receives token,
service2 receives toekn from client,
Now how to check token generated by service1 is same as token received by service2
Sign the token digitally using some pre-defined keypair for which the public key is known and trusted.
If the token you describe is for authentication, you are best off using an existing library such as apache shiro or picket-link. Coding this yourself is unlikely to be secure unless you put in a lot of time and effort.
Related
I am trying to write a client in spring which would invoke a REST api secured by OAuth2.
I have the following which i can use to get a token from Auth Server and then invoke a resource server.
Client ID, Client Secret, Username, Password and Access Token URL(URL to fetch the token from) , and Resource URL.
How do i write a client in spring boot which has above info so i could invoke the resource server URL to fetch my resource or do a POST.
After i get the access token which would have a Time To Live in ms(TTL), how do i cache it so i do not have to generate the token for every request. Is it good to cache the token ?
You can use declarative rest client - feign spring-cloud-starter-openfeign
for consuming the service and for cacheing the Spring cache to cache the access token.
Tip : call the access token and cache it and resume it in the subsequent calls.
Once the endpoint throws unauthroized exception or the token becomes invalid, then the retry mechanism in the feign client can make another call. To implement the retry, you need to have "spring-retry" as one of the dependency.
If you are using JWT tokens, the time-to-live is encoded in the token.
You can store it in local storage
You can store it as a cookie
You can store it in the browser session
You can implement an arbitrary way of storing your token
Where you supply your token is up to you.
It could be at any stage of communication (request parameter, header, on-demand).
I would suggest to do it like below using CloseableHttpClient
Put details like clientID, user creds, access token in the header of the Http call
Use CloseableHttpClient class -> execute method and pass the header along with URL.
Parse the response and extract the details
Store the retrieved token with either using Spring cache as mentioned by #Sivaraj or you can use a table to store the value along with a timestamp and fetch this value for next calls.
I am consuming a secured Restful Service that grants access through Basic Auth (Username and Password). I have successfully accessed the API service and consumed its API; however, I am still confused as to what is the right way to implement HTTP headers with Basic Auth. I would assume I should authenticate only once, but the way I have constructed my code, it looks like I need to authenticate API with each service method I create.
Should I create a helper method with the authentication and call it on each service?
If you are using Basic Auth you need to always include credentials with your request. In case of OAuth, tokens have expiry. In this case, a token caching mechanism for the duration of a little bit less than the expiration duration would do the trick.
The Basic Auth is a kind of no status authentication. That means the server wouldn't record. Every time you need to provide username and password with your request. Each request is equal to the Server.
For another authentication called OAuth, the first time you request with username and password, the server will return a token to the frontend, which has an expiration period. So, you request every time with the token through the filter, where checks the expiry of the token. If it's not expired, using the same token for requests, otherwise, making a request to get another token.
For a few reasons I cannot use refresh tokens on client, is it possible to implement RemoteTokenServices on ResourceServer so that it checks the token is not revoked on auth server, but get auth information like user details from JWT-token itself, not from authentication server, like default implementation does using uuid tokens?
upd: this question is not duplicate, it's about JS and general
approach, I'm fine with approach I explained, I wonder if and how I can implement it using spring boot and spring security.
JWT consists of three sections:
Header #info about used algorithm
Payload #contains data, this one is important in your case
Signature #basically a hash of the first two items on this list
You should read about Payload (and JWT itself) here https://jwt.io/introduction
Long story short, you can include public data in the payload. If it comes to the mentioned RemoteTokenServices - sure, you can do that but I'm not sure if it's a good idea. You could just add public expiration-date (or expires) property to the payload.
Also, take a look at this: https://jwt.io/
I'm talking about the case when these two are separate apps. I'm not interested in merging them in one app.
So, in a authorization server we extend AuthorizationServerConfigurerAdapter class and in resource server ResourceServerConfigurerAdapter and in both we create exactly the same beans like JwtAccessTokenConverter, DefaultTokenServices etc. but mostly I don't get why do we need TokenStore in both.
Does this mean that we store for example in memory the same token in different applications?
What's the best approach to remove this code duplication? Create a library for common classes? Make request to auth server to validate the token? But how are we going to extract more info from JWT token if we don't have the decoding logic in resource server?
Does this mean that we store for example in memory the same token in different applications?
https://auth0.com/learn/json-web-tokens/
This is a stateless authentication mechanism as the user state is never saved in the server memory. The server’s protected routes will check for a valid JWT in the Authorization header, and if there is, the user will be allowed. As JWTs are self-contained, all the necessary information is there, reducing the need of going back and forward to the database.
What's the best approach to remove this code duplication? Create a library for common classes?
If you use a symmetric key:
#Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
return converter;
}
JwtAccessTokenConverter, DefaultTokenServices etc will be identical beans in both resource server and authentication server, so you could have a common project for both with the declarations of these beans, and add them as a dependency in both projects.
But, if you use an asymmetric KeyPair, the beans declaration changes completely and they couldn't be the same.
You can see more information about this difference here:
https://www.baeldung.com/spring-security-oauth-jwt
Make request to auth server to validate the token?
JWT's main advantage is not having to do that.
But how are we going to extract more info from JWT token if we don't have the decoding logic in resource server?
If you use a symmetric key, you can decoding logic in resource server.
The best way to resolve this case in the microservice system - is to create some entities: API composer, authorization service and business services.
Base mechanism of this scheme is:
Firstly, you separate your requests with unauthorized and authorized with a token header. Usually, it's named something like "X-AUTHORIZATION-HEADER" or anything like this. In this header, you put your JWT-token and send it on the server's gateway, which role is performing 'API Composer' - It's some kind of router, which accept requests, and delivery them to the appropriate recipients.
In particular, API composer accepting a response, parsing headers, finding the appropriate header with a token, and sending it to Auth Service and receiving a response with user or error. And in this scheme, you need entities like JwtAccessTokenConverter and else only in Auth Service
Then, aggregated response payload will be complete, your API will send the response to the client.
I use this scheme when I developing my microservice systems, for me it's working fine.
Hope, I correctly understood your question and my answer is will help you) Best Regards.
As restful service stateless, it don't maintain any interaction of user, so i want to know if multiple user accessing same restful service, then how restful service identify which user interact with which method ? and is it possible to make restful service as stateful ?
Which user:
By using a shared secret (a line of chars), created on the server, and returned with every next request.
It's "saved" in a cookie and returned by the client, using either a cookie or a HTTP(S) header.
Which method:
This depends on the framework you use. But eventually it comes down to mapping URI's to your methods.
and is it possible to make restful service as stateful ?
You can make stateful apps, then they are not restful. A restful app is stateless. That's the definition, so you can make stateful apps, but you can never create a stateful rest-app, as rest is stateless.
tl;dr
The client must store its own session state and pass it around to the server in each request.
The stateless constraint
The stateless constraint of the REST architectural style is define as follows:
5.1.3 Stateless
[...] each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. [...]
Authentication
If the client requests protected resources that require authentication, every request must contain all necessary data to be properly authenticated/authorized. See this quote from the RFC 7235:
HTTP authentication is presumed to be stateless: all of the information necessary to authenticate a request MUST be provided in the request, rather than be dependent on the server remembering prior requests.
And authentication data should belong to the standard HTTP Authorization header. From the RFC 7235:
4.2. Authorization
The Authorization header field allows a user agent to authenticate itself with an origin server -- usually, but not necessarily, after receiving a 401 (Unauthorized) response. Its value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested. [...]
The name of this HTTP header is unfortunate because it carries authentication instead of authorization data.
For authentication, you could use the Basic HTTP Authentication scheme, which transmits credentials as username and password pairs, encoded using Base64:
Authorization: Basic <credentials>
If you don't want to send the username and password in each request, the username and password could be exchanged for a token (such as JWT) that is sent in each request. A JWT token can contain the username, an expiration date and any other metadata that may be relevant for your application:
Authorization: Bearer <token>
See this answer for more details.
According to my point of view Restful web service make as a stateless.it's architectural style which have set of constraints and properties so stateless is its properties we cannot change its properties so its doesn't mean that restful service is stateful .
we can mapped URI's to your method then restful know which user is calling which method.