Implementation JWT on Application (Understanding concept of JWT) - php

I just learn JWT on PHP. I'm a litle bit understand how JWT work on single page. When I implementating on multiple page (page to another page).
Is my implementation true if every user move to another page we have to fill HTTP_AUTHORIZATION with token (bearer code) and in the same time we generate new token ?
Thanks in advance

Conceptually, JWT is a bearer token issued to user after successful login using their username and password.
Normally for mobile app we set long expiry for a JWT token, while for a web app, we use the JWT refresh mechanism to avoid invalid API abuse by invalidating the old token and refresh with a new set of token without login again. Once the JWT token is expired, then will need to kick the user out.
For a mobile app, JWT can be saved in SharedPreference and use the same key for all API calls. Set it as an environment instead of page based, so that you no need to set it again every time in every page.
Have a read on this https://tech.justeattakeaway.com/2019/12/04/lessons-learned-from-handling-jwt-on-mobile/

Related

JWT using Firebase to maintain login without cookies

I'm creating a website which necessitate a login for some contents. I have succeeded to use JWT library but i don't find and don't understand how to maintain login without the use of cookies (my temp solution).
Can you explain me what is the best solution to give JWT between pages ?
In general, you can store the JWT in the localstorage of the user's browser. And with every request, you should pass that token into the Authorization header.
On the backend, you need to verify the token and extract informations about the connected user to return data based on his profile.

Dealing with OAuth 2.0 Token expiration at the Consumer

I have a client application that use the oauth2 with authorization grant type resource owner password credential. I write a curl http request to obtain the access token when user provide her credential, but how to request another access token when the first one expired. I read that it's good to estimate the validity of the access token. I found this client library but I don't think it will solve my problem related to requesting a new access token once it expire or even when the refresh token expired too.
Can anyone point me to the right direction how to implement this or use a library for that purpose please?
Instead of checking token expiration for every resource request, you can handle token expiration error and perform a Refresh Token request to get a new access token.
oAuth server should normally mention invalid_grant in its response when access token is invalid, expired, or revoked. Refer here. You should check with your oAuth server what response it provides exactly when a token is expired.
Some libraries does include this feature but I do not find for the library you mentioned. I used Retrofit as java client and it has this. You might want to request this feature for the library you mentioned.
If a refresh token is expired, the oAuth authorization flow should start over again.
the OAuth2 token you receive will have the duration in it. Each token expires after a set amount of time and that information is sent back as part of the object you receive. So you can store it locally and reuse it until the expiration time passes.
Once it does expire you have two options :
Request another token
Refresh the existing token. A lot of the OAuth2 providers offer this functionality.
The only question is if the library you are using has that built in. If not maybe you can add it yourself.
Edit
if you want to store the token somewhere then Session will work. The Session does not expire when the user closes their browser bit when it hits the timeout expiration set on the host itself. To be fair if they reopen the app later, they will have to login again at which point you can request another token. If you decide to use the Refresh Token functionality then it makes sense to store that in the database itself and use it from there as this is a long term thing not something that is session based.

Rest API JWT token based authentication security | laravel/dingo/jwt

I am using JWT token based authentication for the authenticating my REST APIs exposed to mobile apps. I have a login API where the user will be hitting to and get a JWT back as a response. App has to use the JWT token for the rest of the requests. One question that struck during the development is.
Once I give an authentication token to the user, he has access to rest of the set of APIs.
User 1 with JWT token T1 trying to access resources of user 2 is possible in my current design which is a flaw in my system. On each request do I have to check whether the user id in the token and the user id for which the process is requested matches and then proceed? or is there any better way this is been handled some other way?
I am using laravel framework with dingo rest and JWT lib.
Update
Eg :
I as an individual got the endpoints from the app. I logged in and received my jwt token which will be valid across rest of my resources. Now to get a list of products I have added using a different user id.I can do it this way
My JWT token in the header
GET /products/3 and 3 is not my user id!
In this case, Im just validating a jwt token, which will validate it and respond with the resource which is not MINE!
TL;DR: It is imho quite common to use it this way, you should be good the way it is!
More detail:
The point here is that the token is "obscure enough" so that there is an negligable chance a non-authorized user is obtaining the token from an authorized user. In your example this means, that user 2 can with a very high probabilty not guess the token that user 1 is using.
Of course this way may be prune to man-in-the-middle-attacks, so you should be sure to only transfer the tokens over a secure connection. I suggest "HTTPS only". Also, you may think about only sending and receiving the tokens in the header, so they are not exposed in any content views.
As a bit more background: Think about how PHP "standard" session cookies are working: The user (client) gets a session ID in a cookie and sends it back. This is basically the same as you are doing here with the JWT, as user 2 could also somehow steal the cookie from user 1 here, and act on his behalf. JWT even adds you a level with which you can easily confirm that you actually issued the token (provided you are using the RSA-keypair-style approach), which i think is an advantage over the PHP session ID cookie approach.

JWT token login and logout

Hi I am creating mobile native application that uses REST API endpoints to communicate with server side.
I have had previous experience developing native clients, but I have simple token (random generated string) stored in DB in the same table where user information is stored. So it is like sessions used in browser, but instead of cookies each request has token in the header.
Recently I discoreved JWT token. It seems to be great way to secure endpoints which are private. You can request token from mobile client providing you pass + login and get generated token in response.
But the one important thing is that this token is not stored anywhere on the server, server verifies the token using secret word, which is private for the server like private key.
That's okay for secured endpoints, but what to do if I require user session, for example how do apps like Facebook, Amazon, Aliexpress ... work, they have ability to use the app without providing credentials, just navigating through the store, but require logining in when user want't to make purchase. And after that user session is kept for some time.
This can be implemented with the JWT token without any problems, but when user need to logout, what to do in this case ? Token is not stored anywhere on the server, so how can I destroy this token, to make it invalid ?
If token is stored in the database, API is not stateless, as REST API should be.
So in general there is no way to keep user logged in in stateless API, am I right ?
I have some ideas how to implement this using JWT token, but again this will not be stateless API, as I understand.
Create the list of expired tokens
Store JWT token in the database, but what is the purpose of self descriptive token (JWT) in this case if it is stored in the database, the main idea of JWT token to keep all information with token, as I know.
Please suggest what is the best way will be in this case, and correct me if I have mistaken.
Thanks.
If you're using JWTs, then you can't have a server side state in order to properly logout the user without defeating the purpose of using JWTs in the first place. The best option though if you want to do this is to have a last logout date stored in the DB and in the JWT, and if these don't match you logout the user (without updating the date in this case). However, you now have server side state.
Storing logged out tokens in the DB seems like overkill though.
An alternative option is that you could generate a 128 bit token generated by a CSPRNG, store this using SHA-256 in the database, and then use the unhashed value in a web token. This way you can simply delete the entry in order to logout the user server side. This is the more secure option as you now have a way to properly expire tokens and sessions on the server. If a user changes their password, or wants to secure their account by logging out other sessions you now have a way to do this.
JWT authentication is basically happens on both the client side and server side.
When the user sends Username and password to authenticate. its checked against the db and if valid a joken is generated and sent back to the user. There are multipe API's for generating the JWT token, you can check out http://jwt.io/
Once the token is generated and sent back, it needs to be sent along with header in each request and needs to be validated, on the server side, before serving the API back to the user.
There is no need to store the the token as the API itself will allow you to decode it on the server side.
How i am doing it:
I generate a random id (I call it validation code) and store it in database when user signup, encode it in jwt.
Whenever any request is made with jwt, I check the validation code, if it is correct: access is granted.
To expire the session like after changing password, I change the validation code in DB.
If you need to logout a user, provide a logout link. The server should reset the session data by encoding the token with any empty array for example. The user will have a valid session but will not have the valid information to validated them.
Valid Token at login
$data = array("id"=>1,"user_type"=>"Admin");
$token = JWT:encode($data, $key);
Validating Token
$token = $_POST['token'];
$data = JWT:decode($data, $key, $hash);
if($data.id){
return "valid token";
}else{
return "invalid token"
}

How do I programmatically start an OAuth session?

I am using InfusionSoft's API to save the contents of a form that is filled out on a website. The API uses OAuth, and from what I can tell there isn't a way to have a life-long session.
The way the OAuth appears to work is that it is designed for a user to login if their session has expired, just like logging into a website. This obviously isn't suitable for an API, but I'm sure this isn't an unusual requirement.
I have an initial token, but after that expires, what then? The only thing I can think of is to have a cron job that runs hourly to refresh the access token (there is a 'refreshAccessToken' method).
You need to store both the Access Token (short term - it is live for 24 hours) and the Refresh Token (long term).
You will only need to call the refreshAccessToken method at the start of each session. That method will return both a new Access Token and a new Refresh Token.
Use the new Access Token for the current "session" when making API requests. The Access Token will be valid for 24 hours (this changes from time to time).
Store the new Refresh Token and use it again for your next session.

Categories