如何使用 Azure Active Directory 刷新 Web 应用程序中的访问令牌

How to refresh access token in web application using Azure Active Directory

我目前正在努力处理访问令牌的生命周期。我有 dotnet 核心 Web 应用程序和 dotnet 核心 Web API.

Web 应用程序受 OpenIDConnect 授权保护。一旦您尝试连接到 Web 应用程序,您将被重定向到 Microsoft 登录表单,并且在成功登录后,将提供 访问令牌 并将其与 刷新令牌[一起存储到 cookie 中=33=].

因此,访问令牌在我的 WebAPI 请求的授权 Header 中传递。 当 access_token 生命周期到期时,我的 WebAPI 开始 return 401 Unauthorized.

我看了很多关于使用刷新令牌撤销访问令牌的文章,但是我没有找到任何实现示例,所以我转向你们。

这就是我在 Web 客户端中设置 OpenId 的方式。

        services.AddDataProtection();
        services.AddAuthorization();
        services.AddWebEncoders();
        services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
        {
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.ClientId = Configuration["AzureAd:ClientId"];
            options.Authority = $"{Configuration["AzureAd:AadInstance"]}{Configuration["AzureAd:Tenant"]}/v2.0";
            options.ClientSecret = Configuration["AzureAd:ClientSecret"];
            options.ResponseType = "code";
            options.SaveTokens = true;
            options.UseTokenLifetime = true;
            
            options.Scope.Add(Configuration["AzureAd:Scope"]);

            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = Configuration["AzureAd:Tenant"] != "common",
                RoleClaimType = JwtClaimTypes.Role
            };
            options.Events = new OpenIdConnectEvents
            {
                OnRemoteFailure = context =>
                {
                    context.HandleResponse();
                    context.Response.Redirect("/error");
                    return Task.CompletedTask;
                }
            };
        });

        services.AddHttpContextAccessor();

这就是我在 Web 中设置身份验证的方式 API Startup.cs。

            services.AddAuthentication("Bearer")
            .AddJwtBearer(
                "Bearer",
                options =>
                {
                    options.Authority = $"{Configuration["AzureAd:AadInstance"]}{Configuration["AzureAd:Tenant"]}/v2.0";
                    options.Audience = Configuration["AzureAd:Audience"];
                    options.TokenValidationParameters.ValidateIssuer = false;
                });

最后,这是我的 ApiService 的构造函数,我在其中将访问令牌添加到 headers。

    protected ApiService(HttpClient httpClient, string apiUri, IHttpContextAccessor httpContextAccessor, ILogger<ApiService> logger)
    {
        this.httpClient = httpClient;
        this.apiUri = apiUri;
        this.logger = logger;
        context = httpContextAccessor.HttpContext;

        this.httpClient.DefaultRequestHeaders.Authorization
            = new AuthenticationHeaderValue("Bearer", context.GetTokenAsync("access_token").Result);
    }

如果你们需要更多信息,请告诉我,我会提供。谢谢!

据我所知 - 你有基本的 ASP .NET Core Web 应用程序(MVC 或 Razor)并且你想使用 Azure AD 保护它。

如果我的理解是正确的,你应该利用 Microsoft.Identity.Web 库: https://github.com/AzureAD/microsoft-identity-web

它目前仍处于预览阶段,但我可以确认它工作稳定。 以下是如何将其与 ASP .NET Core Web 应用集成的详细说明: https://github.com/AzureAD/microsoft-identity-web/wiki/web-apps

示例如下: https://github.com/AzureAD/microsoft-identity-web/wiki/web-app-samples

该库还管理刷新令牌并提供令牌缓存实现,因此您不必自己实现: https://github.com/AzureAD/microsoft-identity-web/issues/221

在 Startups 中重新编程身份验证并利用 ITokenAcquirer 服务解决了我的问题:https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/4-WebApp-your-API/4-1-MyOrg