2

저는 현재 현재 일하고있는 것에 매우 익숙합니다. 나는 잘 설명하지 못할 수도 있지만, 많은 것을 이해 했으므로 나는 같은 것을 이해하려고합니다.각도 자원에 오존 토큰 인증 헤더를 설정하는 방법

웹 API에 Owin 토큰 기반 인증을 사용하고 있습니다. 로그인 할 때 액세스 토큰을 반환하는 토큰 메서드를 호출하고 있습니다. 액세스 토큰없이 웹 API 메서드를 호출 할 수 없도록 웹 API를 보호하는 방법을 알고 싶습니다. 각도 js 리소스를 사용하고 있는데, angularjs 서비스 부분에 헤더를 정의 할 필요가 있다고 생각합니다. 그러나 정확히 어디에서 어떻게 생각하는지 모르겠습니다.

예 : -

AngularJS와 작성이 내 서비스,

sghServices.factory('GlobalSettingsService', function ($resource) { 
return $resource("../Api/eClaim/SecondGlobalSettings", 
    {}, 
    { 
     post: { 
      method: 'POST', isArray: false, 
      headers: { 'Content-Type': 'application/json' } 
     }, 
     update: { 
      method: 'PUT' 
     } 
    }); 
}); 

내가 액세스하지 않고 웹 API에 액세스 할 수 있어요 지금부터이 웹 API 방법

[Authorize]   
[Route("~/Api/eClaim/GlobalSettings")] 
[HttpGet] 
public ReportAndeCliam GetGlobalSettings() 
{ 
    //Code Wriiten here 
} 

입니다 토큰, 토큰을 사용할 수없는 경우 [승인 된] 웹 API 메서드를 사용할 수 없도록 디자인해야합니다.

감사의 말 :

+0

헤더에서 보안 키를 확인하기 위해 MVC API 코드에서 필터를 만들 수 있습니다. –

+0

예제에서 보았 듯이 메소드에서 [Authorize] 속성을 사용하면 웹 API 메소드가 안전 해지고 액세스 토큰없이 웹 API 메소드를 호출 할 수 없습니다. 제 이해가 잘못되면 저를 시정하십시오. – John

+0

네가 맞다. 나는 나의 대답을 업데이트한다. 그냥 체크 아웃하십시오. –

답변

6

아래와 같이 API 클래스를 만듭니다.

public class AuthorizeAPIAttribute : AuthorizationFilterAttribute 
{ 
    /// <summary> 
    /// Calls when a process requests authorization. 
    /// </summary> 
    /// <param name="actionContext">The action context, which encapsulates information for using <see cref="T:S:System.Web.Http.Filters.AuthorizationFilterAttribute" />.</param> 
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     if (!ConfigItems.APISecurityEnable) 
     { 
      return; 
     } 

     var headers = actionContext.Request.Headers; 
     var security = headers.Any(x => x.Key == "Security"); 
     if (security) 
     { 
      var value = headers.FirstOrDefault(x => x.Key == "Security").Value.FirstOrDefault(); 
      if (value != null) 
      { 
       string token = value; 
       if (token == ConfigItems.APIToken) 
       { 
        return; 
       } 
      } 
     } 

     actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); 
     actionContext.Response.Content = new StringContent("Security Failed", Encoding.UTF8, "application/json"); 
     base.OnAuthorization(actionContext); 
    } 
} 

ConfigItems 클래스

/// <summary> 
/// ConfigItems class 
/// </summary> 
public class ConfigItems 
{ 
    /// <summary> 
    /// Gets a value indicating whether API Security Enable 
    /// </summary> 
    public static bool APISecurityEnable 
    { 
     get 
     { 
      if (Convert.ToBoolean(WebConfigurationManager.AppSettings["APISecurityEnable"])) 
      { 
       return true; 
      } 
      else 
      { 
       return false; 
      } 
     } 
    } 

    /// <summary> 
    /// Gets a value APIToken 
    /// </summary> 
    public static string APIToken 
    { 
     get 
     { 
      return WebConfigurationManager.AppSettings["APIToken"]; 
     } 
    } 
} 

그리고이 같은에서 컨트롤러를 사용할 수 있습니다.

이제 각도 서비스에서 보안 키를 전달하면 위의 필터를 확인합니다.

angular.module('userApp').factory('httpRequestInterceptor', function() { 
    return { 
     request: function (config) { 
      config.headers['Security'] = "Key"; 
      return config; 
     } 
    }; 
}); 
angular.module('userApp', ['ngAnimate', 'ngRoute', 'angular.filter']).config(['$httpProvider', function ($httpProvider) { 
    $httpProvider.interceptors.push('httpRequestInterceptor'); 
}]); 

위와 같이 프로젝트에서 보안 키를 전역 적으로 설정할 수 있습니다.

+0

좋아, 고맙다. 내가 제안한대로 시도해 보겠다. 효과가 없다면 제발 도와주세요. 그리고 다시 감사드립니다 :) – John

+0

좋아요. 시도해보십시오. 제 프로젝트에서 작동하기 때문에 확실히 작동 할 것입니다. –

+0

@junaidameen 그 코드가 작동하는지 확인한 후 다른 사람들이 이것이 작동하는 코드인지 알 수 있도록 대답을 수락합니다. –

관련 문제