How to use ASP.NET Core Identity UserManager<ApplicationUser> through static method to get Identity User data from DB

huangapple go评论56阅读模式
英文:

How to use ASP.NET Core Identity UserManager<ApplicationUser> through static method to get Identity User data from DB

问题

我已经创建了一个 API(ASP.NET Core 6),并且还使用了 Identity 框架进行用户管理。管理员可以激活或停用用户,因此我希望在每次 API 调用时检查用户是否处于激活状态。因此,我创建了一个扩展方法,并在自定义授权属性的 onAuthorization 方法中调用此静态方法。在这里,我尝试解码令牌并从令牌中获取用户 ID。使用用户 ID,我调用扩展方法并在那里希望从数据库中获取用户并检查用户状态(激活/停用)。然而,我遇到了使用 UserManager<User>(初始化)的问题,因为它是一个静态方法。请问有人可以向我展示如何实现这一点吗?

自定义授权属性:

public void OnAuthorization(AuthorizationFilterContext context)
{
    var result = AuthExtension.ValidateUserStatus(context.HttpContext);
    if(result)
        return;
    else
        context.Result = new UnauthorizedResult();
}

扩展方法:

public static bool ValidateUserStatus(HttpContext context)
{
    var user = context.User;
    var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
    if(authHeader == null) return false;

    var token = authHeader.Split(" ")[1];
    var handler = new JwtSecurityTokenHandler();
    var securityToken = handler.ReadToken(token) as JwtSecurityToken;
    var userId = user.FindFirstValue("sid");

    var _userManager = new UserManager<User>(new UserStore<User>(new ApplicationDbContext(new DbContextOptions<ApplicationDbContext>(), new HttpContextAccessor())), null, new PasswordHasher<User>(), null, null, null, null, null, null);
    var dbUser = _userManager.FindByIdAsync(userId).Result;
    if (dbUser == null) return false;
    if (dbUser.RecordStatus == Domain.Entities.Enums.RecordStatus.Deleted) return false;

    return true;
}

希望这能帮助你解决问题。如果有其他问题,请随时提问。

英文:

I have created an API (ASP.NET core 6) and I have also used Identity framework for user management.
Admin can make users active or inactive. so I want to check if the user is active or not
in each API call. So I have created an extension method and I call this static method in onAuthorization method in custom authorize attribute.
There I try to decode the token and get user Id from token. Using the user id I call the extension method and there
I want to get the user from DB and check the user status(active/inactive). However I am facing the problem of using UserManager<User> (initializing) since it is
a static method. Please can somebody show me how to achive this?

Custom Authorize Attribute:

public void OnAuthorization(AuthorizationFilterContext context)
    {
        var result = AuthExtension.ValidateUserStatus(context.HttpContext);
        if(result)
            return;
        else
            context.Result = new UnauthorizedResult();
    }

Extension Method:

public static bool ValidateUserStatus(HttpContext context)
    {
        var user = context.User;
        var authHeader = context.Request.Headers[&quot;Authorization&quot;].FirstOrDefault();
        if(authHeader == null) return false;

        var token = authHeader.Split(&quot; &quot;)[1];
        var handler = new JwtSecurityTokenHandler();
        var securityToken = handler.ReadToken(token) as JwtSecurityToken;
        var userId = user.FindFirstValue(&quot;sid&quot;);

        var _userManager = new UserManager&lt;User&gt;(new UserStore&lt;User&gt;(new ApplicationDbContext(new DbContextOptions&lt;ApplicationDbContext&gt;(), new HttpContextAccessor())), null, new PasswordHasher&lt;User&gt;(), null, null, null, null, null, null);
        var dbUser = _userManager.FindByIdAsync(userId).Result;
        if (dbUser == null) return false;
        if (dbUser.RecordStatus == Domain.Entities.Enums.RecordStatus.Deleted) return false;

        return true;
    }

答案1

得分: 1

看起来初始化步骤引起了问题。如果您已在 Program.cs 中配置了身份服务,可以直接在您的方法中调用它。这是参考链接

另外,我认为您可以将初始化步骤移到 OnAuthorization 方法中:

public void OnAuthorization(AuthorizationFilterContext context)
{
    var userManager = context.HttpContext.RequestServices.GetService<UserManager<User>>();
    var result = AuthExtension.ValidateUserStatus(context.HttpContext, userManager);
    if (result)
        return;
    else
        context.Result = new UnauthorizedResult();
}

并且将扩展方法更改为:

public static bool ValidateUserStatus(HttpContext context, UserManager<User> userManager)
{
    .
    .
    .
    //var _userManager = new UserManager<User>(new UserStore<User>(new ApplicationDbContext(new DbContextOptions<ApplicationDbContext>(), new HttpContextAccessor())), null, new PasswordHasher<User>(), null, null, null, null, null, null);
    var dbUser = userManager.FindByIdAsync(userId).Result;
    if (dbUser == null) return false;
    if (dbUser.RecordStatus == Domain.Entities.Enums.RecordStatus.Deleted) return false;

    return true;
}
英文:

It seems that the initializing step causes the issue. If you have configured Identity services in Program.cs, you can directly call it in your method. Here is the reference link.

Also, I think you can move the initializing step to the OnAuthorization method:

public void OnAuthorization(AuthorizationFilterContext context)
{
    var userManager = context.HttpContext.RequestServices.GetService&lt;UserManager&lt;User&gt;&gt;();
    var result = AuthExtension.ValidateUserStatus(context.HttpContext, userManager);
    if (result)
        return;
    else
        context.Result = new UnauthorizedResult();
}

and change the Extension method to:

public static bool ValidateUserStatus(HttpContext context, UserManager&lt;User&gt; userManager)
{
    .
    .
    .
    //var _userManager = new UserManager&lt;User&gt;(new UserStore&lt;User&gt;(new ApplicationDbContext(new DbContextOptions&lt;ApplicationDbContext&gt;(), new HttpContextAccessor())), null, new PasswordHasher&lt;User&gt;(), null, null, null, null, null, null);
    var dbUser = userManager.FindByIdAsync(userId).Result;
    if (dbUser == null) return false;
    if (dbUser.RecordStatus == Domain.Entities.Enums.RecordStatus.Deleted) return false;

    return true;
}

huangapple
  • 本文由 发表于 2023年6月29日 00:08:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76574960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定