In lots of descriptions the first step is that user tries to acces a resource on server something like
https://fhirblog.files.wordpress.com/2014/06/oauth2sequencediagram.png
Now i got a Rest API with severel endpoints:
GET /server/resource1
DELETE /server/resource1/{uuid}
GET /server/resource2
...
implementation looks something like this:
#DELETE
public Response deleteResource(
#ApiParam(value = "The id", required=true)
#PathParam("uuid") String uuid,
#Context SecurityContext securityContext)
throws NotFoundException {
Until now i have implemented an apikey which is passed by header into the api and a filter that verifies teh apikey.
Now i want to implement a full (three/two legged) oauth 2.0 flow. But i am now wondering about the first step.
So Question is:
Do i have to add a mechanism on each endpoint that verifies if the request has a token? and if not redirect the request to an auth endpoint?
(Also
Can i send the Tokens in the HttpHeader or do the Tokens have to be in the Body of the Request?)
Or:
Do i have to create just one endpoint that does the token stuff and in my other resource endpoints i only verify if the token is valid?
Okay here are the explanations,
Do i have to add a mechanism on each endpoint that verifies if the request has a token? and if not redirect the request to an auth endpoint?
This question has two parts, so i will explain it separately for better understanding,
Do i have to add a mechanism on each endpoint that verifies if the request has a token?
Yes, in general the endpoints would be an APIs, so you need to setup middleware or interceptor or filters, to check to see does this endpoint need authorization if so check access token, if valid then proceed with request, if not return 401 Unauthorized as Http response, for example:
All request to /server/* must be accessed with access token, then you need to setup filter for those paths and check the access token,
if not redirect the request to an auth endpoint?
No, if access token is not provided or invalid or expired any case, you need to return Unauthorized http response like below,
Status Code:401
{"ok":false,"errors":[{"code":"unauthorized_request","message":"unauthroized request, access token either invalid / expired"}]}
here its json response, but any format works
So while the client make http request to access the endpoint, they need to pass the access token in HTTP Header like below,
Authorization: Bearer {access_token}
Do i have to create just one endpoint that does the token stuff and in my other resource endpoints i only verify if the token is valid?
Yes, you need to create an endpoint like /auth (typically called Auth Endpoints) to handle the authentication process, code exchange, refresh, revocation etc.
Then all other resource endpoints should just check token and process the request, and these endpoints wont take part in token management process
Related
I am consuming an API with OAuth1.0 authorization. I want to make call to that API with the authorization Oauth header:-
I have created the authorization header from the token/key received from the server using- (ConsumerKey,keyalias and password) and want to send back the token or the OAuth header with the call.
I have did all these things in a Processor(Class implementing Camel Processor) and now want to do:-
Either call the rest API with this Oauth header(of type String) in the processor itself.
Else send this header in exchange and get this value in camel's to() endpoint and then in it call the REST API.
Thing is i just want to make rest a call in processor with Oauth header.
And then if possible try to access the header in to() endpoint and make the call.
You can set the Authorization header in your processor and then send the REST request with .to()
public void process(Exchange exchange) throws Exception {
String token = //your logic to get the token
exchange.getIn().setHeader("Authorization", "Bearer " + token)
}
.to("your/rest/endpoint")
Camel automatically copies over the message headers onto the outgoing message.
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.
Is there a way to get access to the request parameters in a custom com.google.api.server.spi.config.Autenticator?
I would like to authenticate my users using a token, sent as a request parameter according to https://<mydomain>/_ah/api/v1/myapi/endpoint?token=<mytoken>. Unfortunately, in this case, it is not possible to send it as a request header. Currently, I manage authentication in each endpoint (where I do have access to the request parameters, either through the HttpServletRequest object or through a named parameter) but it would be nice to decouple auth from implementation.
As I understand, Cloud Endpoints will wrap the original request in a new POST request to /_ah/spi/... but only the request headers will be accessible in the Authenticator.
It doesn't matter if the initial request to Cloud Endpoints is GET or POST.
Your understanding is correct--your request is translated such that all query parameters are injected as part of the JSON body as well. I believe the body does have the query parameter, but I'm not 100% sure on that. If you upgrade to the new Endpoints Frameworks beta, you can access it using getParameter or getParameterValues on the servlet request, as you would expect.
I am writing a Restful webservice method,which require authorization first...
such as a findItems method..which need username and password in Http Authorization
the sample code:
#GET
#Produce(MediaType.APPLICATION_JSON)
public String findItems(){
...
}
how to verify the http authorization before the method excutes...
I use a user-type and role-type control with a basic JAAS authentication. After authentication, the client makes http GET requests to the REST web service. In my Facade get method, I inject the #Context SecurityContext as input parameter, and use if for user / role identification in order to provide the correct answer to the GET request, depending on the user's role.
See here for an example of what I mean:
Using JaaS with Jersey on Grizzly
you can use Filters so you can check the authorization