• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

发送用户ID和access_token

用户头像
it1352
帮助1

问题说明

我正在使用React前端在ASP.NET Core 2.1应用中实现Auth0.

I'm implementing Auth0 in my ASP.NET Core 2.1 app with React front-end.

用户进行身份验证后,我会得到一个access_token和一个id_token.我很清楚access_token的目的是授予对我的API方法的访问权限.我也了解id_token提供了可以在前端应用程序中使用的用户数据.

Once the user authenticates, I get both an access_token and an id_token. I'm clear that the purpose of access_token is to grant access to my API methods. I also understand that the id_token provides user data which I can use in my front-end app.

问题/关注点是有关在进行API调用时将用户数据(例如userId)发送到后端的问题.除了将userId包含在我的POST请求的正文中之外,还有其他方法可以将其发送到我的API方法吗?

The question/concern is about sending user data, such as userId to my backend when I make API calls. Other than including userId in the body of my POST request, is there another way to send it to my API method?

在Auth0之前,我使用了其他一些解决方案,并且从它们那里收到的JWT token总是包括userIdusername等.我认为这是一种更安全的方法,因为即使有人可以看到在JWT token中,签名使我们可以确保不对数据进行回火.

Prior to Auth0, I used a couple of other solutions and the JWT token I received from them always included userId, username, etc. I thought this was a more secure approach because even though one can see what's in a JWT token, the signature allows us to make sure the data is not temperered with.

即使我的API调用是通过SSL保护的,但与通过JWT token发送它相比,在我的请求正文中包含进行API调用的人的userId还是不太安全.

Even though my API calls are secured through SSL, I feel including the userId of the person who's making the API call in the body of my request is less secure compared to sending it through a JWT token.

我在这里遗漏了一些东西吗,还是我们确实通过常规方法在API调用中(即在POST调用的正文中或在GET调用的查询字符串中)通过常规方式发送了userId?

Am I missing something here or do we indeed send the userId through the regular means in an API call i.e. in the body of a POST call or in the query string of a GET call?

正确答案

#1

很好的问题,我上周遇到了同样的问题,最后使用相同的JWTAccessToken弄清楚了.

Good question man, i was going through the same problem last week and finally figured it out using the same JWTAccessToken.

难点在于,在生成可在服务器中检索的访问令牌时,将经过身份验证的用户的 UserId 添加为声明.

The catch is in adding the UserId of the authenticated user as a claim when generating an access token which you can retrieve in the server.

添加声明以访问令牌

首先将用户的ID添加到您的声明列表中.

Add the user's id to your list of claims first.

List<Claim> claims = new List<Claim>();
claims.Add(new Claim("UserId", user.Id.ToString()));

然后生成访问令牌.

SecurityToken token = new JwtSecurityToken(
                        issuer: {YOUR_ISSUER},
                        audience: {YOUR_AUDIENCE},
                        claims: claims,
                        notBefore: DateTime.UtcNow,
                        expires: DateTime.UtcNow.AddMinutes(60),
                        signingCredentials: credentials
                     );

假设您已经知道如何在达到最终的代币生成之前执行这些步骤,这要从您在问题中所显示的oAuthJWT的才能中扣除.

Am assuming you already know how to perform the steps before reaching this final token generation as deducted from your prowess of oAuth and JWT shown above in your question.

从访问令牌中检索版权声明

要从其access_token中读取 UserId ,我们创建几个帮助程序/扩展方法,以帮助我们从控制器的RequestContext中读取access_token.

To read a UserId from their access_token, let's create a couple of helper/extension methods to help us in reading an access_token from the RequestContext of a controller.

public static string GetUserId(this ControllerBase controller)
{
    string securityKey = "{YOUR_SECURITY_KEY}";
    SymmetricSecurityKey key = new SymmetricSecurityKey(new UTF8Encoding().GetBytes(securityKey));
    JwtSecurityTokenHandler token_handler = new JwtSecurityTokenHandler();

    var tokenValidationParams = new TokenValidationParameters
    {
        ValidateAudience = false,
        ValidateIssuer = false,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = key,
        ValidateLifetime = false
    };

    string bearer = controller.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer", string.Empty).Trim(' ');

    List<Claim> claims = token_handler.ValidateToken(bearer, tokenValidationParams, out SecurityToken token).Claims.ToList();

    Claim userClaim = claims.FirstOrDefault(x => x.Type == "UserId");

    if(userClaim != null)
    {
        return userClaim.Value;
    }
    else
    {
        throw new Exception("Invalid AccessToken. UserId claim not found");
    }
}

使用方法

现在让我们使用它来获取我们任意一个控制器中的 UserId :

Let's now use this to get the UserId in any of our controllers:

[Authorize]
public class ExampleController : Controller
{
    public IActionResult Index()
    {
        string userId = this.GetUserId();

        // --> continuing code goes here.
    }
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfieca
系列文章
更多 icon
同类精品
更多 icon
继续加载