gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:08:26 26 4
gpt4 key购买 nike

我在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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com