C# Web api的静态api密钥

C# Web api的静态api密钥,c#,asp.net,ajax,api,restful-authentication,C#,Asp.net,Ajax,Api,Restful Authentication,我构建了一个RESTful API(使用ASP.NETWebAPI2),它只用于从单个端点使用。这个端点是一个只包含HTML/CSS/JS的基本前端站点。由于各种原因,前端站点和API完全是外部的,前端站点在API的CORS配置中被列为白名单 我现在正试图锁定API,以便只从这个特定的端点访问它,而不引入新的登录系统,因为此页面所在的上下文确保访问它的任何人都已经是受信任的用户(从技术上讲,它是在登录系统的后面,但是使用API的页面几乎不知道这个上下文) 在较高的层次上,我想引入某种静态定义的A

我构建了一个RESTful API(使用ASP.NETWebAPI2),它只用于从单个端点使用。这个端点是一个只包含HTML/CSS/JS的基本前端站点。由于各种原因,前端站点和API完全是外部的,前端站点在API的CORS配置中被列为白名单

我现在正试图锁定API,以便只从这个特定的端点访问它,而不引入新的登录系统,因为此页面所在的上下文确保访问它的任何人都已经是受信任的用户(从技术上讲,它是在登录系统的后面,但是使用API的页面几乎不知道这个上下文)

在较高的层次上,我想引入某种静态定义的API密钥,它将被硬编码到消费页面的API和JavaScript中,以帮助确保它是访问API的唯一端点。我们可以假设前端页面和API之间的所有通信都将通过安全SSL/TLS连接进行

我的问题:在这种情况下,我想使用静态定义的API密钥对来自特定页面的API请求进行身份验证,从易于实现的角度来看,我的最佳选择是什么?我在Web API授权方面找到的大多数文章都围绕用户登录系统展开,似乎对我的特定页面设计过度用例。当我谈到这个问题时,我会认为自己是新手,所以我真的希望有人能给我指出正确的方向。


谢谢!

在这种情况下,您似乎正在寻找全局筛选器

身份验证筛选器是对HTTP请求进行身份验证的组件

基本上,您将在授权头中的每个请求中发送共享/静态api密钥,自定义筛选器将处理该密钥并决定请求是否有效

过滤器的基本实现:

AuthenticationFailureResultAddChallengeOnUnauthorizedResult是IHttpActionResult的实现。为了全面起见,我将在这里添加它们

身份验证失败结果

class AuthenticationFailureResult:IHttpActionResult
{
私有HttpRequestMessage\u请求;
公共身份验证失败结果(HttpRequestMessage请求)
{
_请求=请求;
}
公共任务执行同步(CancellationToken CancellationToken)
{
HttpResponseMessage response=新的HttpResponseMessage(HttpStatusCode.Unauthorized);
response.RequestMessage=\u请求;
response.Content=newstringcontent(“拒绝访问消息”);
返回Task.FromResult(响应);
}
}
AddChallengeOnUnauthorizedResult

class AddChallengeOnUnauthorizedResult:IHttpActionResult
{
public AddChallengeOnUnauthorizedResult(AuthenticationHeaderValue质询,IHttpActionResult innerResult)
{
挑战=挑战;
InnerResult=InnerResult;
}
公共身份验证HeaderValue质询{get;private set;}
公共IHttpActionResult InnerResult{get;private set;}
公共异步任务ExecuteAsync(CancellationToken CancellationToken)
{
HttpResponseMessage response=等待InnerResult.ExecuteAsync(cancellationToken);
if(response.StatusCode==HttpStatusCode.Unauthorized)
{
//每个身份验证方案仅添加一个质询。
if(!response.Headers.WwwAuthenticate.Any((h)=>h.Scheme==Challenge.Scheme))
{
response.Headers.wwwaauthenticate.Add(质询);
}
}
返回响应;
}
}

这段代码源于本文或本文的衍生版本,我有一个类似的案例,我有一个通过SSL的API,我想知道添加一个带有密钥的头或参数是否会使它更安全,或者是一个不好的做法,你做了什么?
public class ApiKeyAuthenticationAttribute : IAuthenticationFilter
{
    public bool AllowMultiple { get; set; }

    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        HttpRequestMessage request = context.Request;

        // Get Auth header
        AuthenticationHeaderValue authorization = request.Headers.Authorization;

        // Validate the static token
        if (authorization?.Parameter == "123")
        {
            IPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim> { new Claim("CLAIMTYPE", "CLAIMVALUE") }));

            context.Principal = principal;
        }
        else
        {
            context.ErrorResult = new AuthenticationFailureResult(request);
        }
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        var challenge = new AuthenticationHeaderValue("Basic");
        context.Result = new AddChallengeOnUnauthorizedResult(challenge, context.Result);

        return Task.FromResult(0);
    }
}
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Some more config here
        config.Filters.Add(new IdentityBasicAuthenticationAttribute());
    }
}
class AuthenticationFailureResult : IHttpActionResult
{
    private HttpRequestMessage _request;

    public AuthenticationFailureResult(HttpRequestMessage request)
    {
        _request = request;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        response.RequestMessage = _request;
        response.Content = new StringContent("ACCESS DENIED MESSAGE");

        return Task.FromResult(response);
    }
}
class AddChallengeOnUnauthorizedResult : IHttpActionResult
{
    public AddChallengeOnUnauthorizedResult(AuthenticationHeaderValue challenge, IHttpActionResult innerResult)
    {
        Challenge = challenge;
        InnerResult = innerResult;
    }

    public AuthenticationHeaderValue Challenge { get; private set; }

    public IHttpActionResult InnerResult { get; private set; }

    public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await InnerResult.ExecuteAsync(cancellationToken);

        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            // Only add one challenge per authentication scheme.
            if (!response.Headers.WwwAuthenticate.Any((h) => h.Scheme == Challenge.Scheme))
            {
                response.Headers.WwwAuthenticate.Add(Challenge);
            }
        }

        return response;
    }
}