[英]Very basic bearer token authentication and authorization in Web API 2
I have an intranet site, hosted locally within my organisation.我有一个 Intranet 站点,在我的组织内本地托管。 The same site also exposes some data through various web services.
同一个站点还通过各种 Web 服务公开一些数据。 It's written using ASP.NET MVC 5 and WebAPI 2, and it's .NET 4.5, not Core.
它是使用 ASP.NET MVC 5 和 WebAPI 2 编写的,它是 .NET 4.5,而不是 Core。
At the moment users can login to the website using Windows Authentication, and once authenticated they can access the APIs.目前,用户可以使用 Windows 身份验证登录网站,一旦通过身份验证,他们就可以访问 API。 However, I need to also allow access to the APIs using tokens so that they can be interrogated by automated processes, so I've created a page where authenticated users can go and request a token.
但是,我还需要允许使用令牌访问 API,以便自动化进程可以查询它们,因此我创建了一个页面,经过身份验证的用户可以在其中请求令牌。
It's my intention that this token can be used as a Bearer token, included in the header of HTTP requests to the Web API, to allow access to the APIs.我打算将此令牌用作不记名令牌,包含在对 Web API 的 HTTP 请求的标头中,以允许访问 API。 As I understand it, a Bearer token intrinsically represents the User's right to access the data and doesn't require any other information (even a username).
据我了解,不记名令牌本质上代表用户访问数据的权利,不需要任何其他信息(甚至是用户名)。
However, I've struggled to find a complete, end-to-end tutorial for authenticating and authorizing the requests.但是,我一直在努力寻找一个完整的端到端教程来验证和授权请求。 There are questions on this site and Microsoft aritcles which give some great pointers but I feel that they're perhaps hinting at something much too complicated for my requirements.
这个网站上有一些问题和微软的文章提供了一些很好的指导,但我觉得他们可能暗示了一些对我的要求来说太复杂的东西。 I don't need to return any kind of Identity with Claims or anything like that, and I'm not concerned with OAuth at all.
我不需要用声明或类似的东西返回任何类型的身份,而且我根本不关心 OAuth。
I'm using Microsoft's Web API framework so it seems reasonable to assume that it should be fairly straightforward to do something as basic as extract and check a token from the request header!我正在使用 Microsoft 的 Web API 框架,因此可以合理地假设,从请求标头中提取和检查令牌之类的基本操作应该相当简单!
Would somebody be able to outline the components and the process I need to put in place within my application to allow it to extract the Bearer token from the HTTP request, use my own code to check its validity and then support the Authorize
attribute on Web API Methods if the token is valid?是否有人能够概述我需要在我的应用程序中放置的组件和流程,以允许它从 HTTP 请求中提取承载令牌,使用我自己的代码检查其有效性,然后支持 Web API 上的
Authorize
属性令牌是否有效的方法?
Looks like we have the same need, I also just needed a quick bearer token verification to not leave the API completely wide open.看起来我们有同样的需求,我还需要一个快速的不记名令牌验证,以免 API 完全开放。
I copied most parts from here and tweaked it so it just checks the Bearer token https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/authentication-filters我从这里复制了大部分部分并对其进行了调整,因此它只检查不记名令牌https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/authentication-filters
Add filter in WebApiConfig.cs在 WebApiConfig.cs 中添加过滤器
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Add authentication
config.Filters.Add(new SimpleAuthenticationFilter()):
foo
}
}
SimpleAuthenticationFilter.cs 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 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.