授权为Roles =" Admin"在登录期间

时间:2017-11-30 06:09:54

标签: asp.net-mvc

首先,我是MVC用户身份验证系统的新手。代码bellow适用于验证普通用户,但我想根据基于MVC角色的系统记录所有用户。因此管理员用户只能看到管理员控制器和普通用户看不到管理员控制器。我已经在我的管理员控制器上添加了#34; [授权(角色="管理员")]"我也在登录控制器内的登录过滤器中正确地重定向到特定的控制器。现在我的问题是:我如何告诉MVC" [授权(角色="管理员")]"只访问谁有管理员角色?我的意思是如何从我的登录控制器下划分用户作为管理员?如有问题可以提出任何问题

管理员控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Blexz.Controllers
{
    [Authorize(Roles = "Admin")]
    public class AdministratorController : Controller
    {
        // GET: Administrator
        public ActionResult Index()
        {
            return View();
        }
    }
}

登录控制器:

//Login post
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(UserLogin login, string ReturnUrl="")
        {
            string Message = "";
            using (BlexzWebDbEntities db = new BlexzWebDbEntities())
            {
                var v = db.Users.Where(x => x.Email == login.Email && x.IsEmailVerified == true).FirstOrDefault();
                int RoleId = db.Users.Where(x => x.Email == login.Email).Select(x => x.RoleId).FirstOrDefault();
                string RoleTypeName = db.Roles.Where(x => x.RoleId == RoleId).Select(x => x.RoleType).FirstOrDefault();
                if (v != null)
                {
                    if (string.Compare(Crypto.Hash(login.Password), v.PasswordHash) == 0)
                    {
                        int timeOut = login.RememberMe ? 43800 : 100; // 43800 == 1 month
                        var ticket = new FormsAuthenticationTicket(login.Email, login.RememberMe, timeOut);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var cookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires = DateTime.Now.AddMinutes(timeOut);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);


                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return Redirect(ReturnUrl);
                        }
                        else if (RoleTypeName == "Admin")
                        {
                            return RedirectToAction("Index", "Administrator");
                        }
                        else
                        {
                            return RedirectToAction("User", "Home");
                        }


                    }
                    else
                    {
                        Message = "Invalid Credential Provided";
                    }
                }
                else
                {
                    Message = "Invalid Credential Provided";
                }
            }
            ViewBag.Message = Message;
            return View();
        }

1 个答案:

答案 0 :(得分:1)

从RoleTypeName选择中删除FirstOrDefault并将其更改为

string[] RoleTypeName = db.Roles.Where(x => x.RoleId == RoleId).Select(x => x.RoleType);

并将检查更改为

if (Url.IsLocalUrl(ReturnUrl))
{
  return Redirect(ReturnUrl);
}
else if (RoleTypeName.Contains("Admin"))
{
    return RedirectToAction("Index", "Administrator");
}
else
{
    return RedirectToAction("User", "Home");
}

更改您的机票,如下所示

var ticket = new FormsAuthenticationTicket(
        version: 1,
        name: UserName,
        issueDate: DateTime.Now,
        expiration: DateTime.Now.AddSeconds(httpContext.Session.Timeout),
        isPersistent: false,
        userData: String.Join(",", RoleTypeName));

然后在global.asax中你会做这样的事情:

public override void Init()
{
    base.AuthenticateRequest += OnAuthenticateRequest;
}

private void OnAuthenticateRequest(object sender, EventArgs eventArgs)
{
    if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
        var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        var decodedTicket = FormsAuthentication.Decrypt(cookie.Value);
        var roles = decodedTicket.UserData.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);

        var principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
    HttpContext.Current.User = principal;
}

}