加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 使用ASP.NET MVC 6 WebAPI从Auth0获取用户信

发布时间:2020-12-16 03:29:36 所属栏目:asp.Net 来源:网络整理
导读:我在我的WebAPI(ASP.NET Core RC1)中使用JwtBearerAuthentication来验证访问我的API的(Auth0)用户.在Startup.cs中,我使用以下代码配置与Auth0的连接.访问API的每个用户访问用户信息我缺少什么? app.UseJwtBearerAuthentication(options = { options.Automat
我在我的WebAPI(ASP.NET Core RC1)中使用JwtBearerAuthentication来验证访问我的API的(Auth0)用户.在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);
                    }
                };
            });

解决方法

首先,我给你的样品是在RC2中道歉.我的计算机上没有RC1,安装RC2后安装RC1并不是我想要的风险.如果由于某种原因无法升级到RC2,那么希望您可以将此示例改装为RC1.

好的,首先要了解您可以检索的有关用户的信息将仅限于JWT中包含的信息.因此,请务必在请求令牌时设置正确的范围.例如,如果您需要用户的姓名和电子邮件地址,请务必将范围设置为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);

如果您想从控制器操作中访问信息,您只需查看用户的声明,例如

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

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

完整样品可在https://github.com/auth0-samples/auth0-aspnetcore-webapi-userinfo获得

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读