Asp.Net Core google-signin oauth 限制访问并获取 g-suite 角色

Posted

技术标签:

【中文标题】Asp.Net Core google-signin oauth 限制访问并获取 g-suite 角色【英文标题】:Asp.Net Core google-signin oauth restrict access and get g-suite roles 【发布时间】:2017-08-17 06:30:44 【问题描述】:

我正在制作一个带有 Web 视图的 .NET Core 应用程序,我需要在其中验证使用 Google+ 登录的用户。 我遵循了这个 (https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins) 教程,现在可以使用我的谷歌帐户登录。到目前为止一切顺利。

如何将我的应用程序的访问权限限制为仅限特定域中的用户?

如何检索 g-suite 中定义的经过身份验证的用户角色?

我尝试在 Startup.cs 中为身份验证选项添加范围,但我不知道如何提取/接收其中包含的信息。

        app.UseGoogleAuthentication(new GoogleOptions()
           Scope =
               "https://www.googleapis.com/auth/admin.directory.domain.readonly",
                "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly"
            , 
            ClientId = Configuration["Authentication:Google:ClientId"],
            ClientSecret = Configuration["Authentication:Google:ClientSecret"]
        );

【问题讨论】:

【参考方案1】:

好吧,最后我自己解决了...留下这个答案以防其他人有这个问题。

来自 AccountController.ExternalLoginCallback() 的代码 sn-p

    var info = await _signInManager.GetExternalLoginInfoAsync();
    foreach (var claim in info.Principal.Claims)
    
        System.Diagnostics.Debug.WriteLine("Type: " + claim.Type + " Value: " + claim.Value);
    

这将打印声明列表,其中定义了角色和域 (hd)。

或者,您可以在中间件 (Startup.configure()) 中检索声明:

    app.UseGoogleAuthentication(new GoogleOptions()
    
        Scope =
           "https://www.googleapis.com/auth/admin.directory.domain.readonly",
            "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly"
        ,
        ClientId = Configuration["Authentication:Google:ClientId"],
        ClientSecret = Configuration["Authentication:Google:ClientSecret"],
        Events = new OAuthEvents()
        
            OnTicketReceived = e =>
            
                var claims = e.Principal.Claims;
                // Do something with claims
                return Task.CompletedTask;
            
        
    );

【讨论】:

以上是关于Asp.Net Core google-signin oauth 限制访问并获取 g-suite 角色的主要内容,如果未能解决你的问题,请参考以下文章

Asp.NET Core进阶 第四篇 Asp.Net Core Blazor框架

.NET Core 1.0ASP.NET Core 1.0和EF Core 1.0简介

asp.net core 注入后仍然报错?

深入研究 Mini ASP.NET Core(迷你 ASP.NET Core),看看 ASP.NET Core 内部到底是如何运行的

.Net Core 学习 - ASP.NET Core 概念学习

ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 14. ASP.NET Core Identity 入门