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

标签 asp.net-web-api auth0

我在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后再安装它并不是我想要承担的风险。如果由于某种原因无法升级到RC2,则希望可以将此示例 retrofit 为RC1。
好的,因此首先重要的是要了解,您可以检索到的有关用户的信息将仅限于JWT中包含的内容。因此,请确保在请求 token 时设置正确的范围。因此,例如,如果您想要用户的姓名和电子邮件地址,请确保将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);
如果您想从 Controller 操作内部访问信息,则可以简单地查看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
        };
    }
}
如果您需要访问有关用户的更多信息,则还可以将我们完整的.NET SDK用于Management API,并使用与用户相关的方法来检索更多用户信息。但是,我的建议是,宁可确保在颁发 token 时设置正确的作用域,并确保它们包含在JWT token 中。
完整的示例可从https://github.com/auth0-samples/auth0-aspnetcore-webapi-samples/tree/master/Samples/user-info获得。

关于asp.net-web-api - 使用ASP.NET MVC 6 WebAPI从Auth0获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37694139/

相关文章:

node.js - Auth0 和 React 的 CORS 问题

javascript - Auth0.js : Is there a way to silently replace a google access_token into an auth0 access_token?

angular2 - 考虑用对导出函数的引用替换函数或 lambda

reactjs - Auth0。如何获取访问 token 中用户的权限?

c# - 如何使用客户端证书在 Web API 中进行身份验证和授权

c# - 无法让 ASP.NET MVC 6 Controller 返回 JSON

asp.net-mvc-4 - HttpResponseException

cookies - 查找导致 Chrome 的 SameSite 警告的 cookie

c# - webapi 2.2所有属性路由添加任意路由前缀

angularjs - 如何在 adal-angular 的 httpinterceptor 发送的承载中添加声明