php jwt login storage - javascript

I'm building a web app with CodeIgniter 4 where I implemented a REST API for register and login and a profile page just a test my login.
I have a login form that sends a javascript fetch post request to my api and I receives a jwt token. This is working.
Now I am in the situation where I think I did not understand the principle.
I want that the user stays logged in and doesn't need to re-login every time. The token expires after 12h.
And I want to use php (if possible) as the entire app runs on php.
Currently, I have a little javascript function to store my token:
const store = {};
store.setJWT = (data) => {
this.JWT = data;
};
But this is not secure against page reload.
Additionally I am creating a cookie with php, when the user logs in:
helper('cookie');
set_cookie([
'name' => 'login',
'value' => $token,
'expire' => $exp,
'httponly' => true,
'secure' => true,
]);
I am able to fetch data from the API using the cookie or the store object.
const token = getCookie('login');
const res = await fetch('/profile', {
headers: {
'Authorization': `Bearer ${token}` // or store.JWT
}
});
So.... what I want is:
The user goes to a protected url e.g. https://myapp.com/profile and if he is logged in, he has access. If not, he gets redirect to the login page.
Is using the cookie to store the jwt a good idea? Or did I completely misunderstood the idea of JWT and it is not used to be used for a login?
Additionally: I still don't know if biulding the login as an API was the best idea.

First of all there is nothing wrong with building "login with API". It is common practice. And JWT is perfectly suited for auth.
You sure can store JWT token inside a cookie, but it is a little bit wrong in my opinion. Usually JWT tokens are stored in the local storage on the client side. It will persist after page reload.
Set token in the local storage:
localStorage.setItem('token', token);
Get token from the local storage:
token = localStorage.getItem('token');
To better understand the conception of the JWT you can copy some token (without Bearer) and paste it in jwt.io. Basically JWT contain all the required information about the user and server can trust this information.
And when you set the cookie like this
set_cookie([
'name' => 'login',
'value' => $token,
'expire' => $exp,
'httponly' => true,
'secure' => true,
]);
It is an overkill. JWT possible already contains all this information and you can extract it from the token.

Related

Refresh token for Google OAuth 2.0

I have an application that uses Google APIs in some places, and I want to avoid having the user login every time. Currently, I only receive a Google access token in the response, not a refresh token. How can I obtain the refresh token?
This is the function I use to when the user click to login with google:
authenticate() {
const client = google.accounts.oauth2.initTokenClient({
client_id: 'MY_CLIENT_ID',
scope: [
"All_NECESSARY_SCOPES",
].join(" "),
callback: (res) => {
this.accessToken = res.access_token
this.loadClient()
}
})
client.requestAccessToken()
},
It works for getting the access token. And I need the refresh token, Please Help Me :)
Client side JavaScript does not return a refresh token. It would be a security risk.
If you want a refresh token you need to use a server sided language like Node.js

How to properly deal with JWT in headers

I'm trying to set up JWT in my project (NodeJs Express for the backend, and Javascript in frontend).
So in my backend, I send my token like this when the user logs in :
[...]
return res.send({ token, id: userId })
[...]
And in my frontend, I set the Bearer token in my header like this :
const data = {
email,
password
}
await instance.post('/signin', data)
.then((res) => {
instance.defaults.headers.common['authorization'] = `Bearer ${res.data.token}`
window.location = './account.html'
})
.catch((err) => console.log(err))
My questions are :
Did I do it correctly ?
When I'm redirected to the account.html page, how do I retrieve the token that was set while the log in was made ?
When you assign to instance.defaults.headers.common['authorization'] then subsequent requests made via Ajax using whatever library (I'm guessing Axios) that is from that page will include the authorization header.
Assigning a new value to window.location will trigger navigation and discard the instance object (with the assigned header value).
(As a rule of thumb, if you are going to assign a new value to window.location after making an Ajax request then you should probably replace the Ajax request with a regular form submission).
You could assign the data to somewhere where you can read it in the account.html page (such as local storage).
That won't be available to the server for the request for account.html itself though.
You could assign the data to a cookie. Then it would be available for the request for account.html, but in a cookie and not an authorisation header.
Note that using JWTs in authorization headers is something generally done in Single Page Applications and not traditional multi-page websites.

How to securely store JWT tokens in react/next.js application?

I need to store JWT token which is generated when a valid user login after proper registration through REST API. I read and find these ways to store JWT in client site: local storage, session storage, cookies, HttpOnly cookie, Browser memory (React state).
Need suggestion to store JWT in the proper method and also can access some certain APIs for get with JWT token as post request header parameter user-related data.
here is my login code part where I store JWT token to window object at this point, saved previously on local storage but now need to store safely in other ways except local storage or cookies.
const handleSubmitLogin = evt => {
evt.preventDefault();
var cart = new Cart();
var request = new NFRequest();
var response = request.api(HTTP_METHOD.POST, '/auth', {
'email_address': allValuesLogin.email_login,
'password': allValuesLogin.password_login,
'cart_list': cart.getCartPostData(),
});
response.then((res) => {
if (res.type === 'success') {
window.$token = res.data.token
setLoginSuccess('Successfully Login')
setTimeout(()=> {
setLoginSuccess('');
}, 3000)
cart.handle({ action_type: "RESET_ITEMS" });
Router.push('/account')
} else {
setLoginError('Wrong Email or Password')
setTimeout(()=> {
setLoginError('');
}, 3000);
}
});
}
here I store the JWT token:window.$token = res.data.token
Thank you.
It's up to you on how to store it. Generally, this is the most to least secure:
Browser memory
Http-only cookie
local storage
session storage / cookie
The most important thing is to make sure your website is protected against XSS and CSRF attacks.
Update: It's not a good idea to store JWT tokens in local storage.
Read this article => https://www.rdegges.com/2018/please-stop-using-local-storage/
set the token with localStorage
if (res.type === 'success')
localStorage.setItem('token', res.data.token);
setLoginSuccess('Successfully Login')
setTimeout(()=> {
setLoginSuccess('');
}, 3000)
cart.handle({ action_type: "RESET_ITEMS" });
Router.push('/account')
}
to remove the token you use:
localStorage.removeItem('token');
Storing JWT tokens within localStorage or session storage is suggested of course with this in production a proper SSL certificate should be used to help prevent this like a man in the middle attack.
Also there are different advantages to local/session
sessionStorage is removed after browser is closed however localStorage is shared between tabs. This is handy for sharing state between tabs. However you ned to manage removing the JWT token.

Where to store JWT

I barely started reading about JWT and I beliave I understand what a JWT token is. I am also fairly familiar with SESSIONS. And I believe I understand the pros of each as well as their cons. However, there are a couple of parts where I am confused.
When requesting a protected resource, you need to send the jwt on each request, as opposed to having a session stored on the server. But:
1) how do you store your JWT token and where. From what I read I understood that you send your request to authenticate to the server and the server sends you a JWT token if you are successfully authenticated. Then what do you do?, do you store the JWT in a cookie as I have read in some sites? If so, how do you do it (using php, using javascript). And how do you read it.
2) When using session, more or less you just check that there is a session to check the user is logged in. How do you accomplish this when using JWT.
Also I have seen this on some pages:
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
How is this related to this (if related at all)
From client side, the good practice is store JWT in cookie, with mode http_only=true, is_secure (so that only send through https), so that JWT is not accessible by javascript. Then, we don't worry about XSS attach.
We dont need to store the session on server side. A JWT contains two parts, the payload data, and signature, signed by a secret key stored on server side, and only the server could know. When we receive the token from client, we check the payload data is valid or not (user information, who assigned that token, assigned that token to whom, which roles granted with the token, expired time), and we check the signature to make sure that the token is assigned by the server, not faked. Then the user will be authenticated.
It's like a passport the government give to its citizen, the data (payload) is readable for everybody, but the signature can only created by the government, and it can verify against that.
JWT is mostly a way to authenticate a user on rest APIs as, like you said, you send it to the client, and it negates the need to store it in a session.
however, if you are making a browser application, i don't see the need to use JWT authentication, as you can use the session and cookies to do so.
JWT is mainly for those cases, when you have a, say, mobile application frontend, where maintaining a session is not suggested, and maybe impossible.
however, if you are making a hybrid application, then storing it in local storage of the "browser" is the way to go. the JWT is NEVER stored server side.
In my case I use use Illuminate\Foundation\Auth\AuthenticatesUsers;, use JWTAuth; and use Tymon\JWTAuth\Exceptions\JWTException; in my LoginController. Then I need to get my JWTToken like that
use AuthenticatesUsers;
try {
$token = JWTAuth::attempt($request->only('username', 'password'), [
'exp' => Carbon::now()->addWeek()->timestamp,
]);
} catch (JWTException $e) {
return response()->json([
'error' => 'Could not authenticate: ' . $e.message,
], 500);
}
Of cause I do somthing more, if I don't get a token. In my case I go like that:
if (!$token) {
return response()->json([
'error' => 'Could not authenticate.'
], 401);
} else {
$data = [];
$meta = [];
//all what i need from users table if auth
$data['id'] = $request->user()->id;
$data['email'] = $request->user()->email;
$meta['token'] = $token;
//now comes the part, where I set my sessions:
Session::put('auth-user', (array)$request->user());
Session::put('jwt-token', $token);
Session::save();
return response()->json([
'data' => $data,
'meta' => $meta
])->withCookie('jwt-token', $token, config('jwt.ttl'), '/', null, true, true);
}
This is actually that what I do in LoginController I also have a middleware where I have a function to handle stuff like behavior after refresh page an so on.
'my.auth' => \App\Http\Middleware\MyAuth::class
I also handle a lot in javaScript's localStorage and sessionStorage in vuex store. To define routes in web.php or api.php I'll use now the class what I defined in
middleware before Route::group(['middleware' => 'my.auth'], function(){...}
Some resources that helped me out:
LaravelCookies, LaravelSession
Hope you get a bit inspiration to create your JWT auth.

Get Auth0 access_token from existing id_token

I'm using auth0 to authenticate my logins to my Single Page App (built on React). I'm mostly using the base API calls (listed here).
The process I'm using is:
get username/email and password when the user enters them on my app's login page
Send a POST request to /oauth/ro with those values - here is that code:
export const login = (params, err) => {
if (err) return err
const {email, password} = params
const {AUTH0_CLIENT_ID, AUTH0_DOMAIN} = process.env
return fetch(`${AUTH0_DOMAIN}/oauth/ro`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': AUTH0_CLIENT_ID,
'username': email,
'password': password,
'connection': 'Username-Password-Authentication',
'grant_type': 'password',
'scope': 'openid',
'device': '',
'id_token': ''
})
})
.then(response => response.json())
.then(json => {
const {id_token, access_token} = json
setCookieValue('id_token', id_token) // utility function I wrote
return getProfile(access_token)
.then(data => {
const {user_id, email: emailAddress, picture, name} = data
return {id_token, user_id, emailAddress, picture, name}
})
})
.catch(error => console.log(`ERROR: ${error}`))
}
This is all sent through Redux and the user is logged in (assuming the username/password was correct).
However, I'm trying to figure out how to persist the login when refreshing the page/coming back to the app. I'm saving the id_token (which is a JWT) in the browser's cookies and can fetch this when the app renders server-side. I can decode the JWT and get the payload (sub is the user ID from auth0). However, to get the profile data I need the access_token which Auth0 provides when using the /oauth/ro POST request. Obviously, if the JWT token has expired then it will just reject it and keep the user logged out.
Here is my code to decode the JWT (happens on app render):
const ID_TOKEN = req.cookies.id_token || false
if (ID_TOKEN) {
verifyJwt(ID_TOKEN, (err, decoded) => {
if (err) { console.log(`JWT Verification error: ${err}`) }
else {
const {sub} = decoded
getProfile(sub).then(data => store.dispatch(fetchUserDetails(data))) // fails as `sub` (the user id) is not the `access_token` which it requires
}
})
}
I have tried using the /oauth/ro call again, but this time specifying "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer" and using the id_token retrieved from the cookies, and specifying a device. However, when I do this call, I get this error from Auth0:
{
"error": "invalid_request",
"error_description": "there is not an associated public key for specified client_id/user_id/device"
}
So my question is, what API call do I need to make to get the access_token from the id_token JWT?
Also, as a bonus - when I do the POST request to login, the password is being transfered over plaintext. How would I encrypt this when sending to auth0 so they can decrypt it back? I assume it involves using the client_secret which auth0 provide but I'm not sure how to go about doing that.
The ability to refresh a token programmatically without any type of user interaction is accomplished through the use of refresh tokens. However, this is not applicable for browser-based applications because refresh tokens are long-lived credentials and the storage characteristics for browsers would place them at a too bigger risk of being leaked.
If you want to continue to use the resource owner password credentials grant you can choose to ask the user to input the credentials again when the tokens expire. As an alternative, upon authentication you can obtain the required user information and initiate an application specific session. This could be achieved by having your server-side logic create an application specific session identifier or JWT.
You can also stop using the resource owner password credentials grant and redirect the user to an Auth0 authentication page that besides returning the tokens to your application would also maintain an authenticated session for the user, meaning that when the tokens expired and your application redirected again to Auth0, the user might not need to manual reenter credentials because the Auth0 session is still valid.
In relation to the password being sent in plaintext; the resource owner endpoint relies on HTTPS so the data is encrypted at the protocol level. You must also use HTTPS within your own application for any type of communication that includes user credentials of any kind.
Also note that you can control what's returned within the ID token through the use of scopes, depending on the amount of information in question you might not even need to make additional calls to get the user profiles if you signal that you want that information to be contained within the ID token itself.

Categories