ProShav
ProShav

Reputation: 13

Google OAuth2 in external window Asp.Net Core

I'm trying to implement google oauth external authorization to happen in external browser window. My code looks like below:

$('#signinButton').click(function () {
    window.auth2.grantOfflineAccess()
        .then(signInCallback)
        .catch(error => console.log(error));
});
function start() {
    gapi.load('auth2', function () {
        window.auth2 = gapi.auth2.init({
            client_id: 'CLIENT_Id'
        });
    });
};
function signInCallback(authResult) {
    if (authResult['code']) {
        var authCode = authResult['code'];

        $.ajax({
            type: 'POST',
            url: '/Auth/GooglePostredirect',
            data: authCode,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            contentType: 'application/octet-stream; charset=utf-8',
            success: function (result) {
            },
            processData: false,
        });
    } else {

    }
};

And the question is after getting authToken, how i should call google api to get user info by auth token. Is there any handy libraries for that? I can't find any to request userInfo by token from c#.
Thanks you all in advance!

Upvotes: 0

Views: 217

Answers (1)

Mateech
Mateech

Reputation: 1064

You can use Google.Apis.Auth library from nuget package manager, and get info from google token, which you get from your front-end

google auth library

public async Task<IActionResult> ExternalLoginGoogleAsync(string googleTokenId)
    {
        GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();
        settings.Audience = new List<string>() { Configuration["Authentication:Google:ClientId"] };
        GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(googleTokenId, settings);

        ApplicationUser user = await _userManager.FindByEmailAsync(payload.Email);
        if (user == null) //create new user if not exsits
        {
            user = new ApplicationUser
            {
                Email = payload.Email,
                UserName = payload.Name                            
            };                
            ...
        }                       
        return Ok(something);
    }

Upvotes: 1

Related Questions