-->

Implementing social login in asp.net core 2.2 with

2020-08-03 04:32发布

问题:

I am trying to implement social login features in asp.net core 2.2 without using default feature as given here. I couldn't find any where that shows implementation without using default identity.

I have already implemented custom login mechanism to handle user authentication, i.e. there is a user table that stores emailid and its password. When user login it will validate from user table entry. In the same way I want to implement social logins like facebook, twitter, linkedin, microsoft, github etc.

Once user signin using any of these social options there email will be stored in user table with their valid token.

I am able to triggered social login using this article but not able to redirect back to correct action method. Its redirecting back to same action method "IActionResult Google" from where its originated. I couldn't understand "ExternalLoginCallback".

I need to get the response returned by the social login and to retrieve user details.

    public IActionResult Google(string provider)
    {
        provider = "Google";
        //Issue a challenge to external login middleware to trigger sign in process
        return new ChallengeResult(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;
    }

回答1:

The basic idea is your can use AddOAuth or AddOpenIdConnect middleware to trigger the social logins .

For example , if using OAuth 2 flow , you can use AddOAuth extension to make consume the identity provider like facebook , microsoft .... you can acquire access token which could get the current user's basic profile information , in OnCreatingTicket callback function , you can query your local database , link/create the external user in your database , and finally create authentication ticket for user sign-in . For example :

https://www.jerriepelser.com/blog/authenticate-oauth-aspnet-core-2/

That is similar if using OpenID Connect , the difference is you can directly get user's information in ID token :

services.AddAuthentication()
    .AddCookie()
    .AddOpenIdConnect();

You can click here and here code samples .

You can config multi authentication schema for different providers based on your requirements.