问题描述
我有一个需要安全保护的API,允许第三方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]属性来重定向用户到身份服务器登录页面。
解决方法
MVC应用程序中的某些内容必须触发对OpenIDconnect处理程序的质询,该质询将启动对用户进行身份验证的过程。结果,用户已登录,您就可以访问令牌。
使用 [Authorize] 属性是触发质询或使用以下代码手动完成挑战的一种方法:
public async Task Login()
{
await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme,new AuthenticationProperties() { RedirectUri = "/" });
}