2015年12月9日 星期三

ASP.NET 5/MVC 6 自訂使用Claim驗証

在ASP.NET 5 如果不想用落落長又複雜的 Identity 有另一個簡單的方式



在Startup.cs
        public void ConfigureServices(IServiceCollection services)
        {
            var defaultPolicy = new AuthorizationPolicyBuilder()
               .RequireAuthenticatedUser()
               .Build();
            // Add framework services.
            services.AddMvc(setup =>
            {
                setup.Filters.Add(new AuthorizeFilter(defaultPolicy));
            });


            services.AddAuthorization(options =>
            {
                // inline policies
                options.AddPolicy("AdminGroup", policy =>
                {
                    policy.RequireClaim("role", "Admin");
                });
                options.AddPolicy("MemberGroup", policy =>
                {
                    policy.RequireClaim("role", "Member");
                    policy.RequireClaim("role", "Admin");
                });           
            });
        }


       public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
                             ILoggerFactory loggerFactory)
        {
            //.....其它略
            //使用Cookie驗証
            app.UseCookieAuthentication(options =>
            {
                //options.AuthenticationType = "Cookies";                
                options.AccessDeniedPath = "/Common/forbidden"; //權限不夠導向的網址

                options.CookieHttpOnly = true;
                options.LogoutPath = new PathString("/Common/LoginOut"); //登出網址
                options.LoginPath = new PathString("/Common/Login");   //登入網址
                options.AutomaticAuthenticate = true;
                options.AutomaticChallenge = true;
            });
           
       }

在LoginController
    
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {            
            var claims = new List<Claim>
                    {
                        new Claim("userId", model.UserId),
                        new Claim("role", "Member") //設定使用者的Role,這裡偷懶都用Member
                    };

            var id = new ClaimsIdentity(claims, "local", "userId", "role");
            await HttpContext.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(id));
            if (String.IsNullOrEmpty(returnUrl))
            {
                //return Redirect("Msg?msg=isok");
                return RedirectToAction(nameof(CommonController.Msg),new { msg = "登入成功" });
            }
            else { return Redirect(returnUrl); }
        }



        
        public async Task<IActionResult> Logoff()
        {
            await HttpContext.Authentication.SignOutAsync("Cookies");
            return RedirectToAction(nameof(HomeController.Index), "Home");
        }       

注意要標 [AllowAnonymous],不然預設網頁都是要登入會員才行
如果要限定管理群組AdminGroup才可以進入的話,可以這樣設
   
    //整個目錄都設定權限
    [Authorize("AdminGroup")]
    public class AdminController : Controller
    {
        // GET: //
        public IActionResult Index()
        {
            return View();
        }
    } 

   
    //單一個Controller設定權限
    public class AdminController : Controller
    {
        // GET: //
        [Authorize("AdminGroup")]
        public IActionResult Index()
        {
            return View();
        }
    } 

沒有留言:

張貼留言