.NET Core External Authentication without ASP.NET Identity

前端 未结 1 1237
太阳男子
太阳男子 2021-02-05 13:53

I use my own JWT token authentication and not the asp.net identity that comes free with the default template. I\'ve looked everywhere for some documentation/guidence on how to i

相关标签:
1条回答
  • 2021-02-05 14:27

    To solve the:

    No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Bearer

    I had to add a cookie handler that will temporarily store the outcome of the external authentication, e.g. the claims that got sent by the external provider. This is necessary since there are typically a couple of redirects involved until you are done with the external authentication process.

    Startup

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
    {
        o.TokenValidationParameters = tokenValidationParameters;
    })
    .AddCookie()
    .AddGoogle(googleOptions =>
    {
        googleOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        googleOptions.ClientId = "x";//Configuration["Authentication:Google:ClientId"];
        googleOptions.ClientSecret = "x";//Configuration["Authentication:Google:ClientSecret"];
        //googleOptions.CallbackPath = "/api/authentication/externalauthentication/signin-google";
    });
    

    The important part here is CookieAuthenticationDefaults.AuthenticationScheme. This is a string constant that stores "Cookies". While we can directly use the string "Cookies" within our code, using the preset constant would be safer. This is the authentication scheme name given to the AddCookies function by default. It helps you reference the cookies authentication.

    Now it's time to retrieve the user information from the claims provided by the external authentication in the callback action.

    Controller

    [AllowAnonymous]
    [HttpPost(nameof(ExternalLogin))]
    public IActionResult ExternalLogin(ExternalLoginModel model)
    {
        if (model == null || !ModelState.IsValid)
        {
            return null;
        }
    
        var properties = new AuthenticationProperties { RedirectUri = _authenticationAppSettings.External.RedirectUri };
    
        return Challenge(properties, model.Provider);
    }
    
    [AllowAnonymous]
    [HttpGet(nameof(ExternalLoginCallback))]
    public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
    {
        //Here we can retrieve the claims
        var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    
        return null;
    }
    

    Voilà! We now have some user information to work with!

    Helpful link

    http://docs.identityserver.io/en/latest/topics/signin_external_providers.html

    0 讨论(0)
提交回复
热议问题