0

In my ASP.NET Core web app, I want (a) the authorization middleware to take the unauthenticated user to the login endpoint first and (b) to return to the action after the successful login.

With the following code, (a) works as expected, but not sure how to return the caller action in the callback. I tried the suggested approaches here with no joy.

public class AccountController: ControllerBase
{
    [AllowAnonymous]
    [HttpGet]
    public IActionResult Signin()
    {
        var props = _signInManager.ConfigureExternalAuthenticationProperties(provider: GoogleDefaults.AuthenticationScheme);
        return new ChallengeResult(GoogleDefaults.AuthenticationScheme, props);
    }

    [AllowAnonymous]
    [HttpGet]
    public async Task<IActionResult> Callback()
    {
        var info = await _signInManager.GetExternalLoginInfoAsync();
        var user = new User
        {
            Email = info.Principal.FindFirstValue(ClaimTypes.Email),
            UserName = info.Principal.FindFirstValue(ClaimTypes.Email)
        };

        await _userManager.CreateAsync(user);
        await _signInManager.SignInAsync(user, isPersistent: true, authenticationMethod: null);
        return Ok(); 
    }

    [HttpGet]
    [Authorize]
    public async Task<IActionResult> GetUserProfile()
    {
        var user = User;
        return GetUserProfile(user);
    }
}

In other words, I want a call to GetUserProfile endpoint from an unauthenticated user to redirect to Sigin, then to Google login, then to Callback, then to GetUserProfile with the authenticated user information. I am not sure how to return to GetUserProfile (or any caller in general) from Callback.

I configure the authNZ services as the following if needed.

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
    options.LoginPath = "/api/v1/account/signin";
})
.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
{
    options.ClientId = GetGoogleClientId();
    options.ClientSecret = GetGoogleSecret();
});
Dr. Strangelove
  • 2,725
  • 3
  • 34
  • 61

0 Answers0