首页 文章

没有ASP.NET身份的ASP.NET Core中的Google身份验证

提问于
浏览
2

在没有ASP.NET身份的ASP.Net核心中通过Google实现身份验证的方法是什么?我已经实现了基于这样的cookie的身份验证:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x

我需要将Google身份验证添加到项目中 .

2 回答

  • -1

    当然是 . 以下是您可以采用的一种方式的总结 .

    您可以直接调用OAuth2身份验证服务器API,并在.NET中编写自定义属性/处理程序/过滤器以与该功能集成并相应地控制对资源的访问 .

    https://developers.google.com/identity/protocols/OAuth2WebServer

    我相信Google为其显式授权/服务器身份验证流程提供的当前 endpoints 如下:

    您可以在上面的链接中发现有关特定HTTP请求和响应的更多详细信息,但这是OAuth2对于Web服务器的一般要点,据我所知:)

    回到核心应用程序,然后您可以编写自定义处理程序/过滤器/属性代码来处理身份验证和重定向 . 可以在此处找到一些.NET核心代码示例:

    https://ignas.me/tech/custom-authentication-asp-net-core-20/

  • 1

    我想知道同样的事情,在网上找不到任何答案,所以我克隆了 Microsoft.AspNetCore.Security (v2.1) repo,看看我是否能弄清楚它是如何工作的 . 我相信这就是你要找的东西 . 将其添加到 Startup.cs 文件中的 ConfigureServices 方法 .

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o => o.LoginPath = new PathString("/login"))
                // You must first create an app with Google and add its ID and Secret to your user-secrets.
                // https://console.developers.google.com/project
                .AddGoogle(o =>
                {
                    o.ClientId = "YOUR_GOOGLE_CLIENT_ID";
                    o.ClientSecret = "YOUR_GOOGLE_CLIENT_SECRET";
                    o.AuthorizationEndpoint += "?prompt=consent"; // Hack so we always get a refresh token, it only comes on the first authorization response
                    o.AccessType = "offline";
                    o.SaveTokens = true;
                    o.Events = new OAuthEvents()
                    {
                        // There are a number of (optional) events you may want to connect into and add your own claims to the user, or handle a remote failure, etc.
                        OnRemoteFailure = HandleOnRemoteFailure,
                        OnCreatingTicket = HandleOnCreatingTicket
                    };
                    o.ClaimActions.MapJsonSubKey("urn:google:image", "image", "url");
                });
    

    如果要拦截某些事件以向用户添加其他声明,或将其存储在数据库中以应用应用级别授权,则可以连接到各种 OAuthEvents . 我将以下方法放在Startup.cs文件的底部,在Startup Class中 .

    private async Task HandleOnCreatingTicket(OAuthCreatingTicketContext context)
        {
            var user = context.Identity;
            // please use better logic than GivenName. Demonstration purposes only.
            if(user.Claims.FirstOrDefault(m=>m.Type==ClaimTypes.GivenName).Value == "MY_FAVORITE_USER")
            {
                user.AddClaim(new Claim(ClaimTypes.Role, "Administrator"));
            }
    
            await Task.CompletedTask;
        }
    
        private async Task HandleOnRemoteFailure(RemoteFailureContext context)
        {
            // add your logic here.
            await Task.CompletedTask;
        }
    

    最后,您需要添加几个控制器操作 . 我把我放在一个AccountController.cs文件中,如下所示:

    public class AccountController : Controller
    {
        [AllowAnonymous]
        [Route("/login")]
        public async Task<IActionResult> Login()
        {
            if (User == null || !User.Identities.Any(identity => identity.IsAuthenticated))
            {
    
                // By default the client will be redirect back to the URL that issued the challenge (/login?authtype=foo),
                // send them to the home page instead (/).
                string returnUrl = HttpContext.Request.Query["ReturnUrl"];
                returnUrl = string.IsNullOrEmpty(returnUrl) ? "/" : returnUrl;
                await HttpContext.ChallengeAsync("Google", new AuthenticationProperties() { RedirectUri = returnUrl });
            }
    
            return View();
        }
    
        [Authorize]
        [Route("/logout")]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties() { RedirectUri="/" });
    
            return View();
        }
    }
    

    我还提出了几个简单的视图,以便一旦注销,用户可以单击链接返回主页,或再次登录或作为其他用户等 .

    这似乎对我有用 .

相关问题