【发布时间】:2018-07-13 12:26:51
【问题描述】:
我在 C# 中有一个身份验证属性
public class JwtAuthenticationAttribute : Attribute, IAuthenticationFilter
{
public string Realm { get; set; }
public bool AllowMultiple => false;
public User User { get; set; }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
//authentication stuff
this.User = GetUserFromDB();
//more code
}
.... more code
我使用它在 web api 控制器中进行身份验证:
[Authorize]
[JwtAuthentication]
public class AccesosController : ApiController
{
public IHttpActionResult DoSomethingAuthenticated(){
//how to get the user from the [JwAuthentication] attribute?
}
}
如何从方法中的属性中获取 User 属性?我需要这个属性,因为它有一些其他信息,我需要在我的方法中处理一些其他信息。
我知道在令牌中我可以获取用户 ID 并将对象查询到数据库,但我不想这样做,因为我会重复代码(在属性中查询用户)并且我需要使用我的应用程序中每个方法中的用户信息。
我希望我已经解释了自己,对不起我的英语不好
提前致谢:)
【问题讨论】:
-
您还可以在对用户进行身份验证后将有关用户的附加信息存储为声明。可以在您的操作方法中访问当前经过身份验证的用户的声明。
标签: c# asp.net-mvc asp.net-web-api http-token-authentication