Search code examples
asp.net-mvcazurecookiesauthorizationadal

MVC App using Azure AD with ADAL 3 - Authentication Cookie expires after 1 hour


I work on an MVC Web Application using Azure AD with OAuth 2 and Open ID Connect for Authorization of users. Per documentation tokens are refreshed automatically when a token expires after 60 minutes (which is fine). Now the problem is, to acquire a token I need to know the currently authenticated user which is stored in a cookie. The code to acquire a Token is like this:

public async Task<AuthenticationToken> GetTokenForApplication(string resourceID)
{
   string signedInUserID = ClaimsPrincipal.Current.SignedinUserId(); 
    var tenantID = ClaimsPrincipal.Current.TenantId(); 
    string userObjectID = ClaimsPrincipal.Current.SignedinUserObjectId(); 

    // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
    ClientCredential clientcred = new ClientCredential(Config.ClientId, Config.AppKey);
    // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
    AuthenticationContext authenticationContext = new AuthenticationContext(string.Format("{0}{1}", Config.AadInstance, tenantID), new ADALTokenCache(signedInUserID));
    AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(resourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
    var token = new AuthenticationToken(authenticationResult.AccessToken) { ExpiresOn = authenticationResult.ExpiresOn };

    return token;
}

Now I am in the dilemma, that the ClaimsPrincipal.Current.SignedinUserId() method call throws a null reference exception. When I inspect the ClaimsPrincipal.Current object, no data about the logged in user is available. But this is the Information needed to renew / request a token.

What is the best practice in an MVC Web App? Is there a way to extend the validity of the cookie or is there any way to reauthenticate the current user without redirecting to the root page of the web application?

After doing more research I have found these two pages which describe some options to deal with my problem pretty good: Controlling a Web App’s session duration and ASP.NET-Identity-Cookie-Authentication-Timeouts

are these good approaches?


Solution

  • After doing more research I have found these two pages which describe some options to deal with my problem pretty good: Controlling a Web App’s session duration and ASP.NET-Identity-Cookie-Authentication-Timeouts

    are these good approaches?