我正在尝试为我网站中的某些页面添加角色授权。我只有两个角色,'admin'和'rep',用户一次只能分配到1个角色。
问题是,我的授权不断变得不一致。以具有admin角色的用户身份登录时,我可以访问某些页面,但不能访问其他页面。
-
使用我的管理员帐户,我可以毫无问题地访问此页面:
帐户管理
// GET: /Manage/Index
[Authorize(Roles = "admin")]
public async Task<ActionResult> Index(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetUsernameSuccess ? "Your username has been set."
: message == ManageMessageId.SetUsernameUnique ? "That username is taken."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var userId = User.Identity.GetUserId();
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var model = new ManageViewModel();
model.UsernameModel = new SetUsernameViewModel();
model.PasswordModel = new ChangePasswordViewModel();
model.UsernameModel.Username = user.UserName;
return View(model);
}
这个假设我没有履行角色并将我重定向到登录页面:
角色管理
// GET: ManageRoles
[Authorize(Roles = "admin")]
public ActionResult ManageRoles()
{
IList<RoleModel> accountsList = new List<RoleModel>();
IdentityDbContext context = new IdentityDbContext("MavcoConnectionString");
var allUsers = context.Users;
foreach (var u in allUsers)
{
ApplicationUser user = UserManager.FindByEmail(u.Email);
accountsList.Add(new RoleModel(user, UserManager.GetRoles(user.Id)[0]));
}
return View(accountsList);
}
角色和帐户管理都位于ManageController中。
-
我的下载页面存在真正问题的另一个位置。索引在这里:
// GET: Downloads
public ActionResult Index()
{
var downloadsList = new List<DownloadModel>();
if (db.Downloads.Any())
{
foreach (Download ddb in db.Downloads)
{
DownloadModel d = new DownloadModel(ddb);
downloadsList.Add(d);
}
}
string myId = User.Identity.GetUserId();
ViewData["role"] = UserManager.GetRoles(myId)[0];
return View(downloadsList);
}
相关的HTML在这里:
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
@if ((string)ViewData["role"] == "admin")
{
@Html.ActionLink("Add New File", "CreateDownload")
}
当我使用我的管理员帐户登录时,会显示“添加新文件”链接。这意味着我被认为是管理员。
但是......如果我尝试关注该链接,我会被拒绝。
DownloadsController
// GET: CreateDownload
[Authorize(Roles = "admin")]
public ActionResult CreateDownload()
{
return View();
}