Friday, April 24, 2020

External Authentication in ASPMVC Net Core

In the StartUp.cs file a few additions are needed to make external authorization work. First, this section needs to be added to the ConfigureServices method:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
    options.LoginPath = "/auth";
    options.ReturnUrlParameter = "ReturnUrl";
})
.AddGoogle(options => {
    options.ClientId = "[yourclientid]";
    options.ClientSecret = "[yoursecret]";
    options.CallbackPath = "/auth/signin-google";
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})

And later on in the Configure method make sure these lines are added.

app.UseAuthentication();
app.UseAuthorization();

Note that /auth/signin-google is not a path supplied by the application. Instead the mvc middleware handles this return and hands control over to /auth/afterauth (as specified in the RedirectUri of the Challenge result. This section goes in the auth controller:

public IActionResult GoogleLogin(string returnUrl= "/")
{
    return new ChallengeResult("Google", new AuthenticationProperties {
        RedirectUri = Url.Content($"/auth/afterauth?provider=Google&returnUrl={returnUrl}")
    });
}

No comments:

Post a Comment