繁体   English   中英

Web API 2 中非常基本的承载令牌身份验证和授权

[英]Very basic bearer token authentication and authorization in Web API 2

我有一个 Intranet 站点,在我的组织内本地托管。 同一个站点还通过各种 Web 服务公开一些数据。 它是使用 ASP.NET MVC 5 和 WebAPI 2 编写的,它是 .NET 4.5,而不是 Core。

目前,用户可以使用 Windows 身份验证登录网站,一旦通过身份验证,他们就可以访问 API。 但是,我还需要允许使用令牌访问 API,以便自动化进程可以查询它们,因此我创建了一个页面,经过身份验证的用户可以在其中请求令牌。

我打算将此令牌用作不记名令牌,包含在对 Web API 的 HTTP 请求的标头中,以允许访问 API。 据我了解,不记名令牌本质上代表用户访问数据的权利,不需要任何其他信息(甚至是用户名)。

但是,我一直在努力寻找一个完整的端到端教程来验证和授权请求。 这个网站上有一些问题和微软的文章提供了一些很好的指导,但我觉得他们可能暗示了一些对我的要求来说太复杂的东西。 我不需要用声明或类似的东西返回任何类型的身份,而且我根本不关心 OAuth。

我正在使用 Microsoft 的 Web API 框架,因此可以合理地假设,从请求标头中提取和检查令牌之类的基本操作应该相当简单!

是否有人能够概述我需要在我的应用程序中放置的组件和流程,以允许它从 HTTP 请求中提取承载令牌,使用我自己的代码检查其有效性,然后支持 Web API 上的Authorize属性令牌是否有效的方法?

看起来我们有同样的需求,我还需要一个快速的不记名令牌验证,以免 API 完全开放。

我从这里复制了大部分部分并对其进行了调整,因此它只检查不记名令牌https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/authentication-filters

在 WebApiConfig.cs 中添加过滤器

public class WebApiConfig    
{    
    public static void Register(HttpConfiguration config)    
    {    
        // Add authentication    
        config.Filters.Add(new SimpleAuthenticationFilter()):  
        foo
    }  
}

SimpleAuthenticationFilter.cs

public class SimpleAuthenticationFilter : IAuthenticationFilter
{
    private readonly string _bearerToken = ConfigurationManager.AppSettings["simpleToken"];
    public bool AllowMultiple { get; }

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

        // 2. If there are no credentials, do nothing.
        if (authorization == null)
        {
            context.ErrorResult = new AuthenticationFailureResult("Authorization header is 'null''", request);
            return;
        }

        // 3. If there are credentials but the filter does not recognize the 
        //    authentication scheme, do nothing.
        if (!authorization.Scheme.Equals("Bearer"))
        {
            context.ErrorResult = new AuthenticationFailureResult("Authentication type must be 'Bearer'", request);
            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("Bearer token is null or empty", request);
            return;
        }

        if (!authorization.Parameter.Equals(_bearerToken))
        {
            context.ErrorResult = new AuthenticationFailureResult("Bearer token invalid", request);
        }
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        return Task.FromResult(0);
    }
}

AuthenticationFailureResponse.cs

  public class AuthenticationFailureResult : IHttpActionResult
  {
    public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request)
    {
        ReasonPhrase = reasonPhrase;
        Request = request;
    }

    private string ReasonPhrase { get; }

    private HttpRequestMessage Request { get; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Execute());
    }

    private HttpResponseMessage Execute()
    {
        var response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
        {
            RequestMessage = Request, ReasonPhrase = ReasonPhrase
        };
        return response;
    }
}

扩展上面 Min 的回答:

string token = Request.Headers.Authorization.ToString().Split(' ')[1];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM