本文介绍了ASP.NET身份OWIN中间件谷歌的OAuth2的AuthenticationManager登入不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的ASP.NET MVC4网站,以测试新的OWIN认证的中间件,我决定开始与谷歌的OAuth2,我曾与奋斗的配置颇有几分,但我设法让谷歌授权用户,我现在的问题是,OWIN未认证用户。

I have created a simple ASP.NET MVC4 web site to test the new OWIN Authentication middleware, I decided to start with Google OAuth2, I have had struggle quite a bit with the configuration but I have managed to have Google to authorize the user, the problem I have right now is that OWIN is not authenticating the user.

我觉得我有在网络配置正确的设置。

I think I have the proper settings in the web config

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

然后我在启动类很简单的配置

Then I have in the Startup class a very simple configuration

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 我有codeD的操作方式如下这又是很简单,但它应该工作。

In the AccountController I have coded the actions the following way which is again very simple but it should work.

[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 不似乎做任何事情,即使谷歌是授予访问要求,当用户被重定向到在我有以下code首页

The main problem I'm having is that the call to the method AuthenticationManager.SignIn doesn't appear to be doing anything, even though Google is granting access to the request, when the user is redirected to the home page in which I have the following code

@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 的值始终为false,任何人有一个想法,以什么我在这里丢失?从我在网上看了这应该是工作。

The value of Request.IsAuthenticated is always false, anybody has an idea as to what am I missing here? From what I read online this should be working.

我在我的浏览器和其他谷歌OAuth的样品,我有依赖于的UserManager 类的工作,但这个简单的实现我不工作启用Cookie

I have cookies enabled in my browser and other Google OAuth samples that I have that rely on the UserManager class work but this simple implementation I have is not working

推荐答案

阅读在网络上寻找答案无数个小时后,我决定调试OWIN源$ C ​​$ C,以找到解决这个问题,而调试会话我来到这个防空火炮宝石在的AuthenticationHandler

After countless hours of reading on the web for answers I decided to debug the OWIN source code to find a solution to this problem, while the debugging session I came accross this gem in the AuthenticationHandler class

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

在我原来的启动类,我在启用cookie中的外部标志用这种方法

In my original Startup class I was enabling the external sign in cookie with this method

app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

此方法使用默认的 CookieAuthenticationOptions 实例有 AuthenticationMode = AuthenticationMode.Passive ,这是$ P $从读取存储在Cookie中的信息pventing类,在每一个新的请求方式OwinContext未加载认证的身份,并导致对 Request.IsAuthenticated

This method was using a default CookieAuthenticationOptions instance that had AuthenticationMode = AuthenticationMode.Passive and this was preventing the class from reading the information stored in the cookie, that way on every new request the OwinContext was not loading the authenticated identity and it resulted on Request.IsAuthenticated

在我意识到这一点,我所做的是改变 app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 这个

After I realized this all I did was to change app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); with this

app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationMode = AuthenticationMode.Passive,
                AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                ExpireTimeSpan = TimeSpan.FromMinutes(30)
            });

和精美的一切工作。

这篇关于ASP.NET身份OWIN中间件谷歌的OAuth2的AuthenticationManager登入不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 01:00