ADAL renewing token using AcquireTokenAsync and existing JWT token - jwt

I have a JWT token via initial login that is set to expire in 60mins. I want to renew this token so that the user is not logged out.
For this, am using the AcquireTokenAsync call withing that 60mins window using the UserAssertion
public static async Task RenewToken(string resourceUri)
{
var authContext = new AuthenticationContext(Authority);
var authHeader = HttpContext.Current.Request.Headers["Authorization"];
var userAccessToken = authHeader.Substring(authHeader.LastIndexOf(' ')).Trim();
var userAssertion = new UserAssertion(userAccessToken);
// keeps returning the same access token with same expiry
var authResult = await authContext.AcquireTokenAsync(resourceUri, ClientId, userAssertion);
var userInfo = authResult.UserInfo;
var apiAccessToken = authResult.AccessToken;
var expiry = authResult.ExpiresOn.UtcDateTime.ToString("u");
}
Is it that the above call with an existing JWT token can be used only once the token is expired?
Any inputs appreciated.

According to your code seems you want to refresh token on web api(service) side, on service side you shouldn't renew access tokens. The client app should do that operation.
With ADAL, your app will get the access and refresh token the first time an end user logs in, then you can use refresh token to get new access token silently (AcquireTokenSilentAsync) when the access token expires and a refresh token is available & valid.
Access tokens can be refreshed using the refresh-token for a maximum period of time of 90 days with a 14 day expiration sliding window from the date that the access token was acquired by prompting the user.
Checkout our code sample implementing this scenario for more help. If i misunderstand your scenario , please feel free to let me know .

Related

JWT refresh token practice

I'm trying to implement a refresh token concept on my website.
if I understand correctly the refresh token should be a unique identifier for a user to get a new token (the token is valid for 15min only).
I'm using customId package to generate a refresh token for each user on login.
when the token expires. I send a request to an endpoint to generate a new token based on the refresh_token provided for each user.
I'm using nuxt auth module.
try {
const tokenUser = await User.findOne({
refresh: req.body.refresh_token
})
// console.log(tokenUser)
const newToken = await jwtr.sign({
iu: tokenUser._id.toString()
},
'SUPERSECERT', {
expiresIn: '5000' // Testing
}
);
return res.json({
token: newToken
});
} catch (e) {
return res.status(401).send('unauthorized');
}
Am I doing this correctly ? or should I store a newly created jwt token in refresh_token instead of a random unique string? Or did i miss something about the refresh tokens?
This implementation is ok, though you may think of using something which is called a "rolling refresh token". Every time you use the refresh token to get a new access token, you also generate a new refresh token and return both to the client. From now on it should be only possible to get a new access token using the new refresh token. It gives you a bit more security in case someone manages to steal a refresh token.
Nevertheless, you should always expire your refresh tokens at some point (e.g. after a few hours). This will help you ensure that even if someone finds an old refresh token, they will not be able to use it. Once the refresh token expires you should ask the user to log in again.

Can we get FacebookAccessToken from FirebaseAuth?

With Flutter, I am able to login with Facebook, and later I want to get the FacebookAccessToken because it is needed to correctly get the user photoURL.
Is there a way to get the token from FirebaseAuth? Or I must store this value in my code?
Login part, we have the access token:
FacebookLoginResult result = await new FacebookLogin().logIn(['email', 'public_profile']);
...
FacebookAccessToken accessToken = result.accessToken;
Now, let's say in another Widget, we want to get the user photoURL
final auth = FirebaseAuth.instance;
String url = auth.currentUser.photoURL;
This url must be appended with ?accessToken=<access_token> retrieved during the first step. There is a bug created. But for now, can we directly get it from FirebaseAuth?
The Facebook access token is available from the auth result immediately after the user signs in from the FacebookAuthCredential object as result.credential.accessToken. It is not available from the current user, so if you don't capture immediately after sign-in there's no way to find it later without going back to the Facebook SDK.
Also see:
Can I get a facebook access token from firebase.auth().currentUser?
How to get provider access token in Firebase functions?
Get Facebook/Google access token on Firebase Auth#onAuthStateChanged?

Is it a good practice to reload credentials before every request?

I'm working on an iOS app that works with a backend made in laravel, this api manage login and information exchange via JSON web tokens.
To prevent the user to access a web route with an expired token I check the user's credentials before every web call.
My question is, is it a good practice? Because when I started thinking about it the user is accessing twice the amount of times to my server.
For example this is the function to access they're information.
/// Get user's info form the database
///
/// - Parameter completed: Completition Block
func getInfo(completed: #escaping DownloadComplete){
let token = self.getToken()
print(self.getError())
if(token != nil && token != ""){
//Here is where I check credentials.
self.checkCredentials(completed: {
let url = "\(Base_URL)\(myInfo)\(self.getToken() ?? "")"
Alamofire.request(url, method: HTTPMethod.get).responseJSON { respone in
if let result = respone.result.value as? Dictionary<String, AnyObject>{
if let user = result["User"] as? Dictionary<String, AnyObject>{
var Info = Alumno()
if let id = user["id"] as? Int64!{
Info.id = id
}
...
self.userInfo = Info
completed()
}
}
}
})
}
}
The check credentials functions asks the server if the user's token is still valid and if it is it returns
{
"Status": "Success"
}
My answer assumes your server validates the token, and you are not relying on the app to validate the token.
With that assumption, I think it depends on what you can do if the token is expired.
If the only thing you can do is prompt the user to sign in again, then I would probably just make the web request and handle the 401 Not Authorized.
However, if you have the ability to silently refresh the user's token, you may want to preemptively refresh the token if is close to expiring.
In my application, before every web request the app checks if the user's access token will expire within the next 3 minutes, and if so, attempts to refresh it before making the request. If the refresh is successful, the web request is made with the new access token. If the refresh fails, the web request is not made and the app prompts the user to sign in instead. If for any reason the web request still fails after that with 401, the app prompts the user to sign in.
I would do it like once every time the user opens the app not every call.
Other options:
You could also give them a code that they enter that's good for so long.
You could have them sign in when they first download the app. Then they would always be logged in. Then when the token is expired a little popup would say "Something Something Something"

SAP GATEWAY & UI5: How can reset the CSRF token?=

I need to reset the CSRF token in an OData model. Based on the UI5 documentation I am trying to do that with refreshSecurityToken(fnSuccess?, fnError?, bAsync?) function. (click here for reference)
I wrote the following code:
var oDataModel = this.getOwnerComponent().getModel("ZMDM_ODATA_FILE_SRV");
oDataModel.setTokenHandlingEnabled(true);
oDataModel.refreshSecurityToken(function() {
var token = oDataModel.getSecurityToken();
console.log(token);
// can upload the file if token reset
});
The problem is that this token is not reset for 30 minutes and that is our session timeout. Actually it is valid during the session lifetime. I even checked the following link:
https://blogs.sap.com/2014/08/26/gateway-protection-against-cross-site-request-forgery-attacks/
Actually many people had this problem, but I couldn't find a clear solution for resetting the token. I did all the required steps in the front-end for the sending a Head request for resting the token. I think something is missing regarding the back-end gateway settings or ABAP coding.
What do I have to do?
You can delete a CSRF Token (per user/token) via transaction SM05.
seems like you need to set a interval in your front-end application to fetch and update the token more often. But that's a paradox: if your back-end sets the timeout for 30 minutes, why would you keep it live for more time?
SecurityToken timeout is important to make sure the active session is being used and that no individual "forgot" it and left the system open and unwatched/unused.
But if you really need to keep your front-end session always available and force the back-end to be too, you can setInterval() to fetch the CSRF and update the application:
var oDataModel = this.getOwnerComponent().getModel("ZMDM_ODATA_FILE_SRV");
oDataModel.setTokenHandlingEnabled(true);
var fnRefreshToken = oDataModel.refreshSecurityToken(function() {
var token = oDataModel.getSecurityToken();
console.log(token);
// can upload the file if token reset
});
window.setInterval(function(){
fnRefreshToken;
}, 1800000); // where 1.800.000 miliseconds represents 30 minutes
And then you should store your new token in the token variable and allow upload if token is reset.
Kindly regards,
Henrique Mattos

facebook renew access token

I am building desktop application which should commit some stuffs from file system to Facebook.
Application should not give user login form at all.
C#, VS2010 are used.
I have for Facebook App:
client app id
client secret id
token (which is extended, so it is valid for next 60days).
Idea is to somehow renew the access_token, since Facebook doesn't give permanent access_token (offline_token).
So I have tried this:
var fb = new FacebookClient();
dynamic results = fb.Get("oauth/access_token",
new
{
client_id = "aap_id",
client_secret = "secret_id",
grant_type = "fb_exchange_token",
fb_exchange_token = "existing_token"
});
String newToken = results.access_token;
With this code I get newToken, which is different from existing.
My Question:
If this code is run, lets say day before it is expired, will the new token be valid for new 60 days or not?
Or should again be requested extended token?
Thanks,
Ljiljana.