0

私はユーザーを作成し、役割を割り当てました。 AspNetUsersテーブルとAspNetUserRolesテーブルの両方が更新されます。理想的には、ユーザーは認証され、自動化されます。しかし、ナビゲートしようとするとUnAuthorizedアクセスエラーが発生します。ログアウトしてもう一度ログインしようとすると、完璧に動作します。この問題は、ユーザー作成時にのみ発生します。私はアクセスしているコントローラに[CustomAuthorize(Roles = "User")]を追加しました。[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"); 
       } 

私はホームコントローラにリダイレクトすると、コントロールがHandleUnauthorizedRequest機能に入ってきます。

マイカスタムのauthorizeクラスは以下の通りです:次のように

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

あなたの代わりにこれを使用します。あなたは、あなたのユーザーが無許可になっていたので、ロールチェックをスキップしていました。

public class CustomAuthorize : AuthorizeAttribute 
    { 
     protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
     { 
      if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
      { 
       filterContext.Result = new HttpUnauthorizedResult(); 
      } 
      else 
      { 
       var rolesArray = Roles.Split(','); 
       var isAllowed = rolesArray.Any(role => filterContext.HttpContext.User.IsInRole(role)); 
       if (!isAllowed) 
        filterContext.Result = new RedirectToRouteResult(new 
         RouteValueDictionary(new { controller = "AccessDenied" })); 
      } 
     } 
    } 
+0

私はisAllowedをfalseにしているので、まだAccessDeniedを取得しています。私はUser.IsInRole( 'User')をチェックしました、それは偽です。あなたはなぜそれがfalseに設定されているか考えていますか?私はrolesArrayで 'User'を見ることができます。 – KFC

+0

溶液の塊を得た。私はログイン後に役割を設定していました。私はステートメントを入れ替えただけです。 UserManager.AddToRoleAsync(user.Id、 "User")を待ちます。 SignInManager.SignInAsync(user、isPersistent:false、rememberBrowser:false);を待機します。 – KFC

+0

@KFC完璧です。あなたのCustomAuthorizeに問題があったので、私はあなたの登録コードを最初に見ませんでした。 –

関連する問題