Microsoft.Owin.Security.OpenIdConnect与Azure Active Directory身份验证票证生存期

时间:2016-01-26 15:00:28

标签: owin office365 azure-active-directory openid-connect adal

我正在构建一个多租户Web应用程序,使用 Microsoft.Owin.Security.OpenIdConnect,Version = 3.0.0.0 连接Office 365服务,使用 Microsoft.IdentityModel.Clients连接Azure Active Directory .ActiveDirectory,版本= 2.19.0.0 关注this sample

我们的Web应用程序客户端(用户代理)使用asp.NET cookie对我们的服务器进行身份验证,而我们的服务器和授权服务器(此处为Azure AD)之间的身份验证是使用OpenID授权代码流进行的。

我们为Asp.NET cookie设置了30天的滑动到期时间。但是,即使设置 UseTokenLifetime = true ,我们仍然会从Authority Server获得一个短暂的AuthenticationTicket,它应该与两种身份验证机制的生命周期相匹配。Short lived authentication ticket

我们遇到的问题是:我们的最终用户必须经常重新登陆(少于一小时)。那么问题是,我们如何在这个owin openidconnect中间件中增加/更改身份验证票证的生命周期?

备注:我还发布了a question关于使用ADAL刷新令牌的用法。 根据我们的理解,此问题仅与身份验证有关。由ActiveDirectory客户端管理的授权问题 access_token refresh_token 的生命周期与此问题无关。如果我错了,请纠正我。

Startup.Auth.cs

public partial class Startup
{
  public const string CookieName = ".AspNet.MyName";
  public const int DayExpireCookie = 30;

  public void ConfigureAuth(IAppBuilder app)
  {
   app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

   var cookieAuthenticationOptions = new CookieAuthenticationOptions()
   {
       CookieName = CookieName,
       ExpireTimeSpan = TimeSpan.FromDays(DayExpireCookie),
       AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
       SlidingExpiration = true,
   };

   app.UseCookieAuthentication(cookieAuthenticationOptions);

   app.UseOpenIdConnectAuthentication(
       new OpenIdConnectAuthenticationOptions
       {
           ClientId = SettingsHelper.ClientId,
           Authority = SettingsHelper.Authority,
           ClientSecret = SettingsHelper.AppKey,
           UseTokenLifetime = true,
           TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
           {
               ValidateIssuer = false
           },

           Notifications = new OpenIdConnectAuthenticationNotifications()
           {
               // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. 
               AuthorizationCodeReceived = (context) =>
               {
                   var code = context.Code;
                   string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                   string signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                   AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantID), new ADALTokenCache(signInUserId));
                   ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);
                   // Get the access token for AAD Graph. Doing this will also initialize the token cache associated with the authentication context
                   // In theory, you could acquire token for any service your application has access to here so that you can initialize the token cache
                   Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                   AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, credential, SettingsHelper.AADGraphResourceId);
                   return Task.FromResult(0);
               },

               RedirectToIdentityProvider = (RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context) =>
               {
                   string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                   context.ProtocolMessage.RedirectUri = appBaseUrl + SettingsHelper.LoginRedirectRelativeUri;
                   context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl + SettingsHelper.LogoutRedirectRelativeUri;
                   return Task.FromResult(0);
               },
               AuthenticationFailed = (context) =>
               {
                   context.HandleResponse();
                   return Task.FromResult(0);
               }
           }
       });
  }
}

帐户控制器

public class AccountController : Controller
{

     public void SignIn()
     {
         var dateTimeOffset = DateTimeOffset.UtcNow;
         var authenticationProperties = new AuthenticationProperties
         {
             AllowRefresh = true,
             IssuedUtc = dateTimeOffset,
             ExpiresUtc = dateTimeOffset.AddDays(Startup.DayExpireCookie -1),
             RedirectUri = SettingsHelper.LoginRedirectRelativeUri, IsPersistent = true
         };
         HttpContext.GetOwinContext()
             .Authentication.Challenge(authenticationProperties,OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
     }

     public void SignOut()
     {
         HttpContext.GetOwinContext().Authentication.SignOut(
             new AuthenticationProperties { RedirectUri = SettingsHelper.LogoutRedirectRelativeUri,  },
             OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
     }
 }

1 个答案:

答案 0 :(得分:4)

实际上, 我需要设置UseTokenLifetime = false。 实际上,UseTokenLifetime = true将Asp.NET cookie中的内部票证更改为access_token的默认生命周期,即1小时。 来自@Tratcher的评论是真的,但误导了我......是的access_token生命周期是由Azure AD控制的,我无能为力。但是,我们使用ADAL.NET实现了refresh_token管理,因此可以将身份验证/授权与Microsoft身份服务器保持一个多小时。设置UseTokenLifetTime = false并使用cookie身份验证,我的客户端应用程序与我的服务器之间的滑动到期时间为15天就像魅力一样。