So I've been trying to create token based authentication in Java EE lately and I tried to sent token via HTTP Header, but failed so many times.
My question : If I have for example #POST response method and I set header via return response statement
return Response.ok(entity).header(HttpHeader.AUTHORIZATION, authToken).build()
Then I invoke other method that was binded to ContainerRequestFilter and in this filter I try to access header via ContainerRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION) then should it work?
Will I get the value from that header that was set in response method? If not then what should I do to get value of this header in filter method?
The Authorization header(or any other header) must be included by the client in each request
Your client should get the token from the server response, keep it in a secure storage and set the Authorization header when performs a request. Then, with RequestContextFilter your server will be able to recover it
Related
I have a problem with sending API request via postman or Java lib "io.restassured".
When I do the same action on UI the request returns correct response, but when I try the same thing via postman or java code I get:
401 Bad request Your browser sent an invalid
request.
The java code
public static void main(String[] args) {
String requestUrl = "exampleBaseUrl/app/reports/api/rest/v1/graphs?context=shipper&reports_type=freights";
Response response = RestAssured.given().relaxedHTTPSValidation().header("x-csrf-token", "18ea65e740eb0ddddadf0ef435d92564").
when().
get(requestUrl);
}
I assume something is wrong with the authentication, because in dev tools i can see a Get request for CSRF_token, and it looks like this:
the endpoint for the token:
/login?get_csrf_token
and for this request I get following response:
{"csrf_token":"18ea65e740eb0ddddadf0ef435d92564"}
I am not sure how to solve this, I have also tried to get the token via java code by sending a get request to the token's endpoint /login?get_csrf_token
and this one gets my a HTML response with empty username and password input.
Error 401 means your request isn't authorized.
For authorization, usually while logging in you are given a token, which you will have to keep in your cache/local-memory and whenever you communicate with the server you have to add that in your request header (for your own introduction to the server)
It seems like in your case you can get a token from /login?get_csrf_token after logging in. Note that you don't need authorization for a login service.
Now, after getting token from the server, how to add it as a request header? See REST Assured Documentation
This is my first encounter with a JWT token and I'd like to know how is this token returned to the client after it's first created.
Should it come in the Authorization : Bearer header ?
Usually, it's the client that passes the token in Authorization : Bearer header on each request.
I'd like to know how does the server pass this token to the client after user has authenticated and the token gets created. Also in the same header? In a different header?
In my situation, the server will be generating the token not as a response but as part of the request.
For example:-
A user will login to a portal, then click on a link to an authorized application. The JWT containing user claims will be passed to the authorized application as part of the request.
What is the best approach here? GET or POST? Header (which)? Query string? POST body?
Thank you!
there is no standard for how to return JWT token to the client, however, check this URL, it answers your question
https://github.com/dwyl/hapi-auth-jwt2/issues/82#issuecomment-129873082
putting the JWT token in the Authorization header gives us flexibility to send an actual response in a web application. For a REST-only App/API you are free to send the JWT as the response body or a cookie. What matters is how the client stores the JWT and sends it back to the Server, which is done in the Authorization header (or Cookie or URL Token if you prefer) 👍
As for this existing in the "wild", I have not seen an example of the server sending an Authorisation header to the client, but there is nothing in the spec to suggest this is an anti-pattern.
see: http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html
If you want to stick to the guidelines you would do follow this example: http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#ExAccTokResp
One may be interested to know that the OAuth 2.0 standard specifies the response body for that purpose:
5.1. Successful Response
The authorization server issues an access token and optional refresh
token, and constructs the response by adding the following parameters
to the entity-body of the HTTP response with a 200 (OK) status code:
access_token
REQUIRED. The access token issued by the authorization server.
[...]
So after reading lots about BasicAuth, OAuth, JWT... etc. i came up with this question.
I have a client where some ppl can log in (Authentication is done). When ppl want to do an api call they use the clients GUI and the client is sending some requests to the a webservice endpoint.
host/resources/{id}
//id=path, res=post
public Response updateResourceById(String id, Resource res) {
....
So a typical update call could be
POST host/resources/1234 -d={ some json for a resource }
Now i don't want every user to have all rights for every reosurce, so i would
need to add some info about the user who is doing a request.
For this i was thinking to use some JSON Token with some payload (or any user info at all). But i was wondering how to send this token correctly in a RESTful API.
My first idea would be to change the code to something like this:
//id=path, token=post
public Response updateResourceById(String id, Token token) {
...
The endpoint would not change only the POST data.
Would this be correct or are there other approaches?
Edit: Also possible would be sending the Token via HTTP Header.
Sending credentials in HTTP
In HTTP, the credentials should be sent in the standard HTTP Authorization header.
Have a look at the RFC 7235, the current reference for authentication in HTTP 1.1:
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.
Authorization = credentials
[...]
Please note that the name of this HTTP header is unfortunate because it carries authentication data instead of authorization. Anyways, this is the standard header for sending credentials.
In a token based authentication, the tokens are credentials. In this approach, hard credentials such as username and password are exchanged for a token that is sent in each request to identify a user.
It never hurts to say that you should use HTTPS when sending sensitive data, such as credentials, over the wire. HTTPS will protect your application against the man-in-the-middle attack.
Reading the authentication token in JAX-RS
You can read the Authorization header in a JAX-RS application as following and then check if the token is valid:
#GET
public Response myMethod(#HeaderParam("Authorization") String token) {
...
}
However, a better approach would be using a ContainerRequestFilter, keeping your endpoints leans and focused on the business logic. For more information on token based authentication and on how to use a ContainerRequestFilter, have a look at this question.
I'm learning how to build RESTful web services using Spring 4, and one thing I'm not clear on is in #RequestMapping. I've seen examples where one uses headers = "Accept=application/xml" and other examples using consumes (or produces) = "application/xml".
For instance, in my own #RestController class, I have this function...
// POST
#RequestMapping(method = RequestMethod.POST, headers = "Accept=application/xml")
public User create(#RequestBody User user) {
LOG.info("User = " + user.toString());
return userService.create(user);
}
What is the difference between using headers = "Accept=application/xml" vs. using consumes = "application/xml"? Or even using headers = "content-type=application/xml"?
Could someone explain the differences between headers and consumes/produces, and when each is used?
SHORT ANSWER
In the example you have above, using headers = "Accept=application/xml" or produces = "application/xml" will both respond to the client the same way i.e. send a response to the client with XML representation.
LONGER ANSWER
i. Headers
For RESTful web services, the client (e.g. your browser) sends a request (e.g. GET, POST, etc.) to a server, and the server will send a response back. This is an HTTP Transaction. Both the request and response have HTTP header fields ("headers"), which define the operating parameters of an HTTP transaction (I will refer to the headers for client request as "request headers", and these differ from headers from server response "response headers").
As part of the request your browser sends to server, there are different request headers and some examples include Accept, Connection, Content-Length etc. and each of these headers have their own function (see a full list of headers here: https://en.wikipedia.org/wiki/List_of_HTTP_header_fields).
Using your code example, if a client does a POST request, Spring will check the request header(s) and if it finds a header Accept with a value of application/xml, it will map the request to the create method you have above (and in your case the server will return an XML response representation to the client).
Let me modify the headers element in the code you provided:
#RequestMapping(method = RequestMethod.POST, headers = "Connection=keep-alive")
public User create(#RequestBody User user) {
...
}
Notice the headers element now has a value of Connection=keep-alive. If a client does a POST request, Spring will check the request header(s) and if it finds a header Connection with a value of keep-alive, it will map that client request to the create method above.
ii. Produces and Consumes
If you used produces="application/xml" for the create method, this means a client request is only mapped to the create method if the client's Accept header matches application/xml. This essentially is the client saying, "Hey server, I prefer to accept your response in XML representation, so send your response to me in XML". Effectively, the produces="application/xml" is also the server saying, "Hey client, I can only produce responses for you in XML representation, so I will send you that format".
Link to Spring documentation reference.
If you used consumes="application/xml" for the create method, this means a client request is only mapped to the create method if the client's Content-Type header matches application/xml (the Content-Type request header describes the representation the client request is coming in). This essentially is the server saying, "Hey client, I can only consume requests in XML representation, so send that format to me".
SUMMARY
The headers element within the #RequestMapping annotation can take different request headers (Accept, Connection, Cache-Control etc.), but the produces element is only concerned with the Accept request header and the consumes element is only concerned with the Content-Type request header.
As the javadoc of HeadersRequestCondition (which handles the value provided in the headers attribute of a #RequestMapping annotation) states
Expressions passed to the constructor with header names 'Accept' or
'Content-Type' are ignored. See ConsumesRequestCondition and
ProducesRequestCondition for those.
So don't use those headers in headers. Use the produces and consumes attributes for Accept and Content-Type.
As to how to use them, the documentation gives examples: for consumes and for produces.
Right now i'm using java to build rest service, and trying to use spring security to securing my service.
I have a few parameter that server needs to process the service (ex: application ID, username, password, consumer ID) . For username and password, I put in on http header "authorization", encoded with base64. Is there a way to put another parameters above (ex. AppID, consID) into http header?
Some sample of code would help, thanks.
You can put whatever you want in a whatever header you like. You can create custom headers. So you can have a App-Id header where you pass the appId. Alternatively you can pass those as parameters in the URL. That way you'll get rid of the option that some (stupid) proxy trims your headers.
Btw, I would suggest not to send the password, unless you are using https. Generally, I can recommend two similar scenarios:
use OAuth - let the user grant access to the API client via the OAuth dance. The client ends up with a token which it uses on each request.
use a custom, simplified token scheme - login once (with username and password, over https), and send a short-lived token in response. Each subsequent request can be made over an unsecured connection by providing the token, and (optionally) some HMAC of the request parameters, using a consumer secret as a key, so that you can verify the client is legit.