Asp.Net Core google-signin oauth restrict access and get g-suite roles

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-08 16:33:28

问题


I am making a .NET Core application with web views where I need to authenticate users with Google+ sign-in. I followed this ( https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins ) tutorial, and can now sign in user my google account. So far so good.

How do I restrict access to my application to only users within a certain domain?

How do I retrieve the authenticated users roles defined in g-suite?

I have tried to add scopes to the authentication options in Startup.cs, but I dont know how to extract/recieve the information contained in them.

        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:


Well, solved it my self in the end... Leaving this answer in case anyone else has this problem.

Code snippet from AccountController.ExternalLoginCallback()

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

This will print the list of claims, where the roles and domain (hd) are defined.

Or, you can retrieve the claims in the middleware (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;
            }
        }
    });


来源:https://stackoverflow.com/questions/42997458/asp-net-core-google-signin-oauth-restrict-access-and-get-g-suite-roles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!