gpt4 book ai didi

c# - 在 MVC 4 中使用自定义授权

转载 作者:可可西里 更新时间:2023-11-01 08:43:40 24 4
gpt4 key购买 nike

我目前正在使用 MVC 4 Web API 项目类型开发 Web API。我目前正处于需要为 API 添加一些安全性的阶段。我知道 Authorize 属性,但是,客户更喜欢不同的方法。为此,我尝试覆盖我自己的类中的 Authorize 属性,作为一个基本的开始,我只是让 AuthorizeCore 始终返回 false,这应该意味着未经过身份验证。如果我随后将其添加到 Controller 中的一个 Action 中,该 Action 总是会完成并且我总是会检索数据。我认为原因可能是由于未在 web.config 文件中注册自定义属性,但是,我不确定在不使用表单例份验证时如何解决这个问题。

我用来测试的代码是一个全新的 MVC 4 Web API 项目,其自定义属性如下所示。

public class Auth : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return false;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("http://www.google.com");
}
}

然后我将属性添加到默认 ValuesController 的 Get 方法中

[Auth]
public IEnumerable<string> Get()

但是,当我导航到 domain/api/Values 时,我总是看到数据而不是预期的重定向到 google。感谢您的帮助。

编辑:再四处看看后,我在这里找到了这个:http://weblogs.asp.net/jgalloway/archive/2012/05/04/asp-net-mvc-authentication-customizing-authentication-and-authorization-the-right-way.aspx这表明我选择了错误的 AuthorizeAttribute 类,因为我选择了 System.Web.MVC 中的类,而不是 System.Web.Http 中的类。似乎 Http 版本不允许与 MVC 版本相同级别的配置,因为它不允许我覆盖 AuthorizeCore。感谢您对此提供更多帮助。

最佳答案

问题似乎是使用了错误版本的 AuthorizeAttribute 引起的。使用在 System.Web.Http 中找到的版本后,如果用户没有所需的权限,代码将返回正确的错误代码。作为示例,这里是与我在原始问题中输入的代码等效的代码

using System;
using System.Web.Http;
using System.Net.Http;

public class AuthAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
HandleUnauthorizedRequest(actionContext);
}

protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Redirect);
response.Headers.Add("Location", "http://www.google.com");
actionContext.Response = response;
}
}

关于c# - 在 MVC 4 中使用自定义授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12882407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com