使用MVC客户端4.7.1和标识服务器4进行身份验证 [英] Authentication with MVC Client 4.7.1 and IdentityServer4

查看:34
本文介绍了使用MVC客户端4.7.1和标识服务器4进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试集成MVC 4.7.1客户端和ASP.NET Core 3.1标识服务器4和ASP.NET标识服务之间的用户身份验证。

我一直在遵循Cookie颁发的身份验证的本教程:Refreshing your Legacy ASP.NET IdentityServer Client Applications (with PKCE)

到目前为止,MVC客户端能够重定向到登录页面。登录后,我在以下函数中出现空错误:

private string RetrieveCodeVerifier(AuthorizationCodeReceivedNotification n)
{
        string key = GetCodeVerifierKey(n.ProtocolMessage.State);

        string codeVerifierCookie = n.Options.CookieManager.GetRequestCookie(n.OwinContext, key);
        if (codeVerifierCookie != null)
        {
            var cookieOptions = new CookieOptions
            {
                SameSite = SameSiteMode.None,
                HttpOnly = true,
                Secure = n.Request.IsSecure
            };

            n.Options.CookieManager.DeleteCookie(n.OwinContext, key, cookieOptions);
        }

        string codeVerifier;
        var cookieProperties = n.Options.StateDataFormat.Unprotect(Encoding.UTF8.GetString(Convert.FromBase64String(codeVerifierCookie)));
        cookieProperties.Dictionary.TryGetValue("cv", out codeVerifier);

        return codeVerifier;
}

显然codeVerifierCookie为空。

其余配置如下所示。

 app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "cookie"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "mvc.owin",
                Authority = "https://localhost:44355",
                RedirectUri = "http://localhost:5001/Auth/",
                Scope = "openid profile scope1",

                SignInAsAuthenticationType = "cookie",

                RequireHttpsMetadata = false,
                UseTokenLifetime = false,

                RedeemCode = true,
                SaveTokens = true,
                ClientSecret = "secret",

                ResponseType = "code",
                ResponseMode = "query",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                        {
                            // set PKCE parameters
                            var codeVerifier = CryptoRandom.CreateUniqueId(32);

                            string codeChallenge;
                            using (var sha256 = SHA256.Create())
                            {
                                var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                                codeChallenge = Base64Url.Encode(challengeBytes);
                            }

                            n.ProtocolMessage.SetParameter("code_challenge", codeChallenge);
                            n.ProtocolMessage.SetParameter("code_challenge_method", "S256");

                            // remember code_verifier (adapted from OWIN nonce cookie)
                            RememberCodeVerifier(n, codeVerifier);
                        }

                        return Task.CompletedTask;
                    },
                    AuthorizationCodeReceived = n =>
                    {
                        // get code_verifier
                        var codeVerifier = RetrieveCodeVerifier(n);

                        // attach code_verifier
                        n.TokenEndpointRequest.SetParameter("code_verifier", codeVerifier);

                        return Task.CompletedTask;
                    }
                }
            });

和在IdentityServer4 ConfigureServices上:

 services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseSuccessEvents = true;

                // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
                options.EmitStaticAudienceClaim = true;
            })
                .AddInMemoryIdentityResources(Config.IdentityResources)
                .AddInMemoryApiScopes(Config.ApiScopes)
                .AddInMemoryClients(Config.Clients)
                .AddAspNetIdentity<ApplicationUser>();

最后,标识服务器4端的Client.cs配置:

new Client
{
            ClientId = "mvc.owin",
            ClientName = "MVC Client",
            AllowedGrantTypes = GrantTypes.Code,
            ClientSecrets = {new Secret("secret".Sha256())},
            RedirectUris = {"http://localhost:5001/Auth/"},
            AllowedScopes = {"openid", "profile", "scope1"},
            AllowPlainTextPkce = false,
            RequirePkce = true,
            RequireConsent = false,
            // Token lifetimes
            AuthorizationCodeLifetime = 60,
            AccessTokenLifetime = 60,
            IdentityTokenLifetime = 60
}

Account控制器和其余部分基本上是基本的标识服务器4模板,特别是is4aspid

  1. 有没有人尝试过相同的方法,知道什么失败了?
  2. 有没有办法用JWT代替Cookie?还有,它的缺点是什么?

编辑:显然,此配置适用于Firefox,我怀疑这是Chrome的Same-Site Cookie策略的问题,因此GetRequestCookie中的。问题是,虽然MVC客户端应用程序运行在HTTP上(注:两者都在本地主机上),但IdentityServer4运行在HTTPS上(否则,还有其他应用程序)。我曾尝试使用SameSite的策略:无、松、严,反之亦然,但没有成功。我不确定还可以尝试什么。

最佳 Mkanakis。

推荐答案

声明SameSite=None的Cookie也必须标记为安全,这意味着您需要使用HTTPS

阅读更多内容here

这篇关于使用MVC客户端4.7.1和标识服务器4进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆