Authorize權限的擴充功能

在Controller上如果有權限跟角色的設定需求的話可以使用此擴充功能

BaseController.cs

public LoginSuccess()
{
    // 登入授權 - 方便確認是否登入
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        version: 1,
        name: userProfile.UserId,
        issueDate: DateTime.Now,                            // 現在時間
        expiration: DateTime.Now.AddMinutes(1440),          // 有效時間
        isPersistent: false,                                // 記住我 true or false
        userData: userProfile.Role.ToString(),
        cookiePath: FormsAuthentication.FormsCookiePath);
                
    var encryptedTicket = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    Response.Cookies.Add(cookie);
}

/// <summary>
/// Authorize權限的擴充, 方便設定多個角色
/// </summary>
public class AuthorizeRolesAttribute : AuthorizeAttribute
{
    public AuthorizeRolesAttribute(params string[] roles) : base()
    {
        Roles = string.Join(",", roles);
    }
}

public enum RoleType
{
    Checker = 0,
    Maker = 1,
    Unknown = 9
}

/// <summary>
/// 各功能的權限控制, 名稱與RoleType一致
/// </summary>
public class Role
{
    public const string Checker = nameof(RoleType.Checker);
    public const string Maker = nameof(RoleType.Maker);
    public const string Unknown = nameof(RoleType.Unknown);
}

HomeController.cs

[AuthorizeRoles(Role.Maker, Role.Checker)]
public ActionResult Index()
{
    // TODO
}

Global.asax.cs

void Application_AuthenticateRequest(object sender, EventArgs e)
{
    if (Request.IsAuthenticated)
    {
        // 先取得該使用者的 FormsIdentity
        FormsIdentity id = (FormsIdentity)User.Identity;
        // 再取出使用者的 FormsAuthenticationTicket
        FormsAuthenticationTicket ticket = id.Ticket;
        // 將儲存在 FormsAuthenticationTicket 中的角色定義取出,並轉成字串陣列
        string[] roles = ticket.UserData.Split(new char[] { ',' });
        // 指派角色到目前這個 HttpContext 的 User 物件去
        Context.User = new GenericPrincipal(Context.User.Identity, roles);
    }
}