首页 > 解决方案 > identityserver4 混合关注,无需完成登录

问题描述

我有一个需要保护的 API,它允许第 3 方 asp.net 核心 MVC Web 应用程序请求访问令牌并使用此访问令牌来请求安全 API。

我在身份服务器上创建了 HybridAndClientCredentials 客户端

            ClientId = "testclient",
            // no interactive user, use the clientid/secret for authentication
            AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
            AllowOfflineAccess = true,
            // secret for authentication
            ClientSecrets =
            {
                new Secret("password".Sha256())
            },
            RedirectUris = {"http://127.0.0.1:55950",
                            "http://localhost/testLogin",
                            "https://localhost:44322/",
                            "https://localhost:44302/",
                            "https://localhost:44303/signin-oidc"},
            RequireConsent = false,
            // scopes that client has access to
            AllowedScopes = { "roles" , IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile}

和 MVC 客户端,如身份服务器 4 文档中所示

.AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = Constants.Authority;
                    options.RequireHttpsMetadata = false;

                    options.ClientSecret = "password";
                    options.ClientId = "testclient";

                    options.ResponseType = "code id_token";

                    options.Scope.Clear();
                    options.Scope.Add("openid");
                    options.Scope.Add("profile");
                    //options.Scope.Add("email");
                    //options.Scope.Add("resource1.scope1");
                    options.Scope.Add("offline_access");

                    options.ClaimActions.MapAllExcept("iss", "nbf", "exp", "aud", "nonce", "iat", "c_hash");

                    options.GetClaimsFromUserInfoEndpoint = true;
                    options.SaveTokens = true;

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = JwtClaimTypes.Name,
                        RoleClaimType = JwtClaimTypes.Role,
                    };
                });

它正在工作,但用户似乎已登录 MVC 应用程序,我想要的只是用于调用安全 API 的访问令牌,我也不想在 MVC 客户端上使用 [authorize] 属性将用户重定向到身份服务器登录页面。

标签: asp.net-coreidentityserver4

解决方案


MVC 应用程序中的某些内容必须触发对 OpenIDconnect 处理程序的质询,该处理程序启动对用户进行身份验证的过程。结果,用户已登录,您可以访问令牌。

使用[Authorize]属性是触发质询的一种方法,或者使用如下代码手动执行:

    public async Task Login()
    {
        await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme,
            new AuthenticationProperties() { RedirectUri = "/" });
    }

推荐阅读