首页 > 解决方案 > 与本地提供商的 OAuth 身份验证

问题描述

在 ASP.NET Core 2.2 应用程序中,我正在定义OAuth提供程序。提供者能够登录用户并获取一个authorize_code,交换authorize_code一个token并获取用户详细信息,并且身份服务器的 cookie 存储在用户代理中。但是在重定向到授权页面(在我的例子中是/用户)之后,我被重定向回身份提供者,但是 cookie 已经分配给应用程序,所以应用程序获取一个 authorize_code,将其交换为一个令牌并获取用户详细信息并重定向到 Authorize页面和整篇文章一次又一次地开始,最终用户代理取消重定向,所以我陷入了递归,我不知道为什么。

这是使用的配置

services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = "app";
        options.DefaultScheme = "app";
    })
    .AddCookie()
    .AddOAuth("app", options =>
    {
        options.ClientId = "appclient";
        options.ClientSecret = "3f97501d279b44f3bd69e8eec64cf336";

        options.CallbackPath = new PathString("/app-signin");

        options.Scope.Add("app_identity");
        options.Scope.Add("profile");
        options.Scope.Add("email");

        options.AuthorizationEndpoint = "http://dev/services/identity/connect/authorize";
        options.TokenEndpoint = "http://dev/services/identity/connect/token";
        options.UserInformationEndpoint = "http://dev/services/identity/api/user-profile";

        options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
        options.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "firstName");
        options.ClaimActions.MapJsonKey(ClaimTypes.Surname, "lastName");
        options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");

        options.Events = new OAuthEvents
        {
            OnCreatingTicket = async context =>
            {
                var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                var response = await context.Backchannel.SendAsync(request, 
                                   HttpCompletionOption.ResponseHeadersRead, 
                                   context.HttpContext.RequestAborted);
                response.EnsureSuccessStatusCode();

                var user = JObject.Parse(await response.Content.ReadAsStringAsync());
                context.RunClaimActions(user);
            }
        };
    });

services.Configure<CookiePolicyOptions>(options =>
{
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

services
    .AddMvc()
    .AddRazorPagesOptions(options => options.Conventions.AuthorizePage("/User"))
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

应用程序日志在以下输出中

    info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
    Request starting HTTP/1.1 GET http://localhost:5001/User
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
    Executing endpoint 'Page: /User'
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[3]
    Route matched with {page = "/User"}. Executing page /User
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
    Authorization failed.
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[3]
    Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
    Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.OAuth.OAuthHandler`1[[Microsoft.AspNetCore.Authentication.OAuth.OAuthOptions, Microsoft.AspNetCore.Authentication.OAuth, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]][12]
    AuthenticationScheme: app was challenged.
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[4]
    Executed page /User in 64.6437ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
    Executed endpoint 'Page: /User'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
    Request finished in 129.4168ms 302
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
    Request starting HTTP/1.1 GET http://localhost:5001/app-signin?code=311966dfed306bdf5228501edcf7b493e208a0cf720d3ef39f281aabfa04bfb8&scope=wph_identity%20profile%20email&state=CfDJ8Ncai4ZNyK9Bno-T0jQD3hVJUzq-6K_bCKipeVryVM_FhwOvgc_d5ueapYYg7XRTSuFeLbrnZB4K8Zpni8KAk6cg1wWGwDoGXJrb3jp9zwhGQS24bPZUrsVFVxdt9v0loPkJjX6p226E3TisaJkaAxa_bzxyO_JKWtoHKsBLOmbuLh92rvxzde6S9BrElgvOuAYqsJ87UidQbCm8RrqZh78aC1vo5XcdIYEZs6eQjGFt
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[10]
    AuthenticationScheme: Cookies signed in.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
    Request finished in 321.3221ms 302
...

输出仅重复 4 次。我相信它只是一些错误配置,但我无法弄清楚配置错误的是什么。

标签: asp.net-coreoauth-2.0asp.net-identityidentityserver4razor-pages

解决方案


由 SameSite cookie 限制引起。添加.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, opt => opt.Cookie.SameSite = SameSiteMode.None)帮助。


推荐阅读