基于 Shaun Luttin 在 https://stackoverflow.com/a/30857524 上的出色示例我能够使用该代码生成和使用不记名 token 。较小的更改是获取最新的软件包:
"dependencies": {
"Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-rc1-final",
"AspNet.Security.OpenIdConnect.Server": "1.0.0-beta4"
}
尽管代码是一个很好的开始,但它并不是一个完全集成了 ASP.NET Identity 的完整解决方案。我修改 AuthorizationProvider 类如下:
public override Task GrantResourceOwnerCredentials(
GrantResourceOwnerCredentialsContext context)
{
var user = _userManager.FindByNameAsync(context.UserName).Result;
if (user == null)
{
context.Rejected("The user name or password is incorrect.");
}
else
{
var signInManager = context.HttpContext.RequestServices
.GetRequiredService<SignInManager<ApplicationUser>>();
if (signInManager.CanSignInAsync(user).Result &&
_userManager.CheckPasswordAsync(user, context.Password).Result)
{
var principal = signInManager.CreateUserPrincipalAsync(user).Result;
//To avoid leaking confidential data, AspNet.Security.OpenIdConnect.Server
//refuses to serialize the claims that don't explicitly specify a destination.
foreach (var claim in principal.Claims)
claim.WithDestination("token id_token");
context.Validated(principal);
}
else
context.Rejected("The user name or password is incorrect.");
}
return Task.FromResult(0);
}
我正在使用 CreateUserPrincipalAsync 为 Validated 方法创建 ClaimsPrincipal。有没有更好的方法来集成 ASP.NET Identity?
最佳答案
您的实现看起来不错,有 3 条小注释:
async/await
避免 .Result
阻止调用。 最后两点在
OpenIddict
中得到缓解。 (一个全新的实验性 OIDC 服务器,内部使用 AspNet.Security.OpenIdConnect.Server
),所以不要犹豫,看看它的默认实现:https://github.com/openiddict/core/blob/dev/src/OpenIddict.Core/OpenIddictProvider.cs#L353 .
关于asp.net-core - 带有 ASP.NET Identity 3 的 JWT 不记名 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34031776/