gpt4 book ai didi

asp.net-core - 使用 AspNet Core 2.0 进行 Google JWT 身份验证

转载 作者:行者123 更新时间:2023-12-01 18:06:12 28 4
gpt4 key购买 nike

我正在尝试将 google 身份验证集成到我的 ASP.NET Core 2.0 Web api 中,但我不知道如何让它工作。

我的 Startup.cs ConfigureServices 中有此代码:

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDefaultTokenProviders();

services.AddAuthentication()
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});

这在 Configure(IApplicationBuilder app, IHostingEnvironment env) 中:

 app.UseAuthentication();

当我导航到Authorized端点时,结果是302 Found,因为大概它正在重定向到某个登录端点(我从未创建过)。如何防止重定向,并让 API 接受 token 并在未提供 token 的情况下返回 401

最佳答案

为后代发布我的终极方法。

正如特拉彻指出的那样,AddGoogle中间件实际上并不用于 JWT 身份验证流程。经过更多研究后,我意识到我最终想要的是这里描述的内容: https://developers.google.com/identity/sign-in/web/backend-auth

所以我的下一个问题是

  1. 我不能再依赖标准的 dotnet core Jwt auth 中间件,因为我需要将 google token 验证委托(delegate)给 google 库
  2. 该页面上没有将 C# google 验证器列为外部客户端库之一。

经过更多挖掘,我发现 JWT 验证支持已添加到 C# here使用这个类和方法: Google.Apis.Auth.Task<GoogleJsonWebSignature.Payload> ValidateAsync(string jwt, GoogleJsonWebSignature.ValidationSettings validationSettings)

接下来我需要弄清楚如何替换内置的 JWT 验证。从这个问题我想出了一个方法: ASP.NET Core JWT Bearer Token Custom Validation

这是我的自定义 GoogleTokenValidator:

public class GoogleTokenValidator : ISecurityTokenValidator
{
private readonly JwtSecurityTokenHandler _tokenHandler;

public GoogleTokenValidator()
{
_tokenHandler = new JwtSecurityTokenHandler();
}

public bool CanValidateToken => true;

public int MaximumTokenSizeInBytes { get; set; } = TokenValidationParameters.DefaultMaximumTokenSizeInBytes;

public bool CanReadToken(string securityToken)
{
return _tokenHandler.CanReadToken(securityToken);
}

public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
validatedToken = null;
var payload = GoogleJsonWebSignature.ValidateAsync(securityToken, new GoogleJsonWebSignature.ValidationSettings()).Result; // here is where I delegate to Google to validate

var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, payload.Name),
new Claim(ClaimTypes.Name, payload.Name),
new Claim(JwtRegisteredClaimNames.FamilyName, payload.FamilyName),
new Claim(JwtRegisteredClaimNames.GivenName, payload.GivenName),
new Claim(JwtRegisteredClaimNames.Email, payload.Email),
new Claim(JwtRegisteredClaimNames.Sub, payload.Subject),
new Claim(JwtRegisteredClaimNames.Iss, payload.Issuer),
};

try
{
var principle = new ClaimsPrincipal();
principle.AddIdentity(new ClaimsIdentity(claims, AuthenticationTypes.Password));
return principle;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;

}
}
}

Startup.cs ,我还需要清除默认的 JWT 验证,并添加我的自定义验证:

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

})
.AddJwtBearer(o =>
{
o.SecurityTokenValidators.Clear();
o.SecurityTokenValidators.Add(new GoogleTokenValidator());
}

也许有一种更简单的方法,但这就是我着陆的地方,它似乎工作得很好!为了简单起见,我还做了一些额外的工作,例如,检查我的用户数据库中是否已经有一个用户与谷歌提供的声明相匹配,所以如果上面的代码不能 100% 工作,我深表歉意我可能无意中删除了一些东西。

关于asp.net-core - 使用 AspNet Core 2.0 进行 Google JWT 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48727900/

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