How to call REST API with Oauth Header in Apache Camel? - java

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.

Related

How to send Response or status of request using springboot-rest api

I have two rest webservice in my applcation as below(using spring-boot rest api)
1- public void processRequest(Request) - This is asynch webservice to process the request, This will return id of request to client with acknowledgement.
2- public Response getResponse(jobid) - This webservice should return the response of the request generated by ProcessRequest.
here i want to send the status if request is not ready yet.
Is there any way to achieve above requirement?

Spring boot Client to invoke REST API secured by OAuth2

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.

Can I access request parameters in a custom Google Cloud Endpoints Authenticator?

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.

OAuth 2.0 - first step details, can someone clarify?

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

How can i preserve the request headers in error response prepared through JAX-RS ( Apache-CXF implementation) ExceptionMapper

I am implementing JAX-RS using apache CXF. I have created an ExceptionMapper to handle bad requests like this:
public class ClientErrorExceptionMapper implements ExceptionMapper<ClientErrorException> {
#Override
public Response toResponse(final ClientErrorException exception) {
return Response.status(Response.Status.BAD_REQUEST).entity("Invalid request: Invalid URI.").build();
}
}
I am not sure how this works internally but i suppose that framework would throw an exception in case user is making an invalid request and this handler will prepare an error message to be send back. My problem is that i wish to preserve some custom headers that user sends in the request, so that i send that back with the response. But using this exception mapper, i cant see any option to get the original request headers. I can set any new header in the response, but i wish to preserve the request headers - like i do in a normal request.
So is there any way in JAX-RS where i can preserve or efficiently refer to the custom headers in current request ?
What we have resorted to is using a thread local variable to save the RequestContext when the request arrives and then in the ExceptionMapper we can obtain request specific information.
Ugly but it works. I think we have a generic filter in the filter list that catches all requests before dispatch.

Categories