c# - 如何使用不记名令牌和 API 模块在 EmbedIO 中设置主体
问题描述
我正在使用承载令牌模块来保护 API 模块。
如何将 IHttpContext.User 属性设置为当前用户,以便我可以在我的控制器中访问它?
以下是 Web 服务器设置的相关部分:
WebServerEmbedded
.WithCors()
.WithBearerToken("/api", "0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9eyJjbGF", new MyAuthorizationServerProvider())
.WithModule(webApiModule)
这是 MyAuthorizationServerProvider:
internal sealed class MyAuthorizationServerProvider: IAuthorizationServerProvider
{
public async Task ValidateClientAuthentication(ValidateClientAuthenticationContext context)
{
var data = await context.HttpContext.GetRequestFormDataAsync().ConfigureAwait(false);
if (data?.ContainsKey("grant_type") == true && data["grant_type"] == "password")
{
var username = data.ContainsKey("username") ? data["username"] : string.Empty;
var password = data.ContainsKey("password") ? data["password"] : string.Empty;
if (ValidateCredentials(username, password))
{
context.Validated(username);
}
else
{
context.Rejected();
}
}
else
{
context.Rejected();
}
}
public long GetExpirationDate() => DateTime.UtcNow.AddHours(12).Ticks;
private static bool ValidateCredentials(string username, string password)
{
var user = BusinessLayer.CheckUserAndPassword(username, password);
return user != null;
}
}
谢谢。
解决方案
我在 embedio-extras 存储库中发布了一个问题,并创建了一个拉取请求来解决它。如那里详述,升级到 Embedio (v3.3.3) 和 Embedio.BearerToken (v3.4.0) 会从承载令牌模块设置用户主体。
在控制器中 HttpContext.User 可用于访问主体。在调用之前,IAuthorizationServerProvider 实现中可能包含其他声明context.Validated(username);
,例如:
context.Identity.AddClaim(new System.Security.Claims.Claim("Role", "Admin"));
context.Validated(username);
可以在控制器中像这样访问声明:
var principal = HttpContext?.User as ClaimsPrincipal;
if (null != principal)
{
foreach (Claim claim in principal.Claims)
{
Log("Claim type: " + claim.Type + "; Claim value: " + claim.Value);
}
}
推荐阅读
- makefile - Makefile:选择正确的文件
- r - 我可以使用带有 recode() 和 mutate() 的字符向量吗
- python - 在字符串中查找单词,然后在 excel 中写入字符串,找到不同字体的单词
- android - @Override "Method..." 从另一个项目复制方法后
- javascript - 如何在 vue JavaScript 中将数据从一个组件恢复到另一个组件
- python - Python:如何在 Pandas 的循环中正确使用滚动平均值?
- r - 使用 tufte-book 在 bookdown 中设置 PDF 输出的纸张大小
- css - 对话框、快餐栏、...entryComponents 上的 Angular Material 自定义主题
- r - 在 R 中生成特殊矩阵的更有效函数
- sql - SQL罗斯文数据库查询重复行