.net-core - HotChocolate 与 Authorize 属性,如何获取当前登录的用户?
问题描述
我使用带有[Authorize]
属性 from的 HotChocolate 获得了 GraphQL 突变,HotChocolate.AspNetCore.Authorization
以在我的 GraphQL 端点上强制执行授权。
这很好用,我只能在以管理员身份登录后调用突变......
...但现在我想检索已授权的用户,但我似乎没有找到办法。
[ExtendObjectType(Name = "Mutation")]
[Authorize(Roles = new[] { "Administrators" })]
public class MyMutations
{
public bool SomeMethod()
{
// In a regular Web API controller, you can do User.Identity.Name to fetch the user name of the current user. What is the equivalent in Hot Chocolate?
var userName = "";
return false;
}
}
有任何想法吗?
解决方案
HotChocolate 使用 asp.net 核心身份验证机制,因此您可以使用 HttpContext 获取用户。
[ExtendObjectType(Name = "Mutation")]
[Authorize(Roles = new[] { "Administrators" })]
public class MyMutations
{
public bool SomeMethod([Service] IHttpContextAccessor contextAccessor)
{
var user = contextAccessor.HttpContext.User; // <-> There is your user
// In a regular Web API controller, you can do User.Identity.Name to fetch the user name of the current user. What is the equivalent in Hot Chocolate?
var userName = "";
return false;
}
}
推荐阅读
- android - Kotlin - 闪烁文本的最简单方法(可见/不可见)
- python - Beautiful Soup - 使用 find_all 从多个网页中提取文本
- javascript - (GDrive API)用户无需登录即可下载文件需要访问令牌
- javascript - ES 模块何时可以导入名为 export 的 CommonJS?
- excel - 带日期的 Excel 通配符
- java - Spring Security:@PreAuthorized(hasAuthority) 以列表为参数
- size - Teradata 问题 - 多个商店和多个项目
- python - 无法将 LabJack U3 模型正确加载到 PyCharm
- c# - 禁用JS chrome selenium c#
- c - 使用定点而不是浮点计算信号频率