Asp.Net Core 2.1 - Authorize based on content in request

陌路散爱 提交于 2019-12-12 00:03:19

问题


I am exposing an endpoint for integration with a 3rd party and their requirement is for me to authorize their requests to my endpoint based on a key passed in the body being posted. My code will then needs to validate that the passed key matches some predetermined value on my side. The incoming model will look something like this:

public class RequestBase
{
    public string ApiKey { get; set; }
    ...
}

Exploring the options for Authorization in ASP.NET Core I don't really see a match for what I am attempting to do. I am thinking a custom AuthorizeAttribute from this question would work but I'm not having any luck and get a 401 regardless of what I do. This is what I have so far:

[AttributeUsage(AttributeTargets.Class)]
public class MyAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    private static IEnumerable<string> _apiKeys = new List<string>
        {
            "some key... eventually will be dynamic"
        };

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var req = context.HttpContext.Request;
        req.EnableRewind();

        using (var reader = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
        {
            var bodyStr = reader.ReadToEnd();
            var isAuthorized = _apiKeys.Any(apiKey => bodyStr.Contains(apiKey));
            if (!isAuthorized)
            {
                context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
                return;
            }
        }

        req.Body.Position = 0;
    }
}

When the key is not found in the body the 403 is returned as expected. However, when the key is found the result I get back is still a 401. Almost seems as if the base.OnAuthorization is being called. I have other endpoints that use a standard AurhorizeAttribute. They work as expected when only if I pass in a JWT.

Questions:

  1. Am I on the right path with a custom AuthorizeAttribute or is there a better way?
  2. If a customer AuthorizeAttribute is the right path... what am I missing?

Appreciate any help!


回答1:


For using your own authorize logic with IAuthorizationFilter, you should not use with AuthorizeAttribute which will check the Authentication with default authentication schema.

Try to change AuthorizeAttribute to Attribute.

[AttributeUsage(AttributeTargets.Class)]
public class KeyAuthorizeAttribute : Attribute, IAuthorizationFilter
{


来源:https://stackoverflow.com/questions/52854765/asp-net-core-2-1-authorize-based-on-content-in-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!