[ASP.NET Core身份验证,仅适用于特定帐户的Google

问题描述 投票:1回答:1

在我的ASP.NET Core 3应用中,我想实现与Google的登录,并且仅允许特定用户的身份验证。

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

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/social-without-identity?view=aspnetcore-3.0https://docs.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
                };
            });
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;
        }
authentication asp.net-core .net-core authorization
1个回答
0
投票

您可以创建一个策略来检查用户名声明是否在允许的用户名列表中,并根据验证结果返回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;

            return falase;
        });
    });
}); 

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

© www.soinside.com 2019 - 2024. All rights reserved.