0

我有几个客户端应用程序正在使用的 webapi 后端。该 api 使用 jwt 身份验证进行保护,它基于以下示例:https ://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample 。由于我对基于令牌的身份验证的所有概念还不太熟悉,因此我可以在此使用一些指导。我的问题是我需要我的应用程序使用相同的 api,但将每个应用程序的访问权限限制为特定区域或控制器。

根据示例,我可以通过以下方式保护区域内的方法:

[Authorize("Api")]

在启动时添加了一个策略

    authOptions.AddPolicy("Api", new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) // "Bearer" scheme
        .RequireAuthenticatedUser().Build());

对于来自客户端的安全请求,我通常有一个 angular 2 应用程序,它只是在标头中添加 jwt,如下所示:

headers.append('Authorization', 'Bearer ' + jwt);

我不知道这里的所有机制,但我假设当请求安全方法时,“Api”属性装饰决定/限制在 api 中的某个路由使用哪个策略。

什么是最佳实践,我如何扩展它以使用可单独访问的部分?

4

1 回答 1

0

您可以创建一个ActionFilterAttributeforAuthorization并将其用于所有操作。

您可以FrameworkAuthorise根据您的要求实现过滤器方法。

在此处输入图像描述

Global.ApiKey是您的应用程序的唯一代码,用于标识您是否有权访问该应用程序。

     [FrameworkAuthorise(Global.ApiKey, AuthorisationType.None)]
     public async Task<IHttpActionResult> Get()        
     { 
        // code goes here
     }

    [FrameworkAuthorise(Global.ApiKey, AuthorisationType.Bearer)]
     public async Task<IHttpActionResult> Post()        
     { 
        // code goes here
     }

于 2016-06-23T15:16:25.237 回答