我创建了一个简单的 ASP.NET MVC4 网站来测试新的 OWIN 身份验证中间件,我决定从 Google OAuth2 开始,我在配置方面遇到了很多困难,但我设法让 Google 授权用户,我现在遇到的问题是 OWIN 没有对用户进行身份验证。

我想我在网络配置中有正确的设置

<system.web>
     <authentication mode="None" />
</system.web>
<system.webServer>
     <modules>
        <remove name="FormsAuthenticationModule" />
     </modules>
</system.webServer>

然后我在 Startup 类中有一个非常简单的配置
public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        // Enable the External Sign In Cookie.
        app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ExternalCookie);
        // Enable Google authentication.
        app.UseGoogleAuthentication(GetGoogleOptions());
    }

    private static GoogleOAuth2AuthenticationOptions GetGoogleOptions()
    {
        var reader = new KeyReader();
        var keys = reader.GetKey("google");
        var options = new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = keys.Public,
            ClientSecret = keys.Private
        };
        return options;
    }
}

AccountController 中,我按照以下方式对 Action 进行了编码,这同样非常简单,但它应该可以工作。
[AllowAnonymous, HttpPost, ValidateAntiForgeryToken]
    public ActionResult ExternalLogin(string provider, string returnUrl)
    {
        return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
    }

    [AllowAnonymous, HttpGet]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if (loginInfo == null || !loginInfo.ExternalIdentity.IsAuthenticated)
        {
            return RedirectToAction("Login");
        }

        var identity = new ClaimsIdentity(new[] {
            new Claim(ClaimTypes.Name, loginInfo.DefaultUserName),
            new Claim(ClaimTypes.Email, loginInfo.Email)
        }, DefaultAuthenticationTypes.ExternalCookie);

        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

        AuthenticationManager.SignIn(new AuthenticationProperties
                {
                    IsPersistent = false
                }, identity);

        return RedirectToLocal(returnUrl);
    }

我遇到的主要问题是对 AuthenticationManager.SignIn 方法的调用似乎没有做任何事情,即使 Google 授予对请求的访问权限,但当用户被重定向到我有以下代码的主页时
@using Microsoft.AspNet.Identity
@{
    Layout = "~/Views/Shared/_Main.cshtml";
}
<h2>Welcome</h2>
@{
    if (Request.IsAuthenticated)
    {
        <p>Welcome @User.Identity.GetUserName()</p>
    }
    else
    {
        @Html.ActionLink("Login", "Login", "Account")
    }
}
Request.IsAuthenticated 的值总是错误的,有人知道我在这里遗漏了什么吗?从我在网上阅读的内容来看,这应该有效。

我在浏览器和其他 Google OAuth 示例中启用了 cookie,这些示例依赖于 UserManager 类工作,但我拥有的这个简单实现不起作用

最佳答案

在网上阅读无数小时的答案后,我决定调试 OWIN 源代码以找到解决此问题的方法,而调试 session 我遇到了 AuthenticationHandler 类中的这个 gem

if (BaseOptions.AuthenticationMode == AuthenticationMode.Active)
        {
            AuthenticationTicket ticket = await AuthenticateAsync();
            if (ticket != null && ticket.Identity != null)
            {
                Helper.AddUserIdentity(ticket.Identity);
            }
        }

在我原来的 Startup 类中,我使用此方法启用了外部登录 cookie
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

此方法使用具有 CookieAuthenticationOptions 的默认 AuthenticationMode = AuthenticationMode.Passive 实例,这阻止了类读取存储在 cookie 中的信息,这样在每个新请求中,OwinContext 不会加载经过身份验证的身份,并导致 Request.IsAuthenticated
在我意识到这一点之后,我所做的就是用这个改变 app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationMode = AuthenticationMode.Passive,
                AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                ExpireTimeSpan = TimeSpan.FromMinutes(30)
            });

一切都很顺利

关于c# - ASP.NET 身份 OWIN 中间件 Google OAuth2 AuthenticationManager 登录不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25573345/

10-13 03:53