【问题标题】:how to set owin token authentication header in angular resource如何在角度资源中设置 owin 令牌身份验证标头
【发布时间】:2016-10-21 05:45:30
【问题描述】:

我对我目前的工作非常陌生。我可能解释得不好,但就我所知,我想把我的理解放在同样的地方。

我正在为 web api 使用基于 Owin 令牌的身份验证,对于登录,我正在调用返回访问令牌的令牌方法。我想知道如何保护我们的 web api,以便在没有访问令牌的情况下不允许调用 web api 方法。我正在使用 angular 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,如果令牌不可用,我想以这样的方式进行设计,它不应该允许使用 [Authorized] web api 方法。

在此先感谢 :)

【问题讨论】:

  • 您可以在 MVC API 代码中进行过滤,以从标头检查安全密钥。
  • 正如我在一个例子中看到的,一旦我们在方法上使用了 [Authorize] 属性,它使 web api 方法安全,它不会让我们允许在没有的情况下调用 web api 方法访问令牌。如果我的理解有误,请纠正我。
  • 是的,你是对的。我更新了我的答案。看看吧。
  • 自己生成token吗?

标签: angularjs asp.net-mvc asp.net-web-api2 single-page-application


【解决方案1】:

在 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 服务传递安全密钥时,该服务将签入上述过滤器。

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

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

【讨论】:

  • 好的,谢谢,我会按照您的建议尝试,如果不起作用,请帮助我。再次感谢:)
  • 好吧,试试吧。我认为它肯定会起作用,因为它在我的项目中起作用。
  • @junaidameen 如果它的工作然后标记为接受答案,以便其他人可以知道这是工作代码。
  • 你能告诉我什么是'ConfigItems',如果它是一个类,我们需要添加什么属性。那么'angular.filter'有什么插件吗?
  • 这只是我创建了一些属性的一类,我可以从其中访问来自 web.config 文件的应用程序设置。编辑答案。
猜你喜欢
  • 2015-05-08
  • 2023-03-09
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
  • 2018-06-03
  • 1970-01-01
相关资源
最近更新 更多