[C#]登录对话框出现时用户是不授权

发布时间: 2017/2/23 20:09:15
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

在尝试在我的 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);
    }
}

它确实有效。但问题是,当我没有权限时,会发生什么︰

enter image description here

我不想那对话框来。我已经签署。我想要让用户知道他们不授权。我如何做所以该登录对话框不能过来?

解决方法 1:

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);
            }
        });
赞助商