【问题标题】:Google authentication in ASP.NET Core without ASP.NET Identity没有 ASP.NET 身份的 ASP.NET Core 中的 Google 身份验证
【发布时间】:2018-07-07 13:41:09
【问题描述】:

在没有 ASP.NET Identity 的情况下,是否可以通过 Google 在 ASP.Net 核心中实现身份验证? 我已经实现了基于 cookie 的身份验证,如下所示:

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

而且我需要将 Google 身份验证添加到项目中。

【问题讨论】:

    标签: c# authentication asp.net-core asp.net-identity google-authentication


    【解决方案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 类中。

        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();
        }
    }
    

    我还放置了几个简单的视图,以便用户在注销后可以单击链接返回主页,或再次登录或以其他用户身份登录,等等。

    这似乎对我有用。

    【讨论】:

      【解决方案2】:

      当然可以。以下是您可以解决此问题的一种方法的摘要。

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

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

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2018-06-15
        • 2018-01-24
        • 1970-01-01
        • 1970-01-01
        • 2015-10-09
        • 2017-12-06
        • 2017-03-30
        • 2018-06-25
        • 2016-05-19
        相关资源
        最近更新 更多