how to store bearer token in cookies in react js frontend - reactjs

I am using React JS for the front-end part of my code. I want to store the bearer token in cookies and then return the bearer token in the content field when the API is called successfully. As I haven't used cookies earlier so want to know how I can accomplish this task. Also the back-end part is not done by me.
Following is the code in which I am calling the API
onSubmitSignup = () => {
fetch('https://cors-anywhere.herokuapp.com/http://35.154.16.105:8080/signup/checkMobile',{
method:'post',
headers:{'Content-Type':'application/json'},
body: JSON.stringify({
mobile:this.state.mobile
})
})
.then(response => response.json())
.then(data =>{
if(data.statusCode === '2000'){
localStorage.setItem('mobile',this.state.mobile);
// this.props.loadNewUser(this.state.mobile);
this.props.onRouteChange('otp','nonav');
}
})
// this.props.onRouteChange('otp','nonav');
}

First of all, on this line:
if(data.statusCode === '2000'){
Are you sure the status code shouldn't be 200 and not 2000.
Secondly, there are packages for managing cookies. One that springs to mind is:
Link to GitHub "Universal Cookie" repo
However you can use vanilla js to manage cookies, more info can be found on the Mozilla website:
Here
When you make that initial API call, within the data returned, I assume the Bearer token is returned too. Initialise the cookie there like so:
document.cookie = "Bearer=example-bearer-token;"
When you need access to the cookie at a later date, you can just use the following code:
const cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith('Bearer'))
.split('=')[1];
And then forward the bearer with the next call.
Edit
Set the cookie bearer token like this:
document.cookie = "Bearer=example-bearer-token;"
Get the cookie bearer token like this:
const cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith('Bearer'))
.split('=')[1];
A cookie is made up of key/value pairs separated by a semi-colon. Therefore the above code to get the "Bearer" value, firstly gets the cookie, splits it into its key/value pairs, finds the row that has a key of "Bearer" and splits that row to attain the Bearer token.
In your comment you say the dev team said the bearer will be in the "content". In your ajax request you already have access to that content through data. You need to debug that request to find out what it is coming back as. I assume you just need to grab the token from the returned data inside of the "If" block where you check for your statusCode.
It will be something like:
document.cookie = "Bearer=" + data.bearer;
However, I don't have the shape of your data so you can only work that final part out yourself.

Related

How to manage JWT properly using React?

I am builing a member system with a lot of function like memo or post system...etc, so I think it's more safe to use JWT token, so I let my api return jwt token every time I sign in like below
{
"status": 200,
"message": "",
"data": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MGViYzI0MDRhNmVkNDU2NzUwOTk4YjEiLCJ1c2VybmFtZSI6ImpvaG4iLCJleHAiOjE2MjY5NTgwMzEuMjA3LCJpYXQiOjE2MjYzNTMyMzF9.3t_YzKPq4jk6UuIkzTgFaLoXD0Pq5ktmRFp7xg6dFYU"
}
And it contains userID and userName , but here's the problem , every time I have to use something else like userProfilePicture ,userFriend...etc , I have to make an API request, it's really meaningless to do
eventually I manage it like I used axio.interceptor to verify and before I assign my data to context state I fetch user's all data using this token and assign the data to state , Is'nt it the same way to just return all user's data without JWT?.
It seems to me that JWT Token is kind of useless, can anyone tell me that what's the real ,effiecent way to use JWT Token and what's the common managment?
Use can save your token JWT in localstorage... and call it in header of request (or fetch) when you call api...
But dont forget to set expired token of JWT to one week (or one month, or one year... its up to you)...
Or you can set configuration if your JWT, if your token is expired, it will still send the response to your app....

How to get a cookie outside getServerSideProps?

I have this code inside getServerSideProps which gives me the token value from a cookie named token:
const token = context.req.cookies?.token || null;
const auth = true;
//Then I sent the token to server
const settings = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': "Bearer " + token,
},
body: JSON.stringify({ "limit": "10" })
};
The cookie is a httpOnly cookie I receive from a post request sent with Set-Cookie header.
The thing is, I want to use the token not only in page components (getServerSideProps is only in page components). In other components I'd like to sometimes use functions that give me more data, let's say all the messages of the client - based on his token (I limit it to 10 in logs.js and I want to increase it in my inner component functions) . Is it safe to pass the token via props and then use it in my functions? I have logs.js component, which has another component named Messages, and inside the Messages component I want to call a function to get more messages but I am not sure whether it is safe or not because the idea of getting the token in getServerSideProps is that nobody can see it, or am I wrong?
If I am not wrong, what is the best way to get the token from the client-side in order to send requests inside inner components?
the idea of getting the token in getServerSideProps is that nobody can see it
Not really when it comes to cookies. Cookies will be sent to the browser so anyone can see it anyways. What you do with it in getServerSideProps is hidden, but the cookie itself is visible.
Because it's an httpOnly cookie, you can't access it with javascript on the client. So if you need the cookie value in javascript, you have a few options:
Read the cookie in getServersideProps and pass that value to your page and through to your components. This will work if you only need your components to read the cookie value.
Change to a { httpOnly: false } cookie which will allow it to be read (and written to) by javascript. I wouldn't do this if it has anything to do with security, because then anyone can not only read the cookie but could change it and do whatever they want with it.
You mentioned it's a token - the big question is: what is the token for in terms of security? You mention using it to determine if you should have more than 10 logs. Is that a business requirement? Would something bad happen (like you lose money, a breach, etc?) if someone manipulated it to show 20, 30, 1,000?
If your business needs to show the user only 10 except in the case where his/her token increases that limit, and you don't want the user to manipulate the limit, leave it as httpOnly, read it in getServerSideProps, and then pass the number to your component. Then, nothing can be manipulated or changed because the client can't mess with the token to unlock more logs.

How to tell if a user is logged in with http only cookies and JWT in react (client-side)

So I'm trying to follow the security best practices and I'm sending my JWT token over my React app in a only-secure http-only cookie.
This works fine for requests but the major issue I find with this approach is, how can I tell if the user is logged-in on client-side if I can't check if the token exists? The only way I can think of is to make a simple http to a protected endpoint that just returns 200.
Any ideas? (not looking for code implementations)
The approach I would follow is to just assume the user is logged in, and make the desired request, which will send the httpOnly token automatically in the request headers.
The server side should then respond with 401 if the token is not present in the request, and you can then react in the client side accordingly.
Using an endpoint like /api/users/me
Server-side
Probably you don't only need to know if a user is already logged in but also who that user is. Therefore many APIs implement an endpoint like /api/users/me which authenticates the request via the sent cookie or authorization header (or however you've implemented your server to authenticate requests).
Then, if the request is successfully authenticated, it returns the current user. If the authentication fails, return a 401 Not Authorized (see Wikipedia for status codes).
The implementation could look like this:
// UsersController.ts
// [...]
initializeRoutes() {
this.router.get('users/me', verifyAuthorization(UserRole.User), this.getMe);
}
async getMe(req: Request, res: Response) {
// an AuthorizedRequest has the already verified JWT token added to it
const { id } = (req as AuthorizedRequest).token;
const user = await UserService.getUserById(id);
if (!user) {
throw new HttpError(404, 'user not found');
}
logger.info(`found user <${user.email}>`);
res.json(user);
}
// [...]
// AuthorizationMiddleware.ts
export function verifyAuthorization(expectedRole: UserRole) {
// the authorization middleware throws a 401 in case the JWT is invalid
return async function (req: Request, res: Response, next: NextFunction) {
const authorization = req.headers.authorization;
if (!authorization?.startsWith('Bearer ')) {
logger.error(`no authorization header found`);
throw new HttpError(401, 'unauthorized');
}
const token = authorization.split(' ')[1];
const decoded = AuthenticationService.verifyLoginToken(token);
if (!decoded) {
logger.warn(`token not verified`);
throw new HttpError(401, 'unauthorized');
}
(req as AuthorizedRequest).token = decoded;
const currentRole = UserRole[decoded.role] ?? 0;
if (currentRole < expectedRole) {
logger.warn(`user not authorized: ${UserRole[currentRole]} < ${UserRole[expectedRole]}`);
throw new HttpError(403, 'unauthorized');
}
logger.debug(`user authorized: ${UserRole[currentRole]} >= ${UserRole[expectedRole]}`);
next();
};
}
Client-side
If the response code is 200 OK and contains the user data, store this data in-memory (or as alternative in the local storage, if it doesn't include sensitive information).
If the request fails, redirect to the login page (or however you want your application to behave in that case).

Django Rest Framework JWT: How to change the token expiration time when logged in

I'm using Django REST framework JWT Auth for session creation and permissions, the only problem is: when I log in and after the token expires I can't continue doing the operation I want, unless I log in again. And I didn't fully understand the documentations provided for the additional settings.
So can any one explain a method for dynamically creating (and refreshing) my token (following best practices) so that I can keep doing operations when I'm logged in.
P.S: I'm using angular 2 for my front end, and I'm inserting the token in the Http requests headers. Thanks.
JWT token refresh is a little confusing, and i hope this explanation helps.
tokens have an issued at time (iat in the token)
tokens have an expiration date (now() + 1 hour, for example)
the token can't be changed. server can only issue a new one
iat never changes, but expires does change with each refresh
When you want to extend a token, this is what happens:
You send your token to the server endpoint /.../refresh/
Server checks its not expired: now() <= token.iat + JWT_REFRESH_EXPIRATION_DELTA
If not expired:
Issue a NEW token (returned in the json body, same as login)
New Token is valid for now() + JWT_EXPIRATION_DELTA
The issued at value in the token does not change
App now has 2 tokens (technically).
App discards the old token and starts sending the new one
If expired: return error message and 400 status
Example
You have EXPIRATION=1 hour, and a REFRESH_DELTA=2 days. When you login you get a token that says "created-at: Jun-02-6pm". You can refresh this token (or any created from it by refreshing) for 2 days. This means, for this login, the longest you can use a token without re-logging-in, is 2 days and 1 hour. You could refresh it every 1 second, but after 2 days exactly the server would stop allowing the refresh, leaving you with a final token valid for 1 hour. (head hurts).
Settings
You have to enable this feature in the backend in the JWT_AUTH settings in your django settings file. I believe that it is off by default. Here are the settings I use:
JWT_AUTH = {
# how long the original token is valid for
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=2),
# allow refreshing of tokens
'JWT_ALLOW_REFRESH': True,
# this is the maximum time AFTER the token was issued that
# it can be refreshed. exprired tokens can't be refreshed.
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
}
Then you can call the JWT refresh view, passing in your token in the body (as json) and getting back a new token. Details are in the docs at http://getblimp.github.io/django-rest-framework-jwt/#refresh-token
$ http post localhost:8000/auth/jwt/refresh/ --json token=$TOKEN
Which returns:
HTTP 200
{
"token": "new jwt token value"
}
I've had same problem in angularjs and I've solved it by writing a custom interceptor service for my authentication headers.
Here's my code:
function($http, $q, store, jwtHelper) {
let cache = {};
return {
getHeader() {
if (cache.access_token && !jwtHelper.isTokenExpired(cache.access_token)) {
return $q.when({ 'Authorization': 'Token ' + cache.access_token });
} else {
cache.access_token = store.get('token');
if (cache.access_token && !jwtHelper.isTokenExpired(cache.access_token)) {
return $q.when({ 'Authorization': 'Token ' + cache.access_token });
} else {
return $http.post(localhost + 'api-token-refresh/',{'token': cache.access_token})
.then(response => {
store.set('token', response.data.token);
cache.access_token = response.data.token;
console.log('access_token', cache.access_token);
return {'Authorization': 'Token ' + cache.access_token};
},
err => {
console.log('Error Refreshing token ',err);
}
);
}
}
}
};
}
Here, on every request I've had to send, the function checks whether the token is expired or not.
If its expired, then a post request is sent to the "api-token-refresh" in order to retrieve the new refreshed token, prior to the current request.
If not, the nothing's changed.
But, you have to explicitly call the function getHeader() prior to the request to avoid circular dependency problem.
This chain of requests can be written into a function like this,
someResource() {
return someService.getHeader().then(authHeader => {
return $http.get(someUrl, {headers: authHeader});
});
}
just add this line to your JWT_AUTH in settings.py file:
'JWT_VERIFY_EXPIRATION': False,
it worked for me.

Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter..?

I am trying to send a PUT request to an amazonS3 presigned URL. My request seems to be called twice even if I only have one PUT request. The first request returns 200 OK, the second one returns 400 Bad Request.
Here is my code:
var req = {
method: 'PUT',
url: presignedUrl,
headers: {
'Content-Type': 'text/csv'
},
data: <some file in base64 format>
};
$http(req).success(function(result) {
console.log('SUCCESS!');
}).error(function(error) {
console.log('FAILED!', error);
});
The 400 Bad Request error in more detail:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InvalidArgument</Code>
<Message>Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter, Signature query string parameter or the Authorization header should be specified</Message>
<ArgumentName>Authorization</ArgumentName>
<ArgumentValue>Bearer someToken</ArgumentValue>
<RequestId>someRequestId</RequestId>
<HostId>someHostId</HostId>
</Error>
What I don't understand is, why is it returning 400? and What's the workaround?
Your client is probably sending an initial request that uses an Authorization header, which is being responded with a 302. The response includes a Location header which has a Signature parameter. The problem is that the headers from the initial request are being copied into the subsequent redirect request, such that it contains both Authorization and Signature. If you remove the Authorization from the subsequent request you should be good.
This happened to me, but in a Java / HttpClient environment. I can provide details of the solution in Java, but unfortunately not for AngularJS.
For the Googlers, if you're sending a signed (signature v4) S3 request via Cloudfront and "Restrict Bucket Access" is set to "Yes" in your Cloudfront Origin settings, Cloudfront will add the Authorization header to your request and you'll get this error. Since you've already signed your request, though, you should be able to turn this setting off and not sacrifice any security.
I know this may be too late to answer, but like #mlohbihler said, the cause of this error for me was the Authorization header being sent by the http interceptor I had setup in Angular.
Essentially, I had not properly filtered out the AWS S3 domain so as to avoid it automatically getting the JWT authorization header.
Also, the 400 "invalid argument" may surface as a result of wrong config/credentials for your S3::Presigner that is presigning the url to begin with. Once you get past the 400, you may encounter a 501 "not implemented" response like I did. Was able to solve it by specifying a Content-Length header (specified here as a required header). Hopefully that helps #arjuncc, it solved my postman issue when testing s3 image uploads with a presigned url.
The message says that ONLY ONE authentication allowed. It could be that You are sending one in URL as auth parameters, another - in headers as Authorization header.
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:scavenger_inc_flutter/utils/AuthUtils.dart';
import 'package:scavenger_inc_flutter/utils/URLS.dart';
class ApiClient {
static Dio dio;
static Dio getClient() {
if (dio == null) {
dio = new Dio();
dio.httpClientAdapter = new CustomHttpAdapter();
}
return dio;
}
}
class CustomHttpAdapter extends HttpClientAdapter {
DefaultHttpClientAdapter _adapter = DefaultHttpClientAdapter();
#override
void close({bool force = false}) {
_adapter.close(force: force);
}
#override
Future<ResponseBody> fetch(RequestOptions options,
Stream<List<int>> requestStream, Future<dynamic> cancelFuture) async {
String url = options.uri.toString();
if (url.contains(URLS.IP_ADDRESS) && await AuthUtils.isLoggedIn()) {
options.followRedirects = false;
options.headers.addAll({"Authorization": await AuthUtils.getJwtToken()});
}
final response = await _adapter.fetch(options, requestStream, cancelFuture);
if (response.statusCode == 302 || response.statusCode == 307) {
String redirect = (response.headers["location"][0]);
if(!redirect.contains(URLS.IP_ADDRESS)) {
options.path = redirect;
options.headers.clear();
}
return await fetch(options, requestStream, cancelFuture);
}
return response;
}
}
I disallowed following redirects.
Used the response object to check if it was redirected.
If it was 302, or 307, (HTTP Redirect Codes), I resent the request after clearing the Auth Headers.
I used an additioal check to send the headers only if the path contained my specific domain URL (or IP Address in this example).
All of the above, using a CustomHttpAdapter in Dio. Can also be used for images, by changing the ResponseType to bytes.
Let me know if this helps you!
I was using django restframework. I applied Token authentication in REST API. I use to pass token in request header (used ModHeader extension of Browser which automatically put Token in Authorization of request header) of django API till here every thing was fine.
But while making a click on Images/Files (which now shows the s3 URL). The Authorization automatically get passed. Thus the issue.
Link look similar to this.
https://.s3.amazonaws.com/media//small_image.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXXXXXXXXXXXXXXXXXXXX%2F20210317%2Fap-south-XXXXXXXXFaws4_request&X-Amz-Date=XXXXXXXXXXXXXXX&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
I lock the ModHeader extension to pass Authorization Token only while making rest to REST API and not while making resquest to S3 resources. i.e. do not pass any other Authorization while making request to S3 resource.
It's a silly mistake. But in case it helps.
Flutter: if you experience this with the http dart package, then upgrade to Flutter v2.10!
Related bugs in dart issue tracker:
https://github.com/dart-lang/sdk/issues/47246
https://github.com/dart-lang/sdk/issues/45410
--> these has been fixed in dart 2.16, which has been shipped with Flutter v2.10!
https://medium.com/dartlang/dart-2-16-improved-tooling-and-platform-handling-dd87abd6bad1

Resources