How to keep access token for subsequent requests in website like in mobile app - codeigniter

I am developing a web api which will server mobile app and website, if as user access login service in api, user get validated and return back with access token, this access token will be stored in mobile and this access token will be used in subsequest requests for the resources in the api this is fine, but how can we store this access token in website(web browser) to use it for subsequest requests, shall we use sessions to store this access token, if so what about statelessness, if we store it in cokies it will be security treat right, please help me guys thanks in advance

I suggest you to store the access token in the browser's local storage.
Syntax to add
localStorage.setItem("appToken", token);
*where token is the value returned after successful authentication and appToken is the local variable holding that value.
Syntax to access token variable
var token = localStorage.appToken;
*you can access the same token in different pages so that you can hit APIs from there.
Syntax to remove the token
localStorage.removeItem("appToken");
*it's better to remove the token from appToken variable if you want to logout from the application.

Related

How to invalidate mobile personal access token after backend deletion?

I am using Laravel as my backend together with Sanctum which generates personal access token for mobile users. For my mobile application I am using flutter.
To authenticate users they login with their username/password and get a personal access token in return. This works but requires a user to login every time they open the application again so I did what most tutorials suggest which is saving the token on the mobile device using shared preferences/secure storage.
Now comes the question how do you invalidate a user when you remove their token from the backend? On initial login it appears everything is still fine because like in most tutorial I check for the existence of a token. After that whenever I want to make a request which uses the token I obviously run into problems because it not longer exists on the backend.
Most tutorials/guide suggest saving the token and using that a reference to see if the user is logged in or not but this seems flawed because it gives the false impression you actually have a valid token.
My guess is this can be solved by always performing a heartbeat/ping action to check if the current token is valid and if not send them to the login screen instead of simply checking for the existence of the token.
Thoughts on this?
I can suggest a hack or trick here in every launch of the app you can send a request to an API to check if the user's token is valid or not and if it is valid then you can continue the app otherwise force the user to login and generate new token this way your app will be secure via server / API.
For this, you can store the user's secret token in the database and check it via HTTP API call and send a response from the API accordingly and check the response in app and do the next operation according to the response you get.
I don't know if this is a great way of doing this job but it is a kind of hack/trick to achieve what is needed.
Thanks

Where and how to store the access token and refresh token

I have a dotnet core 2.2 MVC web application which uses a web api to perform some database queries. I have implemented JWT token based authetication for web api. Tokens are generated at the api and the web application has received the access token, expiry and refresh token. I need to store this token details at my client , so that I can either use it to access web api(before expiry) or generate new token using the refresh token if the token expires.
Any help on this would be appreciated.
You have various options (secure http-only cookie, localstorage, session storage, etc.).
In the most simple scenario, you can store it in a cookie so that it is sent along with each request :
The cookie should always have the HttpOnly flag to prevent XSS attacks in the browser.
The cookie should also use the Secure flag in production, to ensure that the cookie is only sent over HTTPS.
Protect your forms against CSRF attacks (by using ASP.NET Core’s AntiForgery features, for example).
Previous answers don't provide clear explanation about the reasons of using those solutions.
Typical systems look like on the picture below and there are two common Client Application architectures used in WEB:
Singe Page Application running in browser
Server side MVC application
In case of SPA the tokens are stored in browser (session storage or local storage) and are cleared automatically by either browser or the app itself when expire. FYI, obtaining refresh token is not possible in SPA because of security reasons.
In case of MVC app (your case) the things get more complicated. You have two options: either store it in http-only cookie or some external session store. Aspnet core supports both cases but each has caveats. A good article here. In short, if your are concerned about cookie size then use Distributed Session Storage which adds more complexity to the system architecture. Otherwise cookies is the easiest solution and is enabled by default in aspnet core, you just need to set options.StoreTokens = true and options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme.
There are multiple ways to store the tokens. Usually applications doesn't store access token anywhere, but they do store refresh token in a permanent storage.
Let's take a look at what you need to store at web and api end.
First, user will request to login in web application with credentials, web app will pass this request to the api project - which interacts with DB.
Now, api will generate access tokens and refresh token and the save refresh token to that DB. Web api then need to store access token and refresh token in temporary storage like cookie or session.
When access token is expired; you need to make a call for a new tokens, which will update the previous refresh token in the DB.
TL;DR
Refresh token - in DB
Access token and refresh token - web temporary storage
Make the call from ui to web application server(controller) controller which in turn makes call to get the token from api.
get the token from api response and store it in cookie.
you controller should look something like this
var option = new CookieOptions
{
Expires = DateTime.Now.AddMinutes(response.ExpiresIn)
};
if (!string.IsNullOrEmpty(domain))
{
option.Domain = domain;
}
Response.Cookies.Append({cookiename}, response.AccessToken, option);

What to return after login via API?

I'm creating an API server which will be consumed by a mobile app that I will work on later. I have yet to see any reference of API best practices related to user flow and returned data even after searching for several hours.
My question is whether the login response of an API should return the a personal access token with the refresh token along with the user info? Or should I just return the token and make another API call for getting the user info.
I could just do what I have in mind but I'm trying to learn the best practices so that I don't have to adjust a lot of things later.
I need suggestions as well as good references related to my question.
Thank you.
It depends on what you are using for your authentication. If you are using libraries like Laravel Passport or JWT, you can have the token endpoint which returns the access token, refresh token, validity period and the token type (Bearer). You can then have an authenticated endpoint which will be used to get a user's profile based of the token passed in the request header.
However, if you go through the documentation for those libraries, in most there is an allowance to manually generate a token. You can use this in a custom endpoint that will return the token as well as the user profile Passport Manually Generate Token.
If you are using JWT, you can also embed a few user properties in the token itself. The client can the get the profile info from the JWT itself without having to make a round trip to the server. Passport ADD Profile to JWT
If you have a custom way in which you are handling authentication, you can pass the token as well as the user profile in the same response.
In the end, it's up to you to decide what suits you best.
Have you looked at OpenID Connect? It's another layer on top of OAuth 2.0 and provides user authentication (OAuth 2.0 does not cover authentication, it just assumes it happens) and ways to find information about the current user.
It has the concept of an ID_token, in addition to the OAuth access token, and also provides a /userinfo endpoint to retrieve information about the user.
You could put user information in your access token, but security best practice is to NOT allow your access token to be accessible from JavaScript (i.e. use HTTP_ONLY cookies to store your access token).

YouTube API - How to create a permanent access token?

I am using the access token to play my private videos in my android app and for that, I am created an access token.
But It says,
The OAuth Playground will automatically revoke refresh tokens after 24h. You can avoid this by specifying your own application OAuth credentials using the Configuration panel
I tried to add my own client secrets and ID and after creating a new token, it still displays the same NOTE.
How can I create a permanent access token that will not expire?
I tried to change available parameters like Access Type Online, Offline, and still shows same NOTE.
Google apis generally do not let you get a permanent access token
Access tokens have limited lifetimes. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.
Generate an offline refresh token to use and get a short lived access token
This is part of the Oauth2 standard

Google OAuth2 - tokens, on-line, offline, adding scopes incrementally

Trying to organize this question into something clear. We are integrating Google for Work into our application, to use login, Google+, and eventually Contacts, Calendar, etc. As is recommended by Google and everything I have read, we are going to use incremental access, only adding scopes when they are needed. We are a PHP shop.
But, we will also be needing offline access, as our Contacts (and eventually Calendar) access will be synchronizing with our internal database.
We currently capture the Access and Refresh Tokens when doing the initial link, and store them locally, so that we can re-authorize at any time by using the Refresh token whenever the Access token expires. This is working correctly.
Questions:
a) when adding the incremental scopes for Contacts, the documentation says we need to call the gapi.auth.signIn() function in the page javascript with the new scopes. This is working on the page where we are allowing folks to manage settings. In the original login function callback, I save the Access Token and scopes with an Ajax call that uses the access code passed into the callback, and calls the Google_Client authenticate() function to get the access code and scopes... but at that point, the information I get back does not have the new scopes. Why? Do I have to re-extend the scopes every time the page is drawn?
b) since we are going to have a batch process do the contact synchronization, do I need to get an entirely different access token with access_type=offline, or can I use the current access token (properly extended with the new scopes). Can an off-line access token be used for on-line access as well as off-line? Or vice-versa?
For your questions:
a) have you used the parameter "include_granted_scopes"? as mentioned here:
https://developers.google.com/accounts/docs/OAuth2WebServer#incrementalAuth
b) When you request an offline access token, the response contains the access token and refresh token. so you can refresh the access token after it expires without having the user grant the permissions again.
online access token and offline access token work for the same.
the difference between both its the capability to refresh the access token when it expires without involving the user. Which is the functionality for the offline type.
The online access token doesn't mean that it works for your client-side authentication (done in the browser) and the offline works for the server-side.
You mentioned that you can get an access token, refresh token and authorization code from the client-side of your app. You could send that information to your server and make api calls from there, although this is not a good practice.
I would suggest that you do the OAuth Flow in the server side and from there manage the users information and API calls.
Here you can find the documentation on both Web server applications and Client Side applications.
Hope it's clearer.

Resources