관리 메뉴

IT & Life

권한 필터를 사용하여 ASP.Net 웹 API를 보호하는 방법. 본문

프로그래밍/ASP.NET & C#

권한 필터를 사용하여 ASP.Net 웹 API를 보호하는 방법.

미운앙마 2017. 11. 11. 01:43

 

ASP.Net 웹 API 인증 필터를 활용하여 웹 API에 대한 수신 요청 권한 부여.

Take advantage of ASP.Net Web API authorization filters to authorize incoming requests to your web API.

 

 

보안은 웹 기반 엔터프라이즈 애플리케이션의 주요 관심사입니다. 유선을 통해 데이터를 전송해야하는 경우 해당 데이터를 보호하는 데 사용할 수있는 다양한 도구를 알고 있어야합니다.

Security is a major concern in web-based enterprise applications. When you need to transmit data over the wire, you should be aware of the various tools you can use to secure that data.

 

 

ASP.Net 웹 API는 HTTP에서 실행되는 상태 비 저장 RESTful 서비스를 작성하는 데 사용되는 경량 프레임 워크입니다. 웹 API 서비스를 보호하는 한 가지 방법은 인증 필터를 사용하는 것입니다.

ASP.Net Web API is a lightweight framework used for building stateless RESTful services that run on HTTP.  One way to secure Web API services is with authorization filters.

 


이상적으로는 웹 API 파이프 라인에서 초기에 인증 및 권한 부여를 수행해야합니다. 이는 요청주기에서 불필요한 처리 오버 헤드를 제거하는 데 도움이됩니다. 인증에 HTTP 모듈이나 HTTP 메시지 처리기를 사용하는지 여부에 상관없이 ApiController.User속성 에서 현재 보안 주체 (예 : 사용자)를 검색 할 수 있습니다 .

Ideally, you should perform authentication and authorization early in the Web API pipeline. This helps to eliminate unnecessary processing overhead from the request cycle. Note that, whether you use HTTP modules or HTTP message handlers for authentication, you can retrieve the current principal (i.e. the user) from the ApiController.User property.

 

 

또한 웹 API 권한 필터는 컨트롤러 조치 방법 이전에 실행된다는 점도 기억하십시오. 따라서 들어오는 요청이 승인되지 않으면 서비스에서 오류가 반환되고 요청은 무시되며 서비스의 동작 방법은 실행되지 않습니다.

Also keep in mind that Web API authorization filters execute before the controller action methods. So if the incoming request is not authorized, an error will be returned from the service, the request will be ignored, and the action method of the service will not be executed.


AuthorizeAttribute 권한 필터 사용

Using the AuthorizeAttribute authorization filter

 

 

내장 된 권한 필터 AuthorizeAttribute는 들어오는 요청을 권한 부여하는 데 사용할 수 있습니다. AuthorizeAttribute 사용자가 인증되었는지 확인 하는 데 사용할 수 있습니다  . 사용자가 인증되지 않으면 HTTP 상태 코드 401을 리턴합니다.이 권한은 웹 API에서 전역 또는 제어기 레벨에 적용될 수 있습니다.

The built-in authorization filter AuthorizeAttribute can be used to authorize incoming requests. You can use AuthorizeAttribute to check whether the user is authenticated. If the user is not authenticated, it will return the HTTP status code 401. This authorization can be applied in Web API globally or at the controller level.

 

 

메시지 필터가 웹 API 수명주기의 훨씬 이전에 실행되므로 사용자 정의 메시지 핸들러를 구현하여 컨트롤러 메소드에 대한 액세스 권한을 부여 할 수도 있습니다.

Note that you can also implement a custom message handler to authorize access to your controller methods as message filters are executed much earlier in the Web API life cycle.

 

 

모든 컨트롤러에 대한 액세스를 제한하기 위해 인스턴스 컬렉션에 AuthorizeAttribute전역으로 추가 할 수 있습니다 . 다음 코드 스니 j은 오브젝트 콜렉션에이를 추가하는 f} 을 보여줍니다. FiltersHttpConfigurationAuthorizeAttributeFiltersHttpConfiguration

To restrict access to all controllers, you can add the AuthorizeAttribute globally to the Filters collection of the HttpConfiguration instance. The following code snippet shows how you can add the AuthorizeAttribute to the Filters collection of the HttpConfiguration object.

 

 

        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: “DefaultApi”,
                routeTemplate: “api/{controller}/{id}”,
                defaults: new { id = RouteParameter.Optional }
            );
            config.Filters.Add(new AuthorizeAttribute());
        }

 


Authorize 특성 사용

Using the Authorize attribute

 

 

컨트롤러 레벨에서, Authorize다음에 주어진 코드 스 니펫과 같이 속성을 적용하여 액세스를 제한 할 수 있습니다 .

At the controller level, you can restrict access by applying the Authorize attribute as shown in the code snippet given next.

 

 

[Authorize]
public class EmployeesController : ApiController
{
    //Write methods here that correspond to the Http verbs
}

 


Authorize활동 레벨에서 속성을 적용하여 특정 조치 메소드에 대한 액세스를 제한 할 수도 있습니다 . 다음 코드 스니 j은 이것이 어떻게 구현 될 수 있는지를 보여줍니다.

You can also apply the Authorize attribute at the action level to restrict access to a particular action method. The following code snippet illustrates how this can be implemented.

 

 

public class EmployeesController : ApiController
{
    public HttpResponseMessage Get() { //Some code }
   // Require authorization for a specific action.
    [Authorize]
    public HttpResponseMessage Post(Employee emp) { //Some code }
}

 


앞에서 설명한 코드 스 니펫에서는 Post()메서드에 대한 액세스가 제한되어 있지만 메서드에 대한 액세스는 제한 Get()되지 않습니다. 컨트롤러를 제한 한 다음 하나 이상의 작업 방법에 익명 액세스를 제공 할 수도 있습니다. 다음 코드 스 니펫은이를 보여줍니다.

In the code snippet shown earlier, access to the Post() method is restricted while access to the Get() method is not restricted. You can also restrict the controller and then provide anonymous access to one or more action methods. The code snippet that follows illustrates this.

 

 

public class EmployeesController : ApiController
{
    public HttpResponseMessage Get() { //Some code }
    [AllowAnonymous]
    public HttpResponseMessage Post(Employee emp) { //Some code }
}

 


역할 및 사용자별로 작업 승인

Authorize actions by roles and users

 

 

역할 및 사용자별로 조치 메소드에 대한 액세스를 제한 할 수도 있습니다. 다음 코드 조각은 이것이 어떻게 달성 될 수 있는지 보여줍니다.

It is also possible to restrict access to action methods by roles and users. The following code snippet shows how this can be achieved.

 

 

[Authorize(Users="Joydip,Jini")] //Restrict access by user
public class EmployeesController : ApiController
{
   //Write methods here that correspond to the Http verbs
}

 


위의 예에서 Employees 컨트롤러는 사용자 Joydip 및 Jini에 대한 액세스 만 제한합니다. 아래 코드는 역할별로 액세스를 제한하는 방법을 보여줍니다.

In the above example, the Employees controller restricts access to the users Joydip and Jini only. The code below shows how you can restrict access by roles.

 

 

[Authorize(Roles="Administrators")] //Restrict by roles
public class EmployeesController : ApiController
{
    //Write methods here that correspond to the Http verbs
}

 


ApiController.User컨트롤러 메소드 내부 의 속성에 항상 액세스하여 현재 원칙을 검색하고 사용자의 역할에 따라 권한을 부여 할 수 있습니다. 아래 코드 목록에 나와 있습니다.

You can always access the ApiController.User property inside the controller method to retrieve the current principle and grant authorization based on the user’s role. This is shown in the code listing below.

 

 

public HttpResponseMessage Get()
{
    if (User.IsInRole(“Administrators”))
    {
        //Write your code here
    }
}

 

ASP.Net Web API에서 사용자 정의 권한 필터 사용

Using custom authorization filters in ASP.Net Web API

 

 

권한 필터는 클래스를 확장 AuthorizationFilterAttribute하고 OnAuthorization()메서드를 재정의하는 클래스 입니다. 이것은 권한 논리를 작성할 수있는 f}입니다. 인증에 실패하면 UnauthorizedException클래스 의 인스턴스 또는 사용자 정의를 반환 할 수 있습니다. HttpResponseMessage.

An authorization filter is a class that extends the AuthorizationFilterAttribute class and overrides the OnAuthorization() method. This is the method where you can write the authorization logic. If the authorization fails you can return an instance of the UnauthorizedException class or even a custom HttpResponseMessage.

 

 

다음 코드 목록은 웹 API에 대한 요청을 권한 부여하기위한 사용자 정의 클래스를 구현하는 방법을 보여줍니다. AuthorizeAttribute사용자 자신의 권한 필터 클래스를 구현 하도록 클래스를 확장해야합니다.

The following code listing shows how you can implement a custom class for authorizing requests to your web API. Note that you should extend the AuthorizeAttribute class to implement your own authorization filter class.

 

 

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
         public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (AuthorizeRequest(actionContext))
            {
                return;
            }
            HandleUnauthorizedRequest(actionContext);
        }
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
           //Code to handle unauthorized request
        }
        private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //Write your code here to perform authorization
            return true;
        }
    }

 

 

 

Comments