简体   繁体   English

在ASP.NET Core中进行身份验证后显示用户信息

[英]Displaying User Information after Authentication in ASP.NET Core

I have already implemented Identity with JWT token and secured the routes using [Authorize] attribute. 我已经使用JWT令牌实现了Identity,并使用[Authorize]属性保护了路由。 This works well. 这很好。 There are several tutorials on securing a route using JWT and Identity but I couldn't find any on how to let a particular user only access their own stuff after they have been authenticated. 关于如何使用JWT和Identity保护路由的教程,有几本,但是我找不到如何让特定用户仅在经过身份验证后才访问他们自己的内容的任何教程。

So far, I have done this: 到目前为止,我已经做到了:

    [Authorize]
    [HttpGet("protected")]
    public async Task<string> ProtectedArea()
    {
        var userName = User.Identity.Name;
        var user = repository.GetUserByEmail(userName);
//var user2 = _userManager.FindByIdAsync(userName); //user2.id gives null reference error
        return User.Bio;

    }

Here, GetUserByEmail is a simple method that returns the User object by querying the database(i couldn't get the UserManager to work here either to return the User using FindByEmailAsync as it would throw a null reference exception) 在这里, GetUserByEmail是通过查询数据库返回User对象的简单方法(我无法让UserManager在这里工作,也无法使用FindByEmailAsync返回User,因为它将抛出空引用异常)

Here's what my claims looks like: 这是我的claims

    var claims = new List<Claim>
    {
        new Claim(JwtRegisteredClaimNames.Sub, email),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
        new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
        new Claim(JwtRegisteredClaimNames.NameId, user.Id.ToString())

    };

So what is the standard way for identifying a user from the token and then go on to display that user's info? 那么,从令牌中识别用户然后继续显示该用户信息的标准方法是什么? What I have done above seems a little hacky to me but is it the right approach? 我在上面所做的事情对我来说似乎有点棘手,但这是正确的方法吗? Also, do I need to perform a check on every route and get the User Id via a method or is it possible to do so via some attribute as well? 另外,我是否需要对每条路线进行检查并通过方法获取用户ID,或者是否也可以通过某些属性来获取用户ID?

Any help would be greatly appreciated. 任何帮助将不胜感激。

The reason using UserManager failed was because you're attempting to get the user by id ( FindByIdAsync ), but supplying the username as the "id". 使用UserManager失败的原因是因为您试图通过id( FindByIdAsync )获取用户,但是将用户名提供为“ id”。 That will never match, so no user is returned and your variable is null. 那将永远不会匹配,因此不会返回任何用户,并且您的变量为null。 If you simply use FindByNameAsync instead, you'd be fine. 如果您只是使用FindByNameAsync代替,那就可以了。

However, there's actually an even easier way: 但是,实际上有一个更简单的方法:

var user = await _userManager.GetUserAsync(User);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM