code

사용자 지정 권한 부여 MVC4 Web Api에서 게시물 액세스 또는 매개 변수 가져 오기

codestyles 2020. 12. 25. 09:53
반응형

사용자 지정 권한 부여 MVC4 Web Api에서 게시물 액세스 또는 매개 변수 가져 오기


HttpActionContext 개체를 통해 게시물에 액세스하거나 매개 변수를 가져올 수 있습니까?

REST API를 제공하는 웹 서버에 데이터를 로깅하는 센서 세트가 있습니다. 센서가 데이터에 하드웨어 ID를 포함하도록 한 다음 ID가 존재하는지 여부를 확인하기 위해 데이터베이스에서 조회하도록하여 일종의 인증 / 권한을 도입하고 싶습니다. API는 많은 웹 API 작업 방법을 제공하므로 사용자 지정 권한 부여 속성을 사용하는 것이 이상적입니다.

public class ApiAuthorizationFilter : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        return false;
    }
}

actionContext에서 post / get 데이터에 액세스하려면 어떻게해야합니까?

편집 : POST의 예

POST /Api/api/ActionMethod/ HTTP/1.1\r\n
Content-Type: application/json\r\n
Host: localhost\r\n
Accept: */*\r\n
Content-Length:52\r\n
\r\n
{"Id": '121a222bc', "Time": '2012-02-02 12:00:00'}\r\n

좋은 하루 되세요!


특성으로 인해 AuthoriseAttribute는 모델 바인더 및 매개 변수 바인딩이 실행되기 전에 파이프 라인에서 호출되는 것처럼 보입니다. 또한 Request.Content에 액세스하여 읽을 때 문제가 발생합니다 ... 이것은 한 번만 수행 할 수 있으며 auth 속성에서 시도하려는 경우 mediaTypeFormater를 중단 할 수 있습니다.

WebAPI에서 요청 본문 (HttpContent)은 읽기 전용, 무한, 버퍼링 및 되감기 불가능한 스트림 일 수 있습니다.

업데이트 실행 컨텍스트를 지정하는 방법에는 여러 가지가 있습니다 ... http://msdn.microsoft.com/en-us/library/system.web.http.filters.filterscope(v=vs.108).aspx . AuthoriseAttribute는 "Global"이므로 작업 정보에 액세스하기에는 너무 일찍 적중됩니다.

모델 및 매개 변수에 대한 액세스를 원하면 접근 방식을 약간 변경하고 대신 OnActionExecuting 필터 ( "Action"필터 범위)를 사용하고 유효성 검사에 따라 401 또는 403을 throw 할 수 있습니다.

이 필터는 나중에 실행 프로세스에서 호출되므로 바인딩 된 데이터에 대한 전체 액세스 권한이 있습니다.

아래의 아주 간단한 예 :

public class ApiAuthorizationFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        Foo model = (Foo)actionContext.ActionArguments["model"];
        string param1 = (string)actionContext.ActionArguments["param1"];
        int param2 = (int)actionContext.ActionArguments["param2"];

        if (model.Id != "1")
            throw new HttpResponseException(System.Net.HttpStatusCode.Forbidden);

        base.OnActionExecuting(actionContext);
    }
}

컨트롤러 예 :

public class Foo
{
    public string Id { get; set; }
    public DateTime Time { get; set; }
}

public class FoosController : ApiController
{
    // PUT api/foos/5
    [ApiAuthorizationFilter]
    public Foo Put(int id, Foo model, [FromUri]string param1 = null, int? param2 = null)
    {
        return model;
    }
}

다른 답변이 말한 것 .... 그들은 맞습니다. URL에서 필요한 모든 것에 액세스 할 수 있다면 요청을 통해 물건을 얻을 수 있습니다. 그러나 모델과 요청 내용은 그대로 두어야한다고 생각합니다.

var queryStringCollection = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);

    //example for param1
    string param1 = queryStringCollection["param1"];
    //example for param2
    int param2 = int.Parse(queryStringCollection["param2"]);
    //Example of getting the ID from the URL
    var id = actionContext.Request.RequestUri.Segments.LastOrDefault();

다음과 같은 것을 호출 할 때 사용자 지정 AuthorizeAttribute 내에서 매개 변수를 가져 오기 위해 컨텍스트 경로 데이터에 액세스했습니다 /api/client/123/users.

public class CustomAuthorizeAttribute : AuthorizeAttribute
  {
     protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
     {
        var clientId = Convert.ToInt32(actionContext.ControllerContext.RouteData.Values["clientid"]);

        // Check if user can access the client account.

     }
  }

다음 코드를 사용하여 사용자 지정 권한 부여 속성에서 쿼리 문자열 값에 액세스 할 수 있습니다.

public class ApiAuthorizationFilter : AuthorizeAttribute
{
    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        var querystring = filterContext.RequestContext.HttpContext.Request.QueryString;
        // Do what you need
    }
}

Although this question has already been answered. But in case someone else needs it, you can get the querystrings from ActionFilterAttribute like below:

public class ApiAuthorizationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var queryParameters = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);

        var some_value = queryParameters.ContainsKey("some_key")
                    ? queryParameters["some_key"] : string.Empty;

        // Log Action Filter call
        base.OnActionExecuting(actionContext);
    }
}

But usually how I build API authorizations are using headers and a custom verification logic by adding keys (unique strings) to the database against user/client etc.

public class ApiAuthorizationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var headers = actionContext.Request.Headers.ToDictionary(x => x.Key, x => x.Value);

        string api_key = headers.ContainsKey("api_key") ? headers["api_key"].FirstOrDefault() : null;

        bool canAccessApi = IsValidKey(api_key);

        if (!canAccessApi)
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have access to this API. Please use a valid key.");

        // Log Action Filter call
        base.OnActionExecuting(actionContext);
    }

    private bool IsValidKey(string api_key)
    {
        //Build Access Control Logic here using database keys...
        return true;
    }
}

You should be able to get this information from actionContext.Request That is the way to get to the request data.

The posted data is in actionContext.Request.Content Or if it's a GET request you could get the querystring from actionContext.Request.RequestUri

ReferenceURL : https://stackoverflow.com/questions/12817202/accessing-post-or-get-parameters-in-custom-authorization-mvc4-web-api

반응형