码迷,mamicode.com
首页 > Web开发 > 详细

MVC-登录并设置角色

时间:2015-05-26 15:52:12      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

1、新建一个类,设置角色:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Mvc;
using System.Web.Security;

namespace Soft.Dataprovider
{
    public enum ESoftRoles
    {
        Admin,
        User
    }

    public class ESoftRolesHelper
    {
        public static string GetValue(ESoftRoles role)
        {
            string roleType = "User";
            if (role == ESoftRoles.Admin)
            {
                roleType = "Admin";
            }
            else
            {
                roleType = "User";
            }
            return roleType;
        }
    }

    public class ESoftRolesAttribute : AuthorizeAttribute
    {
        //重载此方法,模拟自定义的角色授权机制     
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //获得当前的验证cookie   
            HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; 
            if (authCookie == null || authCookie.Value == "")
            {
                return false;
            }
            FormsAuthenticationTicket authTicket;
            try
            {
                //对当前的cookie进行解密   
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            }
            catch
            {
                return false;
            }
            if (authTicket != null)
            {
                //和存入时的分隔符有关系,此处存入时的分隔符为逗号   
                var userRoles = authTicket.UserData.Split(new[] { , }).ToList();
                var roles = Roles.Split(new[] { , }).ToList();
                return roles.Any(x => userRoles.Contains(x));
            }
            return false;
        }

  
        //没权限时跳到页面
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
              filterContext.Result = new RedirectResult("/Account/MyAuth"); ;
        }
    }  
}

2、登录代码:

                            string roles = ESoftRolesHelper.GetValue(ESoftRoles.Admin);
                            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(20), false, roles);//写入用户角色
                            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);//对authTicket进行加密
                            SessionCookieHelper.SetCookie(this.AdminCookieName, encryptedTicket, DateTime.Now.AddHours(2));
                            info.CountOfLogin += 1;
                            info.LastLoginDate = DateTime.Now;
                            entity.Configuration.ValidateOnSaveEnabled = false;
                            entity.SaveChanges();
                            entity.Configuration.ValidateOnSaveEnabled = true;

3、退出代码:

            FormsAuthentication.SignOut();
            SessionCookieHelper.ClearCookie(this.AdminCookieName);

4、Action或Controller添加:
    [ESoftRolesAttribute(Roles = "Admin")]

     如果允许匿名访问,添加:

       [AllowAnonymous]

 

MVC-登录并设置角色

标签:

原文地址:http://www.cnblogs.com/yaosuc/p/4530681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!