How to get the access token sent in as header with Autentication Basic in Springboot - spring-boot

I have completed my most of the project but now I am stuck with a new problem. I have to extract the access token from the request which will be in header in Authentication Basic. This is confusing as first I used a simple GET method and was sending the access token in the request itself and extracting that with the use of #RequestParam. I have asked a similar question before but that was for the simple request from the request itself and now I have to do that from the header.
#GetMapping("/persons")
public String loadPersons(#RequestParam("access_token") String access_token) throws ParseException{
String decode_token = pd.testDecodeJWT(access_token);
String token = pd.jsondata(decode_token);
........................ More Code........................
I want to get that token from the request in Authentication Basic format.
I have tried some YouTube tutorials but as I have already done my project almost completely, I want to make minimum changes to it so that no further errors pop up.
Thanks in Advance

To get the value from the HTTP header , you can use #RequestHeader("headerValue") .
But what your question confuse me is that you are using Basic Authentication or JWT ? Basic Authentication is only about username and password and is nothing to do with the access token. It requires a HTTP header with the format :
Authorization: Basic <credentials>
where <credentials> is Base64Encode(username:password).
On the other hand , if you use access token formatted in JWT , the common practise is use Bearer in the "Authorization" header :
Authorization: Bearer <JWT>
So whatever you use , my advice is to use #RequestHeader("Authorization") to get value of the Authorization header first .Then decode the value according to your actual authentication mechanisms:
#GetMapping("/persons")
public String loadPersons(#RequestHeader("Authorization") String authHeader) throws ParseException{
//decode authHeader
}

Related

Getting Weird Invalid Token Error Message At Postman

I'm trying to connect to an API of a website using Token Authorization in Postman.
So the URL that I'm trying to connect is a GET URL that goes like this:
https://seller.digikala.com/api/v1/profile/
And then at Postman, I set the Authorization type to BearerToken and copied and pasted the token.
And Headers is also set to Content-Type of application/json:
But I don't know why I get this error:
{
"status": 401,
"message": "Invalid token!"
}
I also test the token at the jwt.io website and it says: Invalid Signature!
So the question is, does the website provide me a wrong and invalid token (because I just copy and paste it and no chance of entering an incorrect token)?
What are the other ways for authorizing this token and how can I get the proper response?
BearerToken is not always JWT
BearerToken is a type of Authorization Header, you can pass to an http endpoint.
BearerTokens can have multiple token_type, like:
jwt,
api_token,
...
the BearerToken is not always jwt, it can have multiple algorithm.
the 12|xxx format is like api_token
Note: one of the signs if you want to know the token is jwt, if its
format is url encoded string with 2 dots, (xxx.yyy.zzz) its a chance
that it would be JWT token
Validating JWT
in the jwt.io you should provide the digikala.com public key to validate the signature.
It said invalid token, because you haven't provide, digikala
public key
but as decoder showed up, the token you have provided is a jwt token with payload data of :
{
"token_id" : 970,
"payload" : null
}
TD;DR
I guess you can access if you login again and try new token

oAuth2.0 - Fitbit does not return auth code (attributes cannot be empty error)

Ive been struggling with implementing the Authorization Code Grant flow for the Fitbit API. Ive set up the WebSecurityConfigurerAdapter, and I get correctly redirected to the Fitbit /oauth2/authorize page, where I can give permission. However, when I allow my application access, it says the following: authorization_request_not_found. Also, the url does not include a code.
I cannot really find good documentation on how to implement the next step using Spring Boot.
It would be greatly appreciated if anyone could point me in the right direction. Thanks
Stack:
The problem is in access token request. Following authorization code grant flow you need to set authorization header to basic. Your client_id and secret concatenated with a colon and encoded to Base64 will be your basic authorization header value.
You can find more info in official docs: Access Token Request
Implementing this in spring security is quite simple. Just follow this tutorial:
Custom Token Request
Convert method of CustomRequestEntityConverter class should look like this one below:
#Override
public RequestEntity<?> convert(OAuth2AuthorizationCodeGrantRequest req) {
RequestEntity<?> entity = defaultConverter.convert(req);
MultiValueMap<String, String> headers = entity.getHeaders();
String authorization = Base64.getEncoder().encodeToString(BASIC_AUTHORIZATION.getBytes());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setBasicAuth(authorization);
httpHeaders.addAll(headers);
return new RequestEntity<>(entity.getBody(), httpHeaders, entity.getMethod(), entity.getUrl());
}

send api_token through header instead of query parameter

I am trying to build APIS in laravel 5.6, and for api authentication I am using laravel basic API token authentication.
For get request or post request, I need to pass api_token in the query parameter. Is there any way where I can pass the api_token in the header instead of url string?
I followed Laravel - Send api_token within the header .
For GET endpoint, my api url is like this
http://localhost:8000/api/category-list?api_token=YDYsOgkSIOWDdE1NG3Ih1yCkciatOPvtpF1gXTmy8GL1r72mcDEgNDkkZ5jh&Accept=application%2Fjson
For POST my parameter are like this
As you can see, for get I need to add the api token in the url, and for POST I need to add in the body.
If I add the api token in the header, it says unauthorized access.
Header setting where authorization does not work
When you send api token through header the name of the header should be Authorization not api_token.
Also prepend the type of token Bearer to authorization header.
So finally the header should look like:
Authorization: Bearer aEzKClugYHJQsr6If48i1y24KneTT7YwMtNrri7JNhGyEIbJv6YP5SrsFXx2

django-rest-auth token authentication on client side

I have implemented Token Authentication in my api. When I send a POST request with user credentials, I get back the token. But I can't seem to figure how to implement client side logic to use this token. I mean do I store it somewhere?
From Django Rest Framework Docs
For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b1
So indeed, you need to store somewhere on the front-end.
You can read more about where is best place to store tokens here and here.

How do I send spring csrf token from Postman rest client?

I have csrf protection in spring framework. So in each request I send csrf token in header from ajax call, which is perfectly working.
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
In ajax
beforeSend: function(xhr) {
xhr.setRequestHeader(header, token),
xhr.setRequestHeader("username", "xxxx1"),
xhr.setRequestHeader("password", "password")
}
I haven't any idea to generate csrf token and include in header section of Postman Rest Client ? Would you please help me to send csrf token from Postman Rest Client?
The Easiest way to do this consistently so you don't have to get the token each time:
NOTE:you need to install PostMan Interceptor and activate it to have access to the browsers cookies
Create a new environment so environment variables can be stored
Create a login method with a test to store the XSRF cookie in an environment variable, in the test tab post this code
//Replace XSFR-TOKEN with your cookie name
var xsrfCookie = postman.getResponseCookie("XSRF-TOKEN");
postman.setEnvironmentVariable("xsrf-token", xsrfCookie.value);
EDIT
For anyone using the 5.5.2 postman or later you will also have to decode the cookie, and they have also provided alternative ways to obtain cookies as #Sacapuces points out
pm.environment.set("xsrf-token", decodeURIComponent(pm.cookies.get("XSRF-TOKEN")))
Now you will have an environment variable with xsrf-token in it.
Save your login method
Create the new post you want to create and in the headers add your XSRF-Token-Header Key, and the environment variable in handle bars to access it{{}}
Now before running your new request make sure you run your login, it will store the environment variable, and then when you run the actually request it will automatically append it.
I am able to send REST with csrf token by following the steps below:
The CSRF token generated automatically by spring security when you logged in. It will be shown at the response header.
The CSRF token can be used on subsequent request by setting X-CSRF-TOKEN with CSRF token on header.
Firstly you need to install PostMan Interceptor and activate it to have access to the browsers cookies.
You have to fetch the CSRF Token by making a GET Request:
Header: "XSRF-TOKEN" and Value: "Fetch"
You should see the Token in the cookie tab and can copy it (Notice: You can configure spring how the cookie should be named. Maybe your cookie has another name than "XSRF-TOKEN". Attention: You have the remove this blank char in the token from the newline)
Now make your POST Request and set the header to: Header: "X-XSRF-TOKEN" and Value: "Your copied Token without blanks"
For me works variant with adding X-CSRF-TOKEN to headers.
Please put X-CSRF-Token as key and FETCH as the value in the GET request header and you will receive the token in the response header
If you don't want to configure environment variables etc. here is the quickest solution
https://stackoverflow.com/a/49249850/3705478
I've used csrfTokenRepository() to allow spring security to generate csrf token
#EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
// your code
}
}
After adding these lines of code, use GET request to generate csrf token. I've used postman and I got token in the response cookies section. Copy the token and use it in POST call.
Official documentation link :
https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html

Resources