Mik*_*g36 5 google-api google-authentication oauth-2.0 asp.net-core asp.net-core-2.0
我试图在我的ASP.NET Core 2.0 web api中集成google身份验证,我无法弄清楚如何让它工作.
我在我的Startup.cs中有这个代码ConfigureServices
:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDefaultTokenProviders();
services.AddAuthentication()
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});
Run Code Online (Sandbox Code Playgroud)
这个在Configure(IApplicationBuilder app, IHostingEnvironment env)
:
app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)
当我导航到Authorized
端点时,结果是302 Found
因为它可能是重定向到某个登录端点(我从未创建过).如何阻止重定向,只是让API期望一个令牌,401
如果没有提供令牌,则返回一个令牌?
Mik*_*g36 14
为后代发布我的终极方法.
正如Tratcher指出的那样,AddGoogle
中间件实际上并不适用于JWT身份验证流程.经过更多的研究,我意识到我最终想要的是这里描述的内容:https:
//developers.google.com/identity/sign-in/web/backend-auth
所以我的下一个问题是
更挖掘后,我发现这是智威汤逊验证支持添加到C#在这里使用这个类和方法:
Google.Apis.Auth.Task<GoogleJsonWebSignature.Payload> ValidateAsync(string jwt, GoogleJsonWebSignature.ValidationSettings validationSettings)
接下来我需要弄清楚如何替换内置的JWT验证.从这个问题我想出了一个方法: ASP.NET核心JWT承载令牌自定义验证
这是我的自定义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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在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());
}
Run Code Online (Sandbox Code Playgroud)
也许有一种更简单的方法,但这是我降落的地方,似乎工作正常!我做了额外的工作,为了简单起见,我离开了这里,例如,检查我的用户的数据库中是否已有用户与谷歌提供的声明匹配,所以如果上面的代码不是100%工作,我很抱歉我可能无意中删除了一些东西.
khe*_*ang 10
我刚刚发布了一个NuGet包来处理Google OpenID Connect令牌的验证.
该软件包依赖于微软的智威汤逊验证和认证处理Microsoft.AspNetCore.Authentication.JwtBearer,并增加了一些验证周围托管域.
它包含一个单一的公共扩展方法UseGoogle
,就JwtBearerOptions
可以让你配置该处理程序来验证谷歌ID连接令牌,没有其他的依赖关系:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(jwt => jwt.UseGoogle(
clientId: "<client-id-from-Google-API-console>",
hostedDomain: "<optional-hosted-domain>"));
Run Code Online (Sandbox Code Playgroud)
如果您想查看源代码,可以在此处找到它.
归档时间: |
|
查看次数: |
5314 次 |
最近记录: |