【问题标题】:MVC Core 2 external users and access tokenMVC Core 2 外部用户和访问令牌
【发布时间】:2018-10-14 14:08:39
【问题描述】:

我是 Dot net core 2 和实现 MVC 客户端和 IdentityServer4 的新手。

在获取外部用户访问令牌时面临两个问题。

问题 1

services.AddAuthentication(options =>
             { 
                 options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                 options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                 //options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; 
             })

当添加下面的代码行时

options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; 

即使在 ExternalLoginCallback

中成功验证后用户也无法登录

问题 2

如果我删除了上面的代码行,用户可以登录但await HttpContext.GetTokenAsync("access_token") 返回 null。

这里是startup.cs的完整代码

public void ConfigureServices(IServiceCollection services)
        { 


             services.AddAuthentication(options =>
             { 
                 options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                 options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                 //options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;   

             })
           .AddCookie()
           .AddGoogle(googleOptions =>
           {
               googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
               googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
               googleOptions.SaveTokens = true; 
           })
            .AddOpenIdConnect(options =>
            { 
                options.Authority = "http://localhost:xxx/";  
                options.RequireHttpsMetadata = false;  
                options.ClientId = "xxx"; 
                options.ClientSecret = "xxx";
                options.ResponseType = "code id_token";  
                options.Scope.Add("xxxx");
                options.Scope.Add("email");
                options.Scope.Add("offline_access");
                options.GetClaimsFromUserInfoEndpoint = true;
                options.SaveTokens = true;


            });

            services.AddMvc();
        } 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseMvcWithDefaultRoute(); 
        }

我们将不胜感激。

【问题讨论】:

    标签: .net-core asp.net-core-mvc access-token identityserver4


    【解决方案1】:

    这是连接到 Identity Server 4 的 mvc Web 应用程序的启动。注意 .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)

    Setup.cs

    services.AddAuthentication(options =>
                {
                    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                })
                 .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
                {
                    //options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\temp-keys\"));
                    // when the identity has been created from the data we receive,
                    // persist it with this authentication scheme, hence in a cookie
                    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    // Identity server endpoint
                    options.Authority = settingsSetup.IdentityServerEndpoint;
                    // Turns off HTTPS requirement becouse i CBA to set up visual studio.
                    options.RequireHttpsMetadata = false;
                    // Client id to login with
                    options.ClientId = settingsSetup.ClientId;
                    // Client secret.
                    options.ClientSecret = settingsSetup.Secret;
    
                    // Scope of our API
                    options.Scope.Add("testapi");
                    options.Scope.Add("devconsole");
                    // adding offline_access to get a refresh token
                    options.Scope.Add("offline_access");
    
                    options.ResponseType = "code id_token";
                    options.SaveTokens = true;
                    options.GetClaimsFromUserInfoEndpoint = true;
                });
            services.AddAuthorization();
    

    从您的控制器中,您应该能够以这种方式获取值。

    var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
    var refreshToken = await HttpContext.GetTokenAsync(IdentityConstants.HttpContextHeaders.RefreshToken);
    var idToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.IdToken);
    

    【讨论】:

    • 感谢 DalmTo,我也这样做了,用户可以成功登录,但机器人函数返回 null。 var info = await _signInManager.GetExternalLoginInfoAsync(); var token = await HttpContext.GetTokenAsync("access_token");
    • Identty 服务器日志记录说什么?你能看到你的用户登录了吗?
    • var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true); if (result.Succeeded) { _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); }
    • 登录成功重定向后,用户无法登录
    • 如果我们从 startup.cs 'options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme' 中删除这一行,那么用户将成功登录。
    猜你喜欢
    • 2014-10-29
    • 2017-03-31
    • 2015-11-25
    • 2023-04-11
    • 2019-04-06
    • 2019-08-28
    • 1970-01-01
    • 2021-04-20
    • 2022-11-17
    相关资源
    最近更新 更多