49 lines
1.5 KiB
C#
49 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Web.Http.Controllers;
|
|
using System.Web.Http.Filters;
|
|
using Kreta.User.WebApi.Infrastructure;
|
|
|
|
namespace Kreta.User.WebApi.Attributes
|
|
{
|
|
internal class ApiKeyAuthorizationAttribute : AuthorizationFilterAttribute, IOverrideFilter
|
|
{
|
|
const string ApiKey = nameof(ApiKey);
|
|
|
|
public Type FiltersToOverride
|
|
{
|
|
get
|
|
{
|
|
return typeof(IAuthorizationFilter);
|
|
}
|
|
}
|
|
|
|
private bool AccessGratnedByApiKey(KeyValuePair<string, IEnumerable<string>> apiKeyHeader)
|
|
{
|
|
if (apiKeyHeader.Value != null)
|
|
{
|
|
string targetApiKey = apiKeyHeader.Value?.SingleOrDefault();
|
|
|
|
if (!string.IsNullOrWhiteSpace(targetApiKey) && targetApiKey == ApiKeyConfiguration.Instance.ApiKey)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public override void OnAuthorization(HttpActionContext actionContext)
|
|
{
|
|
var headers = actionContext.Request.Headers;
|
|
|
|
var apiKeyHeader = headers.SingleOrDefault(x => x.Key.Equals(ApiKey, StringComparison.InvariantCultureIgnoreCase));
|
|
|
|
if (!AccessGratnedByApiKey(apiKeyHeader))
|
|
{
|
|
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
|
|
}
|
|
}
|
|
}
|
|
}
|