Correctly set headers for Laravel 5 CSRF Token - angularjs

Alright, been searching this one for hours and just can't find the start of a solution.
I am using an angularJS frontend with a laravel backend. Restangular is my communcation service.
My POST are fine, because I can include the _token in the data and it will work.
But for Restangular to call a destroy function it looks like...
Restangular.all('auth/logout').remove(); //maps to AuthController#Destroy
All fine, but then you will get a TOKENMISMATCH Exception, which is a good security messure
Since I can't find a way to include the _token into the remove, since it's body-less essentially, I decided to put the token in the header.
RestangularProvider.setDefaultHeaders({'X-XSRF-TOKEN': CSRF_TOKEN}); //CSRF_TOKEN gathered elsewhere
Out of the Chrome dev tolos, I can see the header is set to
X-XSRF-TOKEN:ClkQIRLpFQgMg8ZT6X5CF6doCplRfdJzW8msx2JI
X-XSRF-TOKEN is exactly what the VerifyCrsfToken.php is looking for. Yet, it spits out a decrypt error. Any other token name, such as XSRF-TOKEN, _TOKEN, CSRF_TOKEN all spit out token mismatch.
Because of that last fact, it seems like the header is declared correctly, but something beyond my comprehension is causing Laravel to fail the decrypt. And I've closely at the decrypt function, but don't understand why it'd fail...
Thank you for your help.

This is due to encryption of the csrf token. Laravel expect the token to be encrypted.
It tries to decrypt the the plain token you provide and it fails.
Before you can use the token in the header you have to encrypt it.
$encrypter = app('Illuminate\Encryption\Encrypter');
$encrypted_token = $encrypter->encrypt(csrf_token());
That did the trick for me.
Alex

For Laravel 5, no need to add CSRF token to Angular http headers.
Laravel 5 with Angular do this automatically for you.
http://laravel.com/docs/5.1/routing#csrf-x-xsrf-token

Related

Adding bearer token to swagger requests using swagger-client

I'm trying to add a bearer JWT token to a swagger request upon login of an account but I can't seem to get it working. The documentation leaves a lot to be desired.
const SWAGGER_CLIENT = SwaggerClient(".../api.yml");
const carsResponse = await SWAGGER_CLIENT.client.execute({ operationId: "getCars" }); // I need { Authorizations: Bearer ${token}} here
If it's not possible to add it there then I can always create the client above with the token upon a successful login.
I think the issue is the syntax more than anything. There is virtually no documentation on how to use the .execute() method which is very frustrating. FWIW; I'm using the execute method and passing in tag names to make it more reusable than using the generated functions e.g., getCars(), addCar() etc. I don't know if this is the "right" way to use Swagger but it makes sense to me.
Is is possible to add it globally so I needn't include it in every request? The token will need to be added upon a successful login. It's a CRA application using Redux.
If somebody could explain, or provide a small example of adding the authorization bearer token to the request above that be fantastic and greatly appreciated.
Thanks all.
We will be renaming Try It Out Executor to HTTP client for OAS operations. Thanks for your input!

Angular show error 405 Method Not Allowed when set Authorization header

I am using SLIM Framework (PHP) for Backend and Angular 1 for Frontend.
All APIs work fine until I set Authorization header when user logged in app.
$http.defaults.headers.common.Authorization = token; // Token isvalid
// or
Restangular.setDefaultHeaders({'Authorization': token });
I got the error 405 Method Not Allowed (OPTIONS method). This error from my local, when I deploy Frontend to server, it works fine.
Should I fix on Frontend or Backend? And please help me how to fix it?
Thanks for your help :)
OPTIONS is CORS preflight request. You need to enable CORS support. One way to do it is to use CORS middleware.
i do not know if any body still interested in this topic
but i am going to tell you my approach
i added CORS Options to web config file in my api project and then add
[HttpOptions] attribute to my api method and then it started working
i do not know if it is the right answer or not but until i find the better solution i am going to user this approach

Node API and Angular App - Understanding Storing JWTs in Cookies

I've built an API with Node.js/Express which I'm currently using alongside my Angular app.
For authentication, I have a username/password setup which then returns a JWT which is happily used.
Now, I've been spending some time (and reading such Stormpath articles) I want to use cookies rather than localstorage for storing these JWTs. And thats where my questions begin.
So what I've essentially done thus far is updated the saving and reading, e.g. for saving from $window.localStorage['jwtToken'] = token; to $cookies.put('jwtToken', token);. And for reading, from return $window.localStorage['jwtToken']; to return $cookies.get('jwtToken');
At this stage I was wondering whether someone could help me understand a few bits, kindly correct and inform me of any missing parts of knowledge:
1 - So in addition to the actual saving and reading as above, is there anything else I need to explicitly set - what I think is HttpOnly cookie flag (so JS can't access the cookie data.
1b - Do i also need to update my node API so that instead of returning res.json its doing res.cookie?
2 - Do i also need to set the Secure cookie flag so that its sent via HTTPs. So at present i wrote a simple authInterceptor that attaches a header with each request: config.headers['x-access-token'] = token;. Is this where that secure cookie flag would be set?
3 - So using cookies am i correct to understand XSS attacks are minimised as JS can't touch the cookies however I need to concentrate on CSRF. For this I am thinking of using this CSRF middleware on my node api server side and use this alongside Angulars built in XSRF-TOKEN as described here. Is this a good implementation to follow?
4 - When looking at Chrome inspector, I see the cookie containing the JWT, however the HTTP/Secure/Same-Site are all untucked, also the Expires says Session. Could someone please explain what this means:
Sigh, I think thats it, sorry if its a little long winded. Hopefully others can gain from what we learn here.
Any help appreciated.
Thanks.
If you set HttpOnly $cookies.get('jwtToken'); wouldn't work...
1b. Don't understand the question here...
The Secure flag tells the browser to only include the cookie if the request is an HTTPS request. You can still make HTTP requests, but the cookie will not be included. document.cookie = "name=somevalue;secure"
If you set HttpOnly so that JavaScript can't read the cookie, that's some protection, but if you have XSS, then all bets are off. The injected script could still perform network requests, and do exactly what your code is doing to include the CSRF tokens. You still need CSRF-protection, but in most cases XSS means circumvention of CSRF-protection.
Session means the cookie will be deleted automatically if you close the browser (which people don't really do all that often anymore).

Angular Satellizer removing JWT from local storage when expired?

I am using Satellizer along with Ionic and Laravel with JWT-Auth for the API.
I am trying to get refreshing tokens working but I think Satellizer is causing me issues.
If I have a token TTL of 5 minutes and log into my app the token is stored correctly. However, when 5 minutes pass and I try to use my app again the token is removed by itself from local storage.
I have searched the Satellizer code but cannot see where this happens, as even if the token has expired I still want to send it in the header so I can resend back a new one.
Any information on this? Thanks.
You are looking for:
https://github.com/sahat/satellizer/blob/master/satellizer.js#L375
I suppose
As far as I can see there seems not to be an easy workaround for this, except for changing package code and doing a pull request. I would suggest adding a config variable to SatellizerConfig like deleteTokenOnExpiration and only delete it if it is set to true, if it is true as default, all tests should pass.

Adding auth token to default headers vs. using $http interceptors

I've been diving into authentication between Angular and Express, and decided on using token auth with JWTs and the npm jsonwebtoken package. I've got everything set up on the server side and am receiving the token on the client side, but now I need to know how to make it send the token with every request.
From what I've found, most resources out there say to use an $http interceptor to transform every outgoing request. But people at work have always used $httpProvider.headers.defaults.common["Auth"] = token in a .config block, which seems a lot more straightforward to me. Here's a blog explaining how to do it both ways.
But the accepted answer on this stackoverflow post says it would be better to use interceptors, but he doesn't give a reason why.
Any insight would be helpful.
After a bunch more research and a conversation on Reddit, it seems like the best way to do it is through the interceptor. Doing the setup in the .config or .run blocks may be good for checking if the user is already authenticated when they first load the app (if there is a token in local storage), but won't be possible for handling dynamic changes like logging out or logging in after the app is loaded. I'm pretty sure you could do it through the $http default headers, but might as well just do it in one place.
Hopefully this helps someone in the future!

Resources