gpt4 book ai didi

c# - WEB API - 在 Controller 或操作级别授权(无身份验证)

转载 作者:太空狗 更新时间:2023-10-29 17:28:32 26 4
gpt4 key购买 nike

我有一个没有身份验证的现有 API。它是一个公共(public) Web API,多个客户端通过发出简单请求使用它。

现在,需要授权访问某个方法。

有没有办法做到这一点,让其余的 Controller 和相应的方法对已经使用该 Web API 的客户端保持“开放”状态?

我如何确定请求是否有权访问此“ protected ”方法?

最佳答案

您需要做的是向您想要保护的方法添加一个 [Authorize] 属性,可选择使用接受一个或多个调用用户必须在其中的角色名称的重载。

然后您必须实现的是一种方法,以确保将调用者的身份验证数据转换为 Principal 对象。设置 Principal 通常不是您自己做的事情,而是让框架为您做。

如果您确实想提供自己的接口(interface),您可以使用实现 System.Web.Http.Filters.IAuthenticationFilter 接口(interface)的身份验证过滤器。

那么你会得到的是:

[MyAuthentication]
[Authorize]
public SomeClass MyProtectedMethod() {
return new SomeClass();
}

然后实现MyAuthentication 属性。下面是一个示例,重要的是您使用传入请求的上下文并最终使用新的 Principal 设置 context.Principal 属性

public class MyAuthentication : ActionFilterAttribute, System.Web.Http.Filters.IAuthenticationFilter {

public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
// 1. Look for credentials in the request.
HttpRequestMessage request = context.Request;
AuthenticationHeaderValue authorization = request.Headers.Authorization;

// 2. If there are no credentials, do nothing.
if (authorization == null)
{
return;
}

// 3. If there are credentials but the filter does not recognize the
// authentication scheme, do nothing.
if (authorization.Scheme != "Basic")
{
return;
}

// 4. If there are credentials that the filter understands, try to validate them.
// 5. If the credentials are bad, set the error result.
if (String.IsNullOrEmpty(authorization.Parameter))
{
context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request);
return;
}

Tuple<string, string> userNameAndPasword = ExtractUserNameAndPassword(authorization.Parameter);
if (userNameAndPasword == null)
{
context.ErrorResult = new AuthenticationFailureResult("Invalid credentials", request);
}

string userName = userNameAndPasword.Item1;
string password = userNameAndPasword.Item2;

IPrincipal principal = await AuthenticateAsync(userName, password, cancellationToken);
if (principal == null)
{
context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request);
}

// 6. If the credentials are valid, set principal.
else
{
context.Principal = principal;
}

}


... other interface methods here
}

我希望这可以帮助您走上正轨。有关更多信息,请查看此帖子: http://www.asp.net/web-api/overview/security/authentication-filters

关于c# - WEB API - 在 Controller 或操作级别授权(无身份验证),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38751104/

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