仅针对特定帐户向 Google 进行 ASP.NET Core 身份验证

Don*_*Box 5 authentication authorization .net-core asp.net-core

在我的 ASP.NET Core 3 应用程序中,我想实现使用 Google 登录,并且只允许对特定用户进行身份验证。

到目前为止我所做的是遵循以下教程:

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

接下来要采取哪些步骤来使用户仅获得特定 Google 帐户的授权?即使用户已成功通过 Google 身份验证,我也只希望特定的 Google 帐户(电子邮件地址)能够访问我的 ASP.NET Core 应用程序。

我尝试的是将委托设置为“OnCreatingEvent”事件,但我不知道如何拒绝授权。

        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
                };
            });
Run Code Online (Sandbox Code Playgroud)
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;
        }
Run Code Online (Sandbox Code Playgroud)

Nan*_* Yu 3

您可以创建一个策略来检查用户的名称声明是否在您允许的用户名列表中,并根据验证结果返回 true/false :

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;
        });
    });
}); 
Run Code Online (Sandbox Code Playgroud)

然后您可以在控制器/操作上应用策略或注册全局过滤器。