[英]Login Dialog Appears When User is Not Authorized
为了在Web应用程序中实现安全性,我创建了一个从AuthorizeAttribute
派生的属性。
public class FunctionalityAttribute : AuthorizeAttribute
{
public string FunctionalityName { get; set; }
protected override bool IsAuthorized(HttpActionContext actionContext)
{
string adGroup = WebConfigurationManager.AppSettings[FunctionalityName];
if (actionContext.RequestContext.Principal.IsInRole(adGroup)) { return true; }
return false; // This causes a login dialog to appear. I don't want that.
}
}
这是在我的Web API方法中的用法:
[Functionality(FunctionalityName = "GetApps")]
public IEnumerable<ApplicationDtoSlim> Get()
{
using (var prestoWcf = new PrestoWcf<IApplicationService>())
{
return prestoWcf.Service.GetAllApplicationsSlim().OrderBy(x => x.Name);
}
}
它确实有效。 但是问题是当我未被授权时会发生什么:
我不希望出现该对话框。 我已经登录。我想让用户知道他们未被授权。 我该如何做才能避免出现登录对话框?
您还需要覆盖HandleUnauthorizedRequest
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
System.Web.Routing.RouteValueDictionary rd = null;
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
//Redirect to Not Authorized
rd = new System.Web.Routing.RouteValueDictionary(new { action = "NotAuthorized", controller = "Error", area = "" });
}
else
{
//Redirect to Login
rd = new System.Web.Routing.RouteValueDictionary(new { action = "Login", controller = "Account", area = "" });
//See if we need to include a ReturnUrl
if (!string.IsNullOrEmpty(filterContext.HttpContext.Request.RawUrl) && filterContext.HttpContext.Request.RawUrl != "/")
rd.Add("ReturnUrl", filterContext.HttpContext.Request.RawUrl);
}
//Set context result
filterContext.Result = new RedirectToRouteResult(rd);
}
在HandleUnauthorizedRequest
,使用HttpStatusCode
Forbidden
,因为Unauthorized
使登录提示显示。 这是整个属性类。
public class FunctionalityAttribute : AuthorizeAttribute
{
public string FunctionalityName { get; set; }
protected override bool IsAuthorized(HttpActionContext actionContext)
{
string adGroup = WebConfigurationManager.AppSettings[FunctionalityName];
if (actionContext.RequestContext.Principal.IsInRole(adGroup)) { return true; }
return false;
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
// Authenticated, but not authorized.
if (actionContext.RequestContext.Principal.Identity.IsAuthenticated)
{
// Use Forbidden because Unauthorized causes a login prompt to display.
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
}
}
这就是我在角度存储库中处理它的方式:
$http.get('/PrestoWeb/api/apps/')
.then(function (result) {
// do success stuff
}, function (response) {
console.log(response);
if (response.status == 403) {
$rootScope.setUserMessage("Unauthorized");
callbackFunction(null);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.