身份验证过滤器:如何使用消息

时间:2015-09-24 19:20:38

标签: c# asp.net authentication asp.net-web-api2 asp.net-web-api

我跟着http://bitoftech.net/2014/12/15/secure-asp-net-web-api-using-api-key-authentication-hmac-authentication/做了自定义身份验证过滤器。

一切正常但我无法让服务器在401上说任何话。它正确地给出www-authenicate标题和状态代码401但没有内容/正文。

我尝试使用来自http://www.asp.net/web-api/overview/security/authentication-filtersAuthenticationFailureResult,但没有帮助。我将AuthenticateAsync转换为async并忽略了await警告。

这是我目前的工作,评论中的代码是我 - 我希望 - 我可以做的,这主要是它使用任何格式化程序

//request.CreateResponse(HttpStatusCode.Unauthorized, new { Error = true, Message = "Token is invalid" });
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.Write("{ \"Error\" = true, \"Message\" = \"Token is invalid\" }");
context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], request);

2 个答案:

答案 0 :(得分:9)

有两种方法可以做到这一点:快速但粗暴,更长但更优雅

一个。直接修改HttpResponse:

HttpContext.Current.Response.StatusCode = 401;
HttpContext.Current.Response.Write("some content");

B中。实施IHttpActionResult并在该类中设置Content的{​​{1}}属性:

HttpResponseMessage

然后你就可以像这样使用它了:

public class AuthenticationFailureResult : IHttpActionResult
{
    public AuthenticationFailureResult(object jsonContent, HttpRequestMessage request)
    {
        JsonContent = jsonContent;
        Request = request;
    }

    public HttpRequestMessage Request { get; private set; }

    public Object JsonContent { get; private set; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Execute());
    }

    private HttpResponseMessage Execute()
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        response.RequestMessage = Request;
        response.Content = new ObjectContent(JsonContent.GetType(), JsonContent, new JsonMediaTypeFormatter());
        return response;
    }
}

注意:如果您想对context.ErrorResult = new AuthenticationFailureResult(new { Error = true, Message = "Token is invalid" }, request); 使用匿名类型,请确保JsonContent在同一个库中实现。

答案 1 :(得分:3)

如果你想附上一条消息和401回复,我想你应该这样做。这就是我在项目中的表现:

public class TokenAuthenticationAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        // Do your authentication here
    }

    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        if (actionContext == null)
        {
            throw new ArgumentNullException("actionContext", "Null actionContext");
        }

        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
        actionContext.Response.Headers.Add("AuthenticationStatus", "NotAuthorized");
        actionContext.Response.ReasonPhrase = "Authentication failed";

        // Create your content here (I use Student class as an example)
        actionContext.Response.Content = new ObjectContent(
            typeof (Student),
            new Student("Forte", 23),
            new JsonMediaTypeFormatter());
    }
}

学生班:

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Student(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

然后,我这样使用它:

[TokenAuthentication]
public class DocumentController : ApiController
{
    // Your code here
}

修改!!!

感谢评论中的wal建议,以下是将消息附加到回复的简短方法:

actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                new {Error = true, Message = "Token is invalid"});

然后,您的回复消息将是:

{"$id":"1","error":true,"message":"Token is invalid"}

通过这种方式,您不必再设置actionContext.Response.Content