Why is my microsoft.owin.security.authenticationmanager Signin method not working?

旧时模样 提交于 2019-12-24 08:52:44

问题


I working on an ASP MVC login form.

I have pretty simple codes. A Startup class and an action trying to set the cookie. Below is my code :

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"),
        });
    }
}

The action method that is suppose to authenticate the user is :

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

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.

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...

I seems that authManager.SignIn(identity) is not doing its job.

How can we solve this ?

debugger screenshot

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)


回答1:


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.

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.



来源:https://stackoverflow.com/questions/43507903/why-is-my-microsoft-owin-security-authenticationmanager-signin-method-not-workin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!