简体   繁体   English

发送用户ID和access_token

[英]Sending user Id along with access_token

I'm implementing Auth0 in my ASP.NET Core 2.1 app with React front-end. 我正在使用React前端在ASP.NET Core 2.1应用程序中实现Auth0。

Once the user authenticates, I get both an access_token and an id_token . 用户认证后,我将同时获得一个access_token和一个id_token I'm clear that the purpose of access_token is to grant access to my API methods. 我很清楚access_token的目的是授予对我的API方法的访问权限。 I also understand that the id_token provides user data which I can use in my front-end app. 我也了解id_token提供了可以在前端应用程序中使用的用户数据。

The question/concern is about sending user data, such as userId to my backend when I make API calls. 问题/关注点是有关在进行API调用时将用户数据(例如userId发送到后端的问题。 Other than including userId in the body of my POST request, is there another way to send it to my API method? 除了在POST请求的主体中包含userId ,还有另一种方法可以将其发送到我的API方法吗?

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. 在Auth0之前,我使用了其他一些解决方案,并且从它们那里收到的JWT token始终包含userIdusername等。我认为这是一种更安全的方法,因为即使可以看到JWT token ,签名也可以我们确保数据不会受到控制。

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调用是通过SSL保护的,但与通过JWT token发送相比,在我的请求正文中包含进行API调用的人员的userId仍然不那么安全。

Am I missing something here or do we indeed send the userId through the regular means in an API call ie in the body of a POST call or in the query string of a GET call? 我是否在这里丢失了某些信息,还是我们确实通过常规方式在API调用中(即在POST调用的正文中或在GET调用的查询字符串中)发送了userId

Good question man, i was going through the same problem last week and finally figured it out using the same JWTAccessToken . 好问的人,我上周遇到了同样的问题,最后使用相同的JWTAccessToken

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. 要注意的是,在生成可以在服务器中检索到的访问令牌时,将经过身份验证的用户的UserId作为声明添加。

Adding Claims To Access Token 添加声明以访问令牌

Add the user's id to your list of claims first. 首先将用户ID添加到您的声明列表中。

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

Then generate an access token. 然后生成访问令牌。

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

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. 假设您已经从问题中上面显示的oAuthJWT能力中扣除了,那么在达到最终令牌生成之前,您已经知道如何执行这些步骤。

Retrieve Claim From 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. 要从其access_token读取UserId ,让我们创建几个帮助器/扩展方法,以帮助我们从控制器的RequestContext读取access_token。

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");
    }
}

How To Use 如何使用

Let's now use this to get the UserId in any of our controllers: 现在让我们使用它在我们的任何控制器中获取UserId

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

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

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

相关问题 如何从 JWT access_token(bshaffer oauth 库)中提取 user_id - How to extract user_id from JWT access_token (bshaffer oauth library) 如何使用 &#39;id_token&#39;、&#39;access_token&#39;、expiry 等直接创建 userManager? - How can create userManager directly with 'id_token', 'access_token', expiry etc.? 在 AWS Lambda 中使用 id_token 与 access_token 的最佳实践 - Best practice for id_token vs. access_token use in AWS Lambda 如何从access_token反向查找用户(Rails,Devise) - How to reverse look up a user from an access_token (Rails, Devise) oauth 2.0 access_token IP是否依赖于IP? - Is oauth 2.0 access_token IP dependant or not? Twitter oauth / access_token 401错误 - Twitter oauth/access_token 401 Error SpringMVC REST access_token和会话 - SpringMVC REST access_token and session Python 带身份验证的请求 (access_token) - Python request with authentication (access_token) 来自 https://www.googleapis.com/oauth2/v4/token 的意外响应。 不给“access_token”,只给“id_token” - Unexpected Response from https://www.googleapis.com/oauth2/v4/token. Not giving "access_token", only "id_token" Nest js通过google access_token保护对路由的访问 - Nest js protect access to route via google access_token
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM