从Google auth接收JWT令牌,而不是接收声明



我们使用。net Core 3.1和Google Authentication。这是我们当前的代码:

Startup.cs:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = "CLIENT_ID"
googleOptions.ClientSecret = "CLIENT_SECRET"
})
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Error/403";
});

AccountController.cs:

public class AccountController : BaseController
{
[AllowAnonymous]
public IActionResult SignInGoogle()
{
return Challenge(new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(SignInReturn))
}, GoogleDefaults.AuthenticationScheme);
}
[AllowAnonymous]
public IActionResult SignInReturn()
{
// Do stuff with the user here. Their information is in the User    
// property of the controller.
return Ok();
}
}

当用户访问/Account/SignInGoogle时,他们被重定向到Google sign in页面。一旦他们成功登录,他们将被重定向回/Account/SignInReturn。如果我在那里放置一个断点,我可以看到声明是在User属性中设置的。

但是,我们不希望自动设置User属性。我们也不希望在调用SignInReturn后用户被认为已经登录。我们只希望接收有关用户的信息(姓名、姓氏、电子邮件),然后继续进行自定义索赔处理逻辑。这可能吗?

Google auth使用OAuth2协议。Google Authentication包只是将OAuth封装在AuthenticationBuilder设置中。通过使用任何OAUth2库,您可以在AspNetCore AuthenticationBuilder之外进行身份验证并检索JWT。

参见:什么是最好的OAuth2 c#库?

您可以通过处理OnCreatingTicket事件来访问令牌:

googleOptions.Events.OnCreatingTicket = (context) =>
{
string accessToken = context.AccessToken;
string refreshToken = context.RefreshToken;
// do stuff with them
return Task.CompletedTask;
}

请注意,除非您指定googleOptions.AccessType = "offline";,否则您不会获得刷新令牌,即使这样,您也只能在您第一次同意时获得它们(如果您需要刷新令牌,您可以触发重新同意)。

或者您可以遵循Microsoft设置的方法,它基本上将令牌保存在cookie中。你可以在这里的文档中阅读到。

最新更新