加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 在身份验证过滤器中的ChallengeAsync方法的

发布时间:2020-12-16 06:27:33 所属栏目:asp.Net 来源:网络整理
导读:这个问题与我提供的答案 here有关.OP的评论让我思考了一下.我建议在身份验证过滤器的ChallengeAsync方法中使用一个实现IHttpActionResult的类. public Task ChallengeAsync(HttpAuthenticationChallengeContext context,CancellationToken cancellationToken
这个问题与我提供的答案 here有关.OP的评论让我思考了一下.我建议在身份验证过滤器的ChallengeAsync方法中使用一个实现IHttpActionResult的类.

public Task ChallengeAsync(HttpAuthenticationChallengeContext context,CancellationToken cancellationToken)
{
    context.Result = new ResultWithChallenge(context.Result);
    return Task.FromResult(0);
}

public class ResultWithChallenge : IHttpActionResult
{
    private readonly IHttpActionResult next;

    public ResultWithChallenge(IHttpActionResult next)
    {
        this.next = next;
    }

    public async Task<HttpResponseMessage> ExecuteAsync(
                                CancellationToken cancellationToken)
    {
        var response = await next.ExecuteAsync(cancellationToken);
        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            response.Headers.WwwAuthenticate.Add(
                   new AuthenticationHeaderValue("Basic","realm=localhost"));
        }

        return response;
    }
}

而不是这样,我可以像这样简化ChallengeAsync.

public Task ChallengeAsync(HttpAuthenticationChallengeContext context,CancellationToken cancellationToken)
{
    var result = await context.Result.ExecuteAsync(cancellationToken);
    if (result.StatusCode == HttpStatusCode.Unauthorized)
    {
        result.Headers.WwwAuthenticate.Add(
                     new AuthenticationHeaderValue("Basic","realm=localhost"));
    }
    context.Result = new ResponseMessageResult(result);
}

这使我免于创建实现IHttpActionResult的类,但这是正确的方法吗?我感到一种不安的感觉,从性能的角度来看,这有点不好,因为我感觉我正在将动作结果转换为HttpResponseMessage并返回到动作结果.关于需要一个单独的类在这里实现IHttpActionResult像我建议的那样的任何指针将被赞赏使用上面的代码.

解决方法

目的是使用第一种方法而不是第二种方法.例如,请参阅基本身份验证示例(也可用于MVC),它遵循第一种方法:
http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/BasicAuthentication/ReadMe.txt

第二种方法大多有效.我不会太担心表现的立场;无论哪种方式,你分配一个动作结果对象和一个响应消息对象,所以我没有看到太大的区别.

但是,我推荐第一种方法有几个原因:

>第二种方法在MVC中的工作方式不同. MVC和Web API都有身份验证过滤器,它们的工作方式基本相同.但是在MVC中,没有与ResponseMessageResult等效的东西(HttpContext根据需要进行更新,而不是返回一个HttpResponseMessage,它可以被每个调用者上传到堆栈中).如果你有一个身份验证过滤器的MVC实现,你可能最终会在那里做第一个方法.
>它略微改变了管道行为的意图. ChallengeAsync中的代码早于上下文中的代码运行.它返回的结果.例如,如果代码更改了HttpRequestMessage上的属性并且影响了后来的过滤器的ChallengeAsync逻辑,则行为可能与预期的不同.

该框架肯定可以使界面更容易实现;随时投票支持这个工作项目:
https://aspnetwebstack.codeplex.com/workitem/1456

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读