We are using .NET Core 3.1 and Google Authentication. This is the code that we have currently:
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();
}
}
When users visit /Account/SignInGoogle
, they are redirected to Google sign in page. Once they log in successfully, they are redirected back to /Account/SignInReturn
. If I place a breakpoint there, I can see that claims are set inside User
property.
However, we don't want the User
property to be automatically set. We also don't want that the user is considered as logged-in once SignInReturn
is called. We would just like to receive information about the user (name, surname, email) and then proceed with our custom claims handling logic. Is it possible?
CodePudding user response:
You can access the tokens by handling the OnCreatingTicket
event:
googleOptions.Events.OnCreatingTicket = (context) =>
{
string accessToken = context.AccessToken;
string refreshToken = context.RefreshToken;
// do stuff with them
return Task.CompletedTask;
}
Note that you don't get the refresh token unless you specify googleOptions.AccessType = "offline";
and even then you only get them when you first consent (you can trigger reconsent if you require the refresh token).
Or you can follow the approach set out by Microsoft, which basically saves the tokens in a cookie. You can read about that in the documentation here.
CodePudding user response:
Google auth uses the OAuth2 protocol. The Google Authentication package just wraps OAuth in an AuthenticationBuilder setup. By using any OAUth2 library you can authenticate outside of the AspNetCore AuthenticationBuilder and retrieve the JWT.
See also: What is the best OAuth2 C# library?