我在asp.net web api上使用自定义授权。我已经按照以下链接 http://www.codeproject.com/Tips/376810/ASP-NET-WEB-API-Custom-Authorize-and-Exception-Han 我在我的控制器中使用属性名称,如此
[mycustomattribute]
public class userController:apicontroller {
}
但是,尽管授权身份验证状态,它仍然会显示401未经授权的例外情况。我已经完全按照它在链接中创建自定义授权属性。
我的自定义授权类
public class tokenAuthorize : AuthorizeAttribute
{
DBEntity _objScrumDBEntities = new DBEntity ();
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
if (actionContext.Request.Headers.GetValues("authenticationToken") != null)
{
// get value from header
string authenticationTokenValue = Convert.ToString(actionContext.Request.Headers.GetValues("authenticationToken").FirstOrDefault());
ObjectParameter m_tokenParam = new ObjectParameter("status", typeof(string));
_objScrumDBEntities.validateToken(authenticationTokenValue, m_tokenParam);
string status = Convert.IsDBNull(m_tokenParam.Value) ? null : (string)m_tokenParam.Value;
if (status == "false")
{
HttpContext.Current.Response.AddHeader("authenticationToken", authenticationTokenValue);
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
// actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
return;
}
else
{
HttpContext.Current.Response.AddHeader("authenticationToken", authenticationTokenValue);
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "Authorized");
return;
}
//return;
}
//actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.ExpectationFailed);
//else
// actionContext.Response.ReasonPhrase = "Please provide valid inputs";
}
}
和我的控制器
[tokenAuthorize]
public class myController : ApiController
{
public IEnumerable<organization> Get()
{
return _objOrgRepository.GetAll();
}
答案 0 :(得分:0)
当您拥有自定义AuthorizeAttribute和自定义RoleProvider时,似乎没有自动连接System.Web.Security.Roles.GetRolesForUser(Username)。
因此,在您的自定义AuthorizeAttribute中,您需要从数据源中检索角色列表,然后将它们与作为参数传递给AuthorizeAttribute的角色进行比较。请尝试以下代码
public class myController : ApiController
{
[RequestKeyAuthorizeAttribute(Roles="Admin,Bob,Administrator,Clue")]
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, "RequestKeyAuthorizeTestController");
}