2016-09-22 21 views
1

我正在从ASP.Net Framework转移到ASP.Net Core。覆盖ASP.Net Core中的AuthorizeAttribute并响应Json状态

在ASP.Net应用中使用的Web API 2项目,我可以自定义AuthorizeAttribute这样的:

public class ApiAuthorizeAttribute : AuthorizationFilterAttribute 
{ 
    #region Methods 

    /// <summary> 
    ///  Override authorization event to do custom authorization. 
    /// </summary> 
    /// <param name="httpActionContext"></param> 
    public override void OnAuthorization(HttpActionContext httpActionContext) 
    { 
     // Retrieve email and password. 
     var accountEmail = 
      httpActionContext.Request.Headers.Where(
        x => 
         !string.IsNullOrEmpty(x.Key) && 
         x.Key.Equals("Email")) 
       .Select(x => x.Value.FirstOrDefault()) 
       .FirstOrDefault(); 

     // Retrieve account password. 
     var accountPassword = 
      httpActionContext.Request.Headers.Where(
        x => 
         !string.IsNullOrEmpty(x.Key) && 
         x.Key.Equals("Password")) 
       .Select(x => x.Value.FirstOrDefault()).FirstOrDefault(); 

     // Account view model construction. 
     var filterAccountViewModel = new FilterAccountViewModel(); 
     filterAccountViewModel.Email = accountEmail; 
     filterAccountViewModel.Password = accountPassword; 
     filterAccountViewModel.EmailComparision = TextComparision.Equal; 
     filterAccountViewModel.PasswordComparision = TextComparision.Equal; 

     // Find the account. 
     var account = RepositoryAccount.FindAccount(filterAccountViewModel); 

     // Account is not found. 
     if (account == null) 
     { 
      // Treat the account as unthorized. 
      httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); 

      return; 
     } 

     // Role is not defined which means the request is allowed. 
     if (_roles == null) 
      return; 

     // Role is not allowed 
     if (!_roles.Any(x => x == account.Role)) 
     { 
      // Treat the account as unthorized. 
      httpActionContext.Response = httpActionContext.Request.CreateResponse(HttpStatusCode.Forbidden); 

      return; 
     } 

     // Store the requester information in action argument. 
     httpActionContext.ActionArguments["Account"] = account; 
    } 

    #endregion 

    #region Properties 

    /// <summary> 
    ///  Repository which provides function to access account database. 
    /// </summary> 
    public IRepositoryAccount RepositoryAccount { get; set; } 

    /// <summary> 
    ///  Which role can be allowed to access server. 
    /// </summary> 
    private readonly byte[] _roles; 

    #endregion 

    #region Constructor 

    /// <summary> 
    ///  Initialize instance with default settings. 
    /// </summary> 
    public ApiAuthorizeAttribute() 
    { 
    } 

    /// <summary> 
    ///  Initialize instance with allowed role. 
    /// </summary> 
    /// <param name="roles"></param> 
    public ApiAuthorizeAttribute(byte[] roles) 
    { 
     _roles = roles; 
    } 

    #endregion 
} 

在我定制AuthorizeAttribute,我可以检查账户是否有效与否与消息返回HttpStatusCode客户。

我想在ASP.Net核心做同样的事情,但没有OnAuthorization为我重写。

我该如何实现ASP.Net Framework中的相同功能?

谢谢,

回答

5

你正在接近这个错误。从来没有真正鼓励为此编写自定义属性,或者扩展现有属性。与ASP.NET Core角色仍然是系统的向后兼容性的一部分,但他们现在也不鼓励。

有一个伟大的2部分系列的一些驾驶体系结构的变化和方式,这是和应该被利用发现here。如果你仍想依靠角色,你可以这样做,但我会建议使用策略。

连接一个政策执行下列操作:

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddAuthorization(options => 
    { 
     options.AddPolicy(nameof(Policy.Account), 
          policy => policy.Requirements.Add(new AccountRequirement())); 
    }); 
} 

我创建了一个Policy枚举为了方便。

public enum Policy { Account }; 

装饰的入口点为这样:

[ 
    HttpPost, 
    Authorize(Policy = nameof(Policy.Account)) 
] 
public async Task<IActionResult> PostSomething([FromRoute] blah) 
{ 
} 

AccountRequirement只是一个占位符,它需要实现IAuthorizationRequirement接口。

public class AccountRequirement: IAuthorizationRequirement { } 

现在我们只需创建一个处理程序并将其连接到DI即可。

public class AccountHandler : AuthorizationHandler<AccountRequirement> 
{ 
    protected override async Task HandleRequirementAsync(
     AuthorizationHandlerContext context, 
     AccountRequirement requirement) 
    { 
     // Your logic here... or anything else you need to do. 
     if (context.User.IsInRole("fooBar")) 
     { 
      context.Succeed(requirement); 
      return; 
     } 
    } 
} 

其他资源

+0

如果我想分析的HttpRequest从报头获得的access_token?因为我想自己实施GitHub OAuth,Google OAuth和Facebook OAuth。第三方库很难使用。 – Redplane

+0

不是问题,请设置此代码并检查“AuthorizationHandlerContext上下文”变量。你会发现它包含带有标题和路由数据的'HttpRequest'等。 –

+0

其实,我没有在那里看到HttpRequest。这里是我的形象: http://www.mediafire.com/view/c1bv86ktb16qqjj/Screenshot_%2815%29.png – Redplane