Adding bearer token to swagger requests using swagger-client - reactjs

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!

Related

Next.js and Nest.js authentification

I have a project where I use Next.js on the front-end and Nest.js on the back-end.
I want to use a JWT authentification method via email and password.
My question is:
What is the best way to implement an authentification for Next.js with custom Back-end.
I'm sending API requests through redux-saga to get some data from back-end.
For me the Set-Cookies from the back-end not work. It's not applying on the client browser.
For now my possible solution is to create a custom axios instance and somehow do the Auth check there.
But I'm sure there should be a better solution, thanks for help!
For now my possible solution is to create a custom axios instance and somehow do the Auth check there.
Yes. This is the correct way of going about it. Give the token to whatever you use for queries and let it handle it for you.
You have a number of different ways of achieving this.
Provide it via a side-effect
Whenever a login event happens, run a side-effect to configure your axios instance to always send the newly acquired token with each request
Set the token in your cookies or localstorage and let axios retrieve it for each request
Set the token in a context and only make requests through that context with a hook

How to send POST login request to a rails api-only app using React?

I have a working rails RESTful api-only app.
I use Postman to consume that api. Now, to use the api the user have to login to http://localhost:3002/authenticate first by setting content-type to application-json in Header then Email and Password's value in body. After sending the POST request to the server I get auth-token as a json response. Then after successful login I have to pass that auth-token as a Authorization key in each GET request to get respective data.
Now, I want to build a UI for that back-end api as I learn React js. But till now all tutorials I could find was how to send GET requests without any authorization factor. And they are using axios, redux etc.
Can any-one please guide me on where should I start or how to
approach this problem?
Do I necessarily have to use a third-party library for this purpose?
If so which will be better axios or redux??
Any beginner friendly tutorial link would be of tremendous help
How start
Securing React Redux Apps With JWT Tokens - Rajaraodv explains how you get a jwt token and how to keep it in the front end app. I think this way will fits for you.
Keep the auth-token
Rajaraodv uses localStorage to keep the jwt token, you can use the same or keep directly in redux store, it's your choice, the best manner that fits you.
Ajax call
You can use Axios to make Ajax calls, or use fetchApi from the browser as Rajaraodv did, it's up to you.
Explains
"If so which will be better axios or redux??" these two libraries are totally different, each with it's own purpose.

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

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!

Correctly set headers for Laravel 5 CSRF Token

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

Resources