c# - 使用 AspNet.Security.OpenIdConnect.Server 的基于令牌的安全性在添加身份后停止工作
问题描述
我创建了一个小型 .NET Core 网站,允许用户使用 AspNet.Security.OpenIdConnect.Server 获取不记名令牌。它按预期工作,直到我添加services.AddDefaultIdentity<IdentityUser>();
添加身份后,日志不会显示任何令牌验证迹象,并且HttpContext.User.Identity.IsAuthenticated
始终为false
. 仍然会生成令牌 - 似乎只是跳过了验证。
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication(OAuthValidationDefaults.AuthenticationScheme)
.AddOAuthValidation(OAuthValidationDefaults.AuthenticationScheme)
.AddOpenIdConnectServer(options =>
{
options.TokenEndpointPath = "/token";
options.AllowInsecureHttp = true;
options.ApplicationCanDisplayErrors = true;
options.Provider.OnValidateTokenRequest = context =>
{
context.Validate();
return Task.CompletedTask;
};
options.Provider.OnHandleTokenRequest = context =>
{
var identity = new ClaimsIdentity(context.Scheme.Name,
OpenIdConnectConstants.Claims.Name,
OpenIdConnectConstants.Claims.Role);
identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique id]");
var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity),
new AuthenticationProperties(),
context.Scheme.Name);
context.Validate(ticket);
return Task.CompletedTask;
};
});
// When the following line is uncommented the bearer token isn't validated anymore
//services.AddDefaultIdentity<IdentityUser>();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvc();
}
一个示例控制器操作可能是这样的:
public bool Get() => HttpContext.User.Identity.IsAuthenticated;
如果我添加Authorize
属性,我将收到 404:
[Authorize]
public bool Get() => HttpContext.User.Identity.IsAuthenticated;
要创建令牌,我会执行以下操作:
POST http://localhost:5005/token HTTP/1.1
User-Agent: Fiddler
Host: localhost:5005
Content-Length: 69
Content-Type: application/x-www-form-urlencoded
client_id=web&grant_type=password&username=username&password=password
带有不记名令牌的请求如下所示:
GET http://localhost:5005/customer HTTP/1.1
User-Agent: Fiddler
Host: localhost:5005
Authorization: Bearer <the token received in the previous call>
整个程序可以在这里下载: https ://gist.github.com/nielslbeck/e454cc1b79aa56948c96f4a24438b34e
解决方案
推荐阅读
- apache-spark - 多个方法上的单个数据帧并行执行
- c# - 非控制器类无法访问 DbContext
- oauth - 如何在不刷新 OAuth 2.0 用户令牌的情况下查询 Google Sheets API?
- android - 完成 Querysnapshot 任务后如何启动新的 Intent?
- django - 如何在 django 模型中调整图像文件的大小
- matlab - 每 100m 等值线图标签
- r - 为什么在 Power BI 中运行我的 R 代码时收到这些错误消息?
- javascript - 将内部包含数组的对象数组更改为一个对象
- spring-boot - 我收到 SSL 异常 - “java.security.cert.CertificateException:找不到与 IP 地址 XXXX 匹配的主题替代名称”
- java - 使用泛型类型使 Field.get 类型安全