我需要根据用户ID控制对控制器的编辑方法的访问,即只有该用户才能访问创建该特定数据的编辑方法。用户ID存储在表EmpProfile UserID列中,并且想要将当前登录的用户与存储的UserID进行比较,并在此基础上允许访问。我的自定义授权属性代码是:
public class AuthorizeAuthorAttribute : AuthorizeAttribute
{
RecruitDB mydb = new RecruitDB(); // My Entity
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
string CurrentUser = httpContext.User.Identity.GetUserId().ToString(); // Current User ID(Converted to string)
var userName = from m in mydb.EmpProfiles //Calling method to get UserID from EmpProfile.UserID Column
where m.UserID == CurrentUser
select m.UserID;
string my = userName.ToString(); //Converting to string
if (CurrentUser.Contains(my)) //Comparing
{
return true;
}
else
{
return false;
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
控制器代码:
[AuthorizeAuthor]
public ActionResult Edit(int? id)
{
}
但是通过应用授权,我总是被定向到登录页面。当用户与作者相同时。
针对您的评论:
通过添加
[Authorize(User="SomeUser")]
到我的操作中,仅允许特定的硬编码用户输入。但是用户如何创建数据只能被授权。为此,当前用户ID和数据创建者用户ID应该匹配。非常类似于“站点用户仪表板”,只有创建它的用户才能访问。MVC是否提供此类授权?请指教
您正确地注意到该Authorize
属性(如.NET中的所有属性)只能具有const参数。
为了灵活起见,在这种情况下不能使用属性,必须实现自己的授权逻辑并通过控制器操作执行调用,如下所示:
public ActionResult Edit(Int32? id) {
// Repeat the below logic for each action you want access-control in, ensure it is also in your POST handlers too.
if( !this.IsAuthorized() ) return this.Http401();
}
protected boolean IsAuthorized() {
if( this.Request.User.Identity.Name == "someoneIDontLike" ) return false;
return true;
}
protected ActionResult Http401(String message) {
this.Response.StatusCode = 401;
// This requires you to create your own custom HTTP 401 "Unauthorized" view file and viewmodel
return this.View( new Http401ViewModel(message) );
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句