Don Box
Don Box

Reputation: 3336

ASP.NET Core authentication with Google only for a specific account

In my ASP.NET Core 3 app, I'd like to implement login with Google and only allow authentication for specific user(s).

What I did so far is to follow the tutorial from:

https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/social-without-identity?view=aspnetcore-3.0 https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins?view=aspnetcore-3.0

What are the next steps to make the user authorized only for specific Google account(s)? Even if the user is authenticated successfully by Google, I want only specific Google account(s) (email addresses) to have access to my ASP.NET Core app.

What I tried was to set a delegate to the 'OnCreatingEvent' event, but I don't know how to reject authorization.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddGoogle(options =>
            {
                options.ClientId = Configuration["google-credentials:ClientId"]; 
                options.ClientSecret = Configuration["google-credentials:ClientSecret"];
                options.Events = new OAuthEvents()
                {
                    OnCreatingTicket = HandleOnCreatingTicket
                };
            });
private async Task HandleOnCreatingTicket(OAuthCreatingTicketContext context)
        {
            var user = context.Identity;

            if (user.Claims.FirstOrDefault(m => m.Type == ClaimTypes.Email).Value != "MY ACCOUNT")
            {
                // How to reject authorization?
            }

            await Task.CompletedTask;
        }

Upvotes: 5

Views: 2130

Answers (1)

Nan Yu
Nan Yu

Reputation: 27578

You can create a policy to check whether user's name claim is in your allowed user name list , return true/false base on your validation result :

services.AddAuthorization(options =>
{
    options.AddPolicy("AllowedUsersOnly", policy =>
    {
        policy.RequireAssertion(context =>
        {
            //Here you can get many resouces from context, i get a claim here for example
            var name = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;

            //write your logic to check user name .


            return false;
        });
    });
}); 

Then you could apply policy on your controller/action or register global filter .

Upvotes: 3

Related Questions