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

标签 c# authentication asp.net-web-api authorization

我有一个没有身份验证的现有 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/

相关文章:

c# - 在 C# 中使用 Neo4JClient 为 Neo4J 定义架构

c# - 谁可以访问 MVVM 模式中的数据库

c# - 在 WPF 中单击更改圆圈 "start-stop"按钮背景图像

c# - 如果我在我的应用程序中使用它,是否必须安装 SQL Server?

Angular 2 : have component auto detect variable change in a service

java - Spring Security 记住我身份验证

c# - 使用 key 大小小于 2048 的 RSA 安全 key 创建 JWT token 时出错

Asp.Net Web API 与 Web 服务

asp.net-mvc - 如何为 ASP.NET 4.5 Web API 创建 MultipartFormFormatter

c# - MVC 5 身份验证和 HttpClient 没有可用的 MediaTypeFormatter