Angularjs 如何在angular resource中设置owin令牌身份验证头

Angularjs 如何在angular resource中设置owin令牌身份验证头,angularjs,asp.net-mvc,asp.net-web-api2,single-page-application,Angularjs,Asp.net Mvc,Asp.net Web Api2,Single Page Application,我对目前的工作非常陌生。我可能无法很好地解释,但正如我所理解的那样,我想把我的理解放在同样的基础上 我正在使用基于Owin令牌的web api身份验证,对于登录,我正在调用令牌方法,该方法返回访问令牌。我想知道如何保护我们的web api,以便在没有访问令牌的情况下不允许调用web api方法。我正在使用angularjs资源,我相信我们需要在angularjs服务部分中定义标题,但是我不知道具体在哪里以及如何定义,请任何人在这方面帮助我 例如:- 这是我用angularjs写的服务 sghSe

我对目前的工作非常陌生。我可能无法很好地解释,但正如我所理解的那样,我想把我的理解放在同样的基础上

我正在使用基于Owin令牌的web api身份验证,对于登录,我正在调用令牌方法,该方法返回访问令牌。我想知道如何保护我们的web api,以便在没有访问令牌的情况下不允许调用web api方法。我正在使用angularjs资源,我相信我们需要在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'
        }
    });
});
这是WebAPI方法

[Authorize]        
[Route("~/Api/eClaim/GlobalSettings")]
[HttpGet]
public ReportAndeCliam GetGlobalSettings()
{
    //Code Wriiten here
}
到目前为止,我能够在没有访问令牌的情况下访问web api,我想设计这样一种方式,如果令牌不可用,则不允许使用[Authorized]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);
    }
}
现在,当您从angular service传递安全密钥时,它将签入上述过滤器

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

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

您可以在MVC API代码中进行筛选,以检查标头中的安全密钥。正如我在示例中看到的,一旦我们在方法上使用[Authorize]属性,它将使web API方法安全,并且不允许我们在没有访问令牌的情况下调用web API方法。如果我的理解有误,请纠正。是的,你是对的。。我更新我的答案。你自己生成令牌吗?好的,谢谢,我会按照你的建议尝试,如果不行,请帮助我。再次感谢:)好的,试试看。。我认为它肯定会工作,因为它在我的项目中工作。@junaidameen如果它工作,那么就标记为accept answer,这样其他人就可以知道这是工作代码。你能告诉我什么是'ConfigItems',如果它是一个类,我们需要添加什么属性吗。“angular.filter”有什么插件吗?它只是一个类,我在其中创建了一些属性,可以从web.config文件访问应用程序设置。编辑答案。
[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');
}]);