我创建了一个简单的 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;
}
}
In the AccountController
我已经按照以下方式对操作进行了编码,这又非常简单,但它应该可以工作。
[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
课堂工作,但我的这个简单实现不起作用