我一直在盯着这个人。 我一直在尝试为WebApi实现自定义授权属性。我已经阅读了多篇关于如何执行此操作的文章,但由于某种原因,授权永远不会执行。
$merchant_key='JBZaLc';
$merchant_salt='GQs7yium';
我可以看到我从正确的AuthorizeAtribute继承而不是mvc。但从未调用过IsAuthorized方法。 控制器动作
public class ActivityAuthorizeWebApiAttribute : System.Web.Http.AuthorizeAttribute
{
private string[] Activities { get; set; }
public string Activity
{
set
{
this.Activities = value.Split(',').Select(x => x.Trim()).ToArray();
}
get { return string.Join(",", this.Activities); }
}
public ActivityAuthorizeWebApiAttribute()
{
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var principalUser = HttpContext.Current.User;
if (principalUser == null || !principalUser.Identity.IsAuthenticated)
{
return false;
}
if (!principalUser.Activities().Any())
{
var activityProvider = (IActivityProvider)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IActivityProvider));
var activities = activityProvider.GetActivitiesByRoleId(principalUser.Identity.GetUserId());
principalUser.SetActivities(activities);
}
return principalUser.HasAnyActivity(this.Activities.ToList());
//check your permissions
}
}
可能是因为与承载令牌认证相结合吗?
编辑: 我甚至尝试过这段代码:
[ActivityAuthorizeWebApi(Activity = "Home")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
作为自定义代码,而不是执行。
答案 0 :(得分:0)
创建自定义属性时需要隐藏以下方法:
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
您需要覆盖并执行安全逻辑的 OnAuthorization 方法。您可以从签名方法中的 actionContext 获取用户。
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (AuthorizeRequest(actionContext))
{
return;
}
HandleUnauthorizedRequest(actionContext);
}
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Code to handle unauthorized request
}
private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Write your code here to perform authorization
return true;
}
}