使用[CustomAuthorize(Roles =“User”)创建用户和分配角色后未经授权的访问]

时间:2017-05-11 22:58:03

标签: c# asp.net-mvc entity-framework authentication authorization

我创建了用户并分配了角色。表AspNetUsers和AspNetUserRoles都会更新。理想情况下,用户在身份验证和authrorized。但是当我尝试导航时,它会抛出UnAuthorized访问错误。如果我退出并尝试再次登录,它将完美无缺。此问题仅在创建用户时出现。我已将[CustomAuthorize(Roles = "User")]添加到我正在访问的控制器中。

示例代码是:

var user = new ApplicationUser { UserName = model.EmailID, Email = model.EmailID, PhoneNumber = model.PhoneNumber, FirstName = model.FirstName, LastName = model.LastName,Organisation = model.Organisation, isAdmin = model.isAdmin };
                var result1 = await UserManager.CreateAsync(user, model.Password);
                if (result1.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    await UserManager.AddToRoleAsync(user.Id, "User");
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    return RedirectToAction("Index", "Home");
                }

当我重定向到Home控制器时,控件进入HandleUnauthorizedRequest功能。

我的自定义授权类如下:

public class CustomAuthorize : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(new
                    RouteValueDictionary(new { controller = "AccessDenied" }));
            }
        }


    }

控制器代码如下:

[Authorize]
    public class HomeController : Controller
    {
        MusicJournalContext db = new MusicJournalContext();
        private static RoleManager<IdentityRole> RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
        public ActionResult Index()
        {
            if (User.IsInRole("Admin"))
            {
                return RedirectToAction("Index", "Articles", new { status = "InProcess" });
            } else if(User.IsInRole("User")){
                return RedirectToAction("Index", "EndUser");
            }

            return View();
        }

我找到了1个解决方案,但它没有用。我已添加await UserManager.UpdateSecurityStampAsync(user.Id);帮助表示感谢。

0 个答案:

没有答案