【问题标题】:How to refresh access token in web application using Azure Active Directory如何使用 Azure Active Directory 在 Web 应用程序中刷新访问令牌
【发布时间】:2020-12-12 20:13:11
【问题描述】:

我目前正在为访问令牌的生命周期而苦苦挣扎。我有 dotnet core Web 应用程序和 dotnet core Web API。

Web 应用程序受到 OpenIDConnect 授权的保护。一旦您尝试连接到 Web 应用程序,您将被重定向到 Microsoft 登录表单,并在成功登录后,提供 Access Token 并将其与 Refresh Token 一起存储到 cookie 中。

因此,访问令牌在我的 WebAPI 请求的授权标头中传递。 当 access_token 生命周期到期时,我的 WebAPI 开始返回 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 的构造函数,我在其中向标头添加访问令牌。

    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 App 调用 ASP .NET Core Web API。第二个问题 - 您想为特定用户正确撤销刷新令牌吗?
  • 1) 正确 2) 我想通过使用刷新令牌来撤销访问令牌(授权代码流程原则)但是经过几次搜索后,这似乎是一个内置功能。所以我不确定这是否能解决我的问题。
  • @DanielRusnok 我已经编辑了标题以反映您的 cmets,如果这不正确,请随时将其改回
  • @DanielRusnok 没错,但从我们现在的讨论来看,我认为您的问题的答案在这里:stackoverflow.com/questions/48952087/… 您可以使用 MSAL 来刷新令牌。也检查一下 - 这是解释:github.com/AzureAD/microsoft-authentication-library-for-dotnet/…

标签: azure authentication azure-active-directory access-token refresh-token


【解决方案1】:

我现在不明白 - 你有基本的 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

【讨论】:

  • 谢谢。但不是我的意思。
  • 好的,听到这个消息很难过。我以为我们正在讨论 Azure AD 中的刷新令牌撤销。
  • 我会尽量解释更多。对不起,这是我的英语,这主要是破坏我的沟通技巧。我有 Web Api 和 Web 客户端应用程序(Dotvvm 框架)。我的问题是,有时 Web Api 在使用客户端应用程序一段时间后返回 401 Access Denied。我认为这是因为访问令牌过期。
  • 现在唯一的解决方案是退出并登录到应用程序并获取新的访问令牌。我想通过使用刷新令牌默默地“在幕后”获取新的访问令牌,但我不知道如何,因为我找不到任何代码示例。
  • 我认为这种行为是内置的,我猜我的设置是错误的。或者,我应该使用 ConfidentialClientApplication 类以某种方式访问​​访问令牌并更新它吗?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-25
    • 2019-11-06
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 2017-02-17
    相关资源
    最近更新 更多