为什么我的microsoft.owin.security.authenticationmanager登录方法不起作用? [英] Why is my microsoft.owin.security.authenticationmanager Signin method not working?
问题描述
我正在处理ASP MVC登录表单.
I working on an ASP MVC login form.
我有非常简单的代码. Startup
类和尝试设置cookie的操作.下面是我的代码:
I have pretty simple codes. A Startup
class and an action trying to set the cookie. Below is my code :
启动
位于App_Start中(在<appSetting>
和key="owin:AppStartup"
中也有对其的引用)
Startup
which is located in App_Start (there is also a reference to it in <appSetting>
with key="owin:AppStartup"
)
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/auth/login"),
});
}
}
用于验证用户身份的操作方法是:
[HttpPost]
public ActionResult Login(user model)
{
if(ModelState.IsValid)
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Email, "admin@admin.com"),
new Claim(ClaimTypes.Name, "tom"),
new Claim(ClaimTypes.Role, "admin")
});
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignIn(identity);
return RedirectToAction("Index", "Home");
}
return View(model);
}
但是,当return RedirectToAction("Index", "Home");
时,我的_Layout.cshtml
中的@User.Authenticated
是假的,这并没有得到身份验证,而且调试器显示IsAuthenticated
属性是假的(在控制器Login
动作和_Layout.cshtml
.
But this does not get the identity authenticated as @User.Authenticated
is false in my _Layout.cshtml
when return RedirectToAction("Index", "Home");
and also the debbuger shows that IsAuthenticated
property is false (in the controller Login
action and in the _Layout.cshtml
.
我已经使用Windows管理工具检查了IIS是否启用了匿名身份验证,并且还检查了应用程序启动时是否设置了启动...
I have checked that IIS is enabled for Anonymous authentication using my windows administrative tools and also I have checked that Startup is set when the application starts...
我似乎authManager.SignIn(identity)
没有做好工作.
我们如何解决这个问题?
How can we solve this ?
ps:我什至没有看到浏览器弹出窗口询问我是否要保存密码(即使用户仍未通过身份验证,我在测试过程中也只弹出一次)
ps : I do not even see the browser popup asking if I want to save the password (I popped only once during my tests even though the user was still not authenticated)
推荐答案
SignIn保留用户的将来请求(通过cookie),它不会更改当前请求.您可以根据需要直接为当前请求设置HttpContext.User.
SignIn persists the user for future requests (via cookies), it does not alter the current request. You can directly set HttpContext.User for the current request if you want.
我还记得您需要将ClaimsIdentity AuthenticationType设置为CookieAuthenticationDefaults.AuthenticationType(或用于标识中间件的任何身份验证类型).否则,cookie身份验证中间件将无法激活.
I also recall that you need to set the ClaimsIdentity AuthenticationType to CookieAuthenticationDefaults.AuthenticationType (or whatever auth type you're using to identify your middleware). Otherwise the cookie auth middleware won't activate.
这篇关于为什么我的microsoft.owin.security.authenticationmanager登录方法不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!