登录并向Action添加Authorize属性后,无法访问Controller操作

时间:2016-10-28 14:28:35

标签: c# asp.net asp.net-mvc login asp.net-mvc-5

我设置了一个简单的登录页面,用于在用户点击登录按钮时登录。用户在登录时获得分配的角色。为了测试它是否成功,我已经完成了以下登录代码:

  [HttpPost]
        [ActionName("Login")]
        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                string userName = model.Username;
                string[] userRoles = new string[5];
                userRoles[0] = "Administrator";

                ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userName));

              //  userRoles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role)));
                identity.AddClaim(new Claim(ClaimTypes.Role, userRoles[0]));
                identity.AddClaim(new Claim(ClaimTypes.Name, userName));

                AuthenticationManager.SignIn(identity);

                return RedirectToAction("Success");
            }
            else
            {
                return View("Login",model);
            }
        }

我已经为我的MVC操作添加了一个Authorize属性,只是为了看看用户是否真的能够在登录后访问它...这就是我如何做到的:

[Authorize(Roles="Administrator")]
        public ActionResult Register()
        {
            var model = new UserRegistrationViewModel();
            var countries = Connection.ctx.Countries.OrderBy(x => x.CountryName).ToList();
            model.Countries = new SelectList(countries, "CountryId", "CountryName");
            return View(model);
        }

但出于某种原因,我尝试访问如下:

mywebsite.com/user/register

它告诉我:

HTTP Error 401.0 - Unauthorized
You do not have permission to view this directory or page.

它可能是什么?

编辑:

以下是用户登录后声明和身份的快照:

enter image description here

第二个:

enter image description here

2 个答案:

答案 0 :(得分:1)

我说你得到的是401,因为你的用户没有“管理员”角色。在后续请求中检查您的用户(身份),我不确定角色是否存在于cookie中 - 您可能需要找到一种方法来自己保留角色。

答案 1 :(得分:1)

你能确保你有Cookie中间件吗?例如,

Startup.cs

[assembly: OwinStartup(typeof(YourApplicationName.Startup))]
namespace YourApplicationName
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
}

Using Cookie Middleware without ASP.NET Core Identity