Skip to content

Back end google token validation #107

Open
@valentasm1

Description

@valentasm1

I spend some time finding solution. I post it here so maybe it will help to someone.

Problem. Mobile App google authentication and same google account validation on back end with token from mobile. It is just general idea without specific parts which could vary on solution.

Mobile Setup:
Create Web Application and android as described in readme. I dont use secret since works without it. Also i recommend to use same signing key(keystore) for debug and release and use these for setup google driod hash.

Login in app

string droidClientId = "871919386588-465sq7xxxxxxxxxxxxxapps.googleusercontent.com";
string webClientId = "871919386588-d7dofotb06xxxxxxxxxer1o8h57m.apps.googleusercontent.com";

var api = new GoogleApi("google", droidClientId)
{
	ServerClientId = webClientId,
	Scopes = new[]
	{
		"https://www.googleapis.com/auth/userinfo.email",
		"https://www.googleapis.com/auth/userinfo.profile"
	},
};

and authenticate like this

var account = await api.Authenticate() as OAuthAccount;
var serverToken = account.IdToken;

serverToken is token which should be validated in back end. It should be very long stiring with two . in it (3 parts Header, Payload, and Signature).

BackEnd Setup
Download nuget Google.Apis.Oauth2.v2

Pass and validate token in back end. I am not validating if token is expered, claims and other. Just to show main idea.

public async Task<bool> Validate(string token)
{

	GoogleJsonWebSignature.Payload payload = new GoogleJsonWebSignature.Payload();
	try
	{
		payload = await GoogleJsonWebSignature.ValidateAsync(token);
		return true;
	}
	catch (InvalidJwtException exception)
	{
		Console.WriteLine(exception);
	}
	return false;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions