Search code examples
c#asp.netasp.net-mvcasp.net-mvc-5asp.net-identity-2

Why ASP.NET Identity returns 401 instead redirect to login page?


I am trying to add ASP NET Identity to existing mvc5-project with code-first. I have studied new project, which generated VS, and I readed many articles on the ASP.NET Identity. For the most part, I copied the code from the template to my project. I just replaced DBContext on IdentityDbContext and few changes changes. Tables were generated by EF Migration and filled by Seed method through UserManager and RoleManager, so, I think, some part of code works as expected.

But, when I added [Authorize] to Controller (not WebApi, just Controller), and tried to get a page from the controller then I faced a problem - server returns 401.0 error, although the options set to LoginPath = new PathString("/Account/Login").

Here is my code Startup.Auth.cs

namespace App
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(CwDb.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
                        SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
                            validateInterval: TimeSpan.FromMinutes(30),
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
        }
    }
}

Here is my Startup.cs

[assembly: OwinStartupAttribute(typeof(CarWashApplication.Startup))]
namespace App
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            ConfigureAuth(app);
        }
    }
}

I need only simple auth with login/pass and cookies, I don't need auth by social network and etc.

Where am I wrong? How get redirection like in vs-generated template?


Solution

  • I found a solution. I just added Microsoft.Owin.Host.SystemWeb to the project and it worked. Unfortunately, no article that I have seen has any information about the necessity of this library.