Check claims (email) before creating a new cookie, without asp. core identity store using asp net core social login

Bipn Paul

I'm working on my hobby project where I'have implemented social login via Google.

now I want to prevent this so that only certain user can sign in into the app, As I found that there is no way to restrict this on google OAuth side, So I have added a table to store the email and role.

if the email address is not found in that table I want to prevent a user from signing.

            services
           .AddAuthentication(options =>
           {
               options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
           })
           .AddCookie()
           .AddGoogle(googleOption =>
           {

               googleOption.ClientId = Configuration["Authentication:Google:ClientID"]; ;
               googleOption.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
               googleOption.Events.OnRemoteFailure = (context) =>
               {
                   context.HandleResponse();
                   return context.Response.WriteAsync("<script>window.close();</script>");
               };
               googleOption.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
               {
                   OnTicketReceived = async ctx =>
                   {
                       string emailAddress = ctx.Principal.
                                               FindFirstValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress");
                       var db = ctx.HttpContext.RequestServices.GetRequiredService<DbContext>();
                       var roles = await db.EmailRoles.Where(c => c.Email == emailAddress).ToListAsync();
                       if (roles.Count > 1)                           
                       {
                           var claims = new List<Claim>();
                           foreach (var item in roles)
                           {
                               claims.Add(new Claim(ClaimTypes.Role, item.Role));
                           }
                           var appIdentity = new ClaimsIdentity(claims);
                           ctx.Principal.AddIdentity(appIdentity);
                       }
                   }
               };
           });
DaImTo

I think you are looking for OnCreatingTicket. this will allow you to test the users as their logging in. In this example only gmail.com emails would be allowed to login anyone else would be kicked out

 services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddGoogle("Google", options =>
        {
            options.ClientId = Configuration["Authentication:Google:ClientId"];
            options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
            options.Events = new OAuthEvents
            {
                OnCreatingTicket = context =>
                {
                    string domain = context.User.Value<string>("domain");
                    if (domain != "gmail.com")
                        throw new GoogleAuthenticationException("You must sign in with a gmail.com email address");

                    return Task.CompletedTask;
                }
            };
        });

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to refresh CSRF token on login when using cookie authentication without identity in ASP .NET Core Web API

External Login without using identity asp.net core 2.0

Not able to get user group claims when using Azure AD as external login alongside Identity Core(ASP.NET Core 2.1)

How to check privileges in JWT using Claims in ASP.NET Core?

client specific claims identity server4 using asp.net core identity

Dynamic claims asp.net core identity no DB persistence

ASP .NET CORE 2.2 JWT & Claims identity Authentication for Website

Not claims comes from cookie in ASP.NET CORE AUTHENTICATION

ASP .Net Core, Store JWT in Cookie

Adding and accessing claims in asp net core 3.0 using built in Identity server

Invalid state cookie. An error was encountered while handling the remote login. ASP.NET Core MVC external social login

ASP.NET Identity Cookie across subdomains on .Net and Core

Adding Redirection immediately after Login in ASP.Net Core 2.1 using Identity Core

Using ASP.NET Identity in an ASP.NET Core MVC application without Entity Framework and Migrations

Cookie Middleware without Identity ASP.NET Core v2

ASP.NET Core. How can i create an auth cookie without an identity user account?

How to implement social login (with Google etc.) with an SPA and ASP.NET Core using OpenIdDict?

Using Asp.Net Core Identity in MVC, Authorize attribute is rebouncing to login page after succesfull login

how to get claims of another user using ASP.NET Core

Using claims or just roles in ASP.NET Core MVC

Refresh user cookie ticket in ASP.Net Core Identity

Multiple & SubDomain's cookie in asp.net Core Identity

ASP.NET Core MVC: setting expiration of identity cookie

JS get cookie ASP.NET Core Identity

Save tokens in Cookie with ASP.NET Core Identity

asp.net core identity cookie replay attack

How to check if user is logged in to ASP.NET Core web application when using ASP.NET Core Web API to house identity

Asp.net core identity change username/email

Confirming more than one email in Asp.net Identity core

TOP Ranking

HotTag

Archive