繁体   English   中英

如何在角度资源中设置owin令牌认证头

[英]how to set owin token authentication header in angular resource

我现在正在努力工作。 我可能不会很好地解释,但我已经理解,我想对我的理解相同。

我正在为web api使用基于Owin令牌的身份验证,对于登录我正在调用返回访问令牌的令牌方法。 我想知道如何保护我们的web api,这样没有访问令牌就不应该允许调用web 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'
        }
    });
});

这是web api方法

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

截至目前我能够访问没有访问令牌的web api,我想以这种方式设计如果令牌不可用,它不应该允许使用[授权] web api方法。

提前致谢 :)

在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"];
        }
    }
}

你可以像这样在控制器中使用它。

[AuthorizeAPIAttribute]
public class MainController : ApiController
{
}

现在,当您从角度服务传递安全密钥时,将检查上面的过滤器。

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');
}]);

如上所述,您可以在项目中全局设置安全密钥。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM