用户未经授权时出现登录对话框

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 会导致显示登录提示。这是整个属性 class.

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);
        }
    }
}

这就是我在 angular 存储库中处理它的方式:

    $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);
            }
        });