【问题标题】:Get user information from Auth0 using ASP.NET MVC 6 WebAPI使用 ASP.NET MVC 6 WebAPI 从 Auth0 获取用户信息
【发布时间】:2016-10-08 05:28:37
【问题描述】:

我在我的 WebAPI (ASP.NET Core RC1) 中使用 JwtBearerAuthentication 来验证 (Auth0) 访问我的 API 的用户。在 Startup.cs 中,我使用以下代码配置与 Auth0 的连接。访问有关访问 API 的每个用户的用户信息时,我缺少什么?

app.UseJwtBearerAuthentication(options =>
            {
                options.AutomaticAuthenticate = true;
                options.AutomaticChallenge = true;
                options.Audience = clientId;
                options.Authority = domain;

                options.Events = new JwtBearerEvents
                {
                    OnValidatedToken = context =>
                    {
                        var claimsIdentity = context.AuthenticationTicket.Principal.Identity as ClaimsIdentity;
                        claimsIdentity.AddClaim(new Claim("id_token",
                            context.Request.Headers["Authorization"][0].Substring(context.AuthenticationTicket.AuthenticationScheme.Length + 1)));
                        return Task.FromResult(0);
                    }
                };
            });

【问题讨论】:

    标签: asp.net-web-api auth0


    【解决方案1】:

    首先很抱歉,我给您的示例位于 RC2 中。我的计算机上没有 RC1,我不想在安装 RC2 后安装它。如果您由于某种原因无法升级到 RC2,那么希望您可以将此示例改装为 RC1。

    好的,首先要了解的是,您可以检索到的有关用户的信息将仅限于 JWT 中包含的信息。因此,请务必在请求令牌时设置正确的范围。所以例如,如果你想要用户的姓名和电子邮件地址,请务必将scope 设置为openid name email

    好吧,如果你想访问OnTokenValidated事件里面的信息,那么你可以使用下面的代码:

    var options = new JwtBearerOptions
    {
        Audience = Configuration["auth0:clientId"],
        Authority = $"https://{Configuration["auth0:domain"]}/",
        Events = new JwtBearerEvents
        {
            OnTokenValidated = context =>
            {
                // If you need the user's information for any reason at this point, you can get it by looking at the Claims property
                // of context.Ticket.Principal.Identity
                var claimsIdentity = context.Ticket.Principal.Identity as ClaimsIdentity;
                if (claimsIdentity != null)
                {
                    // Get the user's ID
                    string userId = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
    
                    // Get the name
                    string name = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "name")?.Value;
                }
    
                return Task.FromResult(0);
            }
        }
    };
    app.UseJwtBearerAuthentication(options);
    

    如果您想从控制器操作中访问信息,您可以简单地查看User 的声明,例如

    public class ValuesController : Controller
    {
        [Authorize]
        [HttpGet]
        [Route("userinfo")]
        public object UserInformation()
        {
            string userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
    
            // Get the name
            string name = User.Claims.FirstOrDefault(c => c.Type == "name")?.Value;
    
            return new
            {
                UserId = userId,
                Name = name
            };
        }
    }
    

    如果您需要访问有关用户的更多信息,您还可以使用我们用于管理 API 的完整 .NET SDK 并使用与用户相关的方法来检索更多用户信息。不过,我的建议是确保在颁发令牌时设置正确的范围,并确保它们包含在 JWT 令牌中。

    完整示例可在https://github.com/auth0-samples/auth0-aspnetcore-webapi-samples/tree/master/Samples/user-info获取

    【讨论】:

    • 所以限制了我可以发布的链接数量。您可以在auth0.com/docs/scopes 获取有关范围的更多信息
    • 感谢您提供如此详细的回答 :) 我会尝试一下,并就我的进展与您联系。
    猜你喜欢
    • 2019-12-11
    • 2018-08-07
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2017-07-13
    • 2018-08-17
    • 1970-01-01
    相关资源
    最近更新 更多