Set and check token 'Bearer xxxxx' in body instead header - laravel

I'm using Laravel and use Tymon\JWTAuth for authentication.
As we know, when user login successfully, we will set the token to the header and when user call other api, Laravel will check it in header: "Authorization: Bearer xxxxx" by default
My spec is: in body I will pass the token with param: "token: Bearer xxxx", so I wonder if I could check the token in body and how to do this. It is my current spec and could not be changed to move to header, please help me

You can create a middleware to check the Authorization property inside your request body, see the docs here. Inside that middleware, you can check whether the token sent is valid or not.

Related

How to resolve unauthenticated issue in Postman GET Request

I used Laravel-8 for rest api. The route is shown below:
localhost:8888/myapp/server/api/v1/admin/role
It is a GET Request.
When I send it on POSTMAN, I got this error:
401Unauthorized
{
"message": "Unauthenticated."
}
In my route I have:
'middleware' => ['auth:api']]
The reason is because I don't know how to add the Login details. email: akwetey#gmail.com, password: mypass
How do I achieve this?
Thanks
This person walks you through the process nicely and should get you setup.
https://coding-lesson.com/api-authentication-with-laravel-passport/
Basically you need to:
Get to your login api, probably something like: localhost:8888/myapp/server/api/v1/login
Create a POST request to the login API, select the Body tab and define key values for you Email and Password
Then run the request and copy the AccessToken value from the results
Now with your API above, select the Authorization tab, choose Bearer Token as the Type and paste in your AccessToken value for the Token field
You should also go to your Headers table and define Accept and Content-Type keys, both with values of: application/json
Of course you'll want to then change all this to use variables after you get it right, so you don't have to keep repeating this with all your new API calls.
To fetch data behind protected routes you need to provide a token that will verify that the user who made the call is authenticated.
Then you have to provide the token in Authorization section of postman.
I assume you know the difference between Post and Get. Laravel works a little different then regular PHP, let me tell you how.
In order to access the protected routes you'll have to first access the token from login route. By sending the required data in .
Once that's done it'll return the token which can be used to access the protected routes under admin or auth middleware.
In your case you're accessing localhost:8888/myapp/server/api/v1/admin/role which is a protected route under admin middleware. You'll have to first access token and then send token with the get request to fetch the required data.

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

JWT auth in lumen

I complete Login With Token Generate Like This
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0L2x1bWVuL2F1dGgvbG9naW4iLCJpYXQiOjE0NzUwNjAwMzMsImV4cCI6MTQ3NTA2MzYzMywibmJmIjoxNDc1MDYwMDMzLCJqdGkiOiIwOTFjYWNhZGRlODQ1NjNhMzc4M2JkM2EwNDdkZmM3YSIsInN1YiI6M30.VjXTSkzrmzTQSTZvp3VxlWacL8VHyM8XBUa5db8GOOI"
But When i Run api with jwt.auth middleware it give response
{
"message": "Token not provided"
}
How I can solve it
Are you sure you are providing the token in the headers properly as specified in the JWT documentation?
You need to send the Authorization header followed by Bearer TOKEN.
So the final result in your case would be:
Authorization : Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0L2x1bWVuL2F1dGgvbG9naW4iLCJpYXQiOjE0NzUwNjAwMzMsImV4cCI6MTQ3NTA2MzYzMywibmJmIjoxNDc1MDYwMDMzLCJqdGkiOiIwOTFjYWNhZGRlODQ1NjNhMzc4M2JkM2EwNDdkZmM3YSIsInN1YiI6M30.VjXTSkzrmzTQSTZvp3VxlWacL8VHyM8XBUa5db8GOOI

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

Missing CSRF token in REST request

I'm writing a REST API using Spring MVC. I'm trying to access a controller method via a POST request.
I always receive a 403error:
Invalid CSRF Token '' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
How can I deliver a CSRF token within my REST request?
I tried to use the default security password which is displayed during application startup as the value for _csrf but it wasn't successful.
How can I retrieve the CSRF token and is it correct to send the token in the _csrf parameter?
You will need to provide the correct header and CSRF token when making the request e.g.
request.setRequestHeader('${_csrf.headerName}', '${_csrf.token}');
You can also send the token as a request parameter using _csrf.parameterName.

Resources