ASP.NET WebAPI(消息处理程序) - 为什么Authorize属性允许所有请求?

时间:2013-11-23 17:46:07

标签: asp.net-web-api

我创建了关于ASP.NET WebAPI的示例,我使用消息处理程序来设置主体。在控制器类中,我为某些方法设置了authorize属性但是允许所有请求???谁能帮我? 非常感谢!!!

AuthenticationHandler类

public class AuthenticationHandler : DelegatingHandler
{        
    private readonly IUserRepository _userRepository;

    public AuthenticationHandler(IUserRepository userRepository)
    {            
        _userRepository = userRepository;
    }

    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        var accessToken = request.Headers.GetCookies("Authorization-Token");
        if (accessToken.Count == 0) 
        //requests have no token always go here and doesn't set principal!!!!
            return base.SendAsync(request, cancellationToken);

        var tokenValue = accessToken[0]["Authorization-Token"].Value;
        try
        {
            var token = RSAClass.Decrypt(tokenValue);
            if (token == null)
                return base.SendAsync(request, cancellationToken);

            var user = _userRepository.GetUserData(token);

            var identity = new GenericIdentity(user.Username, "Basic");
            if (user.Roles != null)
            {
                var principal = new GenericPrincipal(identity, user.Roles.Split(',').Reverse().ToArray());
                Thread.CurrentPrincipal = principal;
            }                
        }
        catch (Exception e) {
            return System.Threading.Tasks.Task<HttpResponseMessage>.Factory.StartNew(
            () => request.CreateResponse(HttpStatusCode.Unauthorized));
        }
        return base.SendAsync(request, cancellationToken);
    }
}

控制器类

    //when i try send anonymous request, it always allows to get data???  
    // Why authorize attribute not working
    [Authorize(Roles = "Administrators")]
    public HttpResponseMessage GetAll() {
        var customers = repository.GetAll();
        var customersDto = new List<CustomerDto>();
        if (customers == null)
        {
            var response = Request.CreateResponse(HttpStatusCode.NotFound, "Customer not found");
            throw new HttpResponseException(response);
        }
        else
        {
            foreach (var cust in customers)
            {
                customersDto.Add(mapper.Map<Customer, CustomerDto>(cust));
            }
            return Request.CreateResponse<List<CustomerDto>>(
            HttpStatusCode.OK,
            customersDto);
        }
    }    

1 个答案:

答案 0 :(得分:1)

因为在web api中,Authorize属性实际上不起作用,而且更多是关于asp.net mvc方法。

要在asp.net web api中启用AuthorizationHandler,您需要添加处理程序。您应该在那里映射您的路径 - WebApiConfig类或Global.asax.cs

以下是为所有Web api路由分配身份验证处理程序的示例

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new AuthenticationHandler());

        config.Routes.MapHttpRoute(name: "DefaultApi",...);
    }
}

enter code here