asp.net-core - 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] 属性将用户重定向到身份服务器登录页面。
解决方案
MVC 应用程序中的某些内容必须触发对 OpenIDconnect 处理程序的质询,该处理程序启动对用户进行身份验证的过程。结果,用户已登录,您可以访问令牌。
使用[Authorize]属性是触发质询的一种方法,或者使用如下代码手动执行:
public async Task Login()
{
await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties() { RedirectUri = "/" });
}
推荐阅读
- ios - 对 Firebase/Crashlytics 的多个应用使用相同的谷歌应用 ID
- r - 主成分分析循环不起作用
- python - 如何将脚本中的函数作为包从同级文件夹导入
- python - 在 Python 中通过“ElementTree”解析 XML
- python - 有没有办法使用 Flask Socket IO 登录用户?
- angular - Angular 反应式表单根据其他两个输入验证输入
- r - 将数据框转换为结构化列表
- c# - MVC 5 Nonfactorsgrid 不工作。命名空间有问题
- javascript - 如何测试一个变量是否是javascript中某种类型对象的数组?
- javascript - 尽管返回 false,但仍提交 HTML 表单