Can I cache the token generated for a tenant, while creating the GraphServiceClient and reuse it again, if so how long is the token valid? what causes it's expiration?
The code I have uses IAuthenticationProvider and implements
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
AuthenticationContext authContext = new AuthenticationContext(url.ToString());
ClientCredential creds = new ClientCredential(clientId, clientSecret);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com", creds);
request.Headers.Add("Authorization", "Bearer " + token);
}
The Azure Active Directory Token Lifetimes are documented here.
Default Limits
Access Token Lifetime
Affects: Access tokens, ID tokens, SAML2 tokens
Default Lifetime: 1 hour
Refresh Token Max Inactive Time
Affects: Refresh tokens
Default Lifetime: 14 days
Single-Factor Refresh Token Max Age
Affects: Refresh tokens (for any users)
Default Lifetime: 90 days
Multi-Factor Refresh Token Max Age
Affects: Refresh tokens (for any users)
Default Lifetime: 90 days
Single-Factor Session Token Max Age
Affects: Session tokens (persistent and nonpersistent)
Default Lifetime: Until-revoked
Multi-Factor Session Token Max Age
Affects: Session tokens (persistent and nonpersistent)
Default Lifetime: Until-revoked
Related
As the refresh token is expired we have to re-login the user again for new access and refresh token so my question is how we can alive in the same session even after the refresh token is expired?
I have tried this in settings.py
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(seconds=60),
'REFRESH_TOKEN_LIFETIME': timedelta(seconds=120),
}
When User Sign In Gmail account via Oauth2 protocol and finish it, my server get authorization code and I make exchange this code for refresh token and access token, everything works as planned but I need to get email address too. I mean if user logged in as helloworld#gmail.com, somehow with authorization code I would like to know this address, may I somehow to know it?
This is endpoint where I exchange authorization code on access token and refresh token:
public OAuth2AccessToken oauth(String authorizationCode) {
AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
resource.setUserAuthorizationUri(userAuthorizationUri);
resource.setAccessTokenUri(accessTokenUri);
resource.setClientId(clientId);
resource.setClientSecret(clientSecret);
resource.setPreEstablishedRedirectUri(redirectUrl);
resource.setScope(scopes);
resource.setUseCurrentUri(false);
AccessTokenRequest request = new DefaultAccessTokenRequest();
request.setPreservedState(new Object());
request.setAuthorizationCode(authorizationCode);
AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider();
OAuth2AccessToken accessToken = provider.obtainAccessToken(resource, request);
return accessToken;
}
I don't have WebSecurityConfigurerAdapter for OAuth2
If the user's email address is not already provided in the id_token part of the oauth2 response, you can use the Gmail API Users.getProfile operation, using the special value "me" as the userId to refer to the authenticated user.
See: https://developers.google.com/gmail/api/v1/reference/users/getProfile
That should give you a response like:
{
"emailAddress": -string-,
"messagesTotal": -integer-,
"threadsTotal": -integer-,
"historyId": -unsigned long-
}
I'm using Google API to obtain access and refresh tokens for offline access, however, the refresh token is always null.
The authorizationCode comes from the client, so I exchange it with the tokens on the server:
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT,
JSON_FACTORY,
clientId,
clientSecret,
scopes)
.setAccessType("offline")
.build();
GoogleTokenResponse response = flow
.newTokenRequest(authorizationCode)
.setRedirectUri(redirectUri)
.execute();
// response has access_token and id_token. don't see any refresh token here
return flow.createAndStoreCredential(response, null);
// this returns Credential with refreshToken = null
Client code:
$(document).ready(function() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: '<my client id>',
// Scopes to request in addition to 'profile' and 'email'
scope: 'https://www.google.com/m8/feeds https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appfolder'
});
});
$('#signinButton').click(function() {
auth2.grantOfflineAccess({'redirect_uri': 'postmessage'}).then(onSignIn);
});
});
// the onSignIn function sends the one time code (i.e. authResult['code']) to the server
Am I doing anything wrong here?
I saw this question: Google OAuth: can't get refresh token with authorization code but it didn't really answer my question and I'm not aware of refresh token only being created the first time a user logs in.
Edit:
I believe this is actually a client side problem, because the consent window doesn't ask for offline access. Will update this question based on the results of a new question here: Google javascript sign-in api: no offline access
The VS 2013 SPA Template is configured with the cookie middleware, among other middlewares like the OAuth MW or ExternalCookie MW.
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(20),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
Since the WebApi will authorize the calls made from the client side through bearer tokens and the external cookie middleware is there to support external login providers, what role does the cookie middleware serve in this?
It's there as a replacement for forms authentication. Before, a user would sign in with forms auth, then it would issue a cookie, and create a principal object that represents the user's identity. With OWIN, the cookie authentication middleware does the same task.
It will also handle things like logins/redirects (forbidden requests) as you can see with the above line of code:
LoginPath = new PathString("/Account/Login"),
I'm using express.js and mongoStore and csrf in express.js
and I want to maintain the login session for 24 hours.
so my express configuration file is like this.
// express/mongo session storage
app.use(express.session({
secret: pkg.name,
store: new mongoStore({
url: config.db,
collection : 'sessions',
auto_reconnect: true
}),
cookie:{
maxAge : new Date(Date.now() + 3600000*24) //1 Hour = 3600000
}
}))
// adds CSRF support
app.use(express.csrf())
and it works maintaining login session for 24 hours.
the problem is csrf session token also change.
Thus, after 24 hours from first login, csrf error occur on my website.
is there any way to maintaining user login session without csrf error?
thanks in advance!
:D