Signing in with Google, only allowing organizational domains Accounts

Viewed 215

I am trying to create a web application that can only be accessed by signing in with Google and only be able to use a GSuite (organisational domains). I would like for this to be done, without initialising which domains are allowed beforehand, meaning that it allows all of the email addresses registered under Google, but not "gmail.com".

Thank you for your help.

2 Answers

I assume you're using OpenID Connect? Then you can use the hd parameter and claim:

The hd (hosted domain) parameter streamlines the login process for G Suite hosted accounts. By including the domain of the G Suite user (for example, mycollege.edu), you can indicate that the account selection UI should be optimized for accounts at that domain.

[...]

Be sure to validate that the returned ID token has an hd claim value that matches what you expect (e.g. mycolledge.edu). Unlike the request parameter, the ID token hd claim is contained within a security token from Google, so the value can be trusted.

The hd claim contains the primary domain name of the user's Cloud Identity/Workspace account. If there is a hd claim in the ID token, it's a managed user account, if there is no hd claim, it's a consumer account.

Note that checking the domain part of an email address is not a reliable way to determine whether somebody is using a managed user account or a consumer account: bob@example.com could be a consumer account or a managed account, there's no way to tell just from looking at the email address.

I think you could write some codes inside the asp.net core application to check the account Email is google or not.

Like below ConfigureServices method add below codes:

        services.AddAuthentication()
.AddGoogle(options =>
{
    IConfigurationSection googleAuthNSection =
        Configuration.GetSection("Authentication:Google");

    options.ClientId = googleAuthNSection["ClientId"];
    options.ClientSecret = googleAuthNSection["ClientSecret"];

    options.Events.OnTicketReceived = onticketreceived;
});

    }

onticketreceived method to check the Email, then decide the authentication result is success or not.

    private Task onticketreceived(TicketReceivedContext context) {
        var receivedClaims = context.Principal.Claims;
        string emailClaim = receivedClaims.FirstOrDefault(x => x.Type == "email").Value;
        //then you could do something to according to this email
       
        return Task.CompletedTask;

    }
Related