【问题标题】:How to post Antiforgery token from IdentityServer 3如何从 IdentityServer 3 发布防伪令牌
【发布时间】:2017-05-20 08:42:37
【问题描述】:

我正在使用 IdentityServer 3 进行身份验证。当用户通过身份验证时,IdentityServer 向客户端的应用程序 URL 发出“POST”请求。例如 http://localhost/home 到目前为止一切正常。

我的客户端应用程序是在 ASP.NET Core 中开发的。在客户端应用程序中,我想验证每个 POST 请求。因此,我没有在每个操作方法上添加 ValidateAntiForgeryToken 属性,而是创建了一个中间件来验证每个 POST 请求。

public class ValidateAntiForgeryTokenMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IAntiforgery _antiforgery;

    public ValidateAntiForgeryTokenMiddleware(RequestDelegate next, IAntiforgery antiforgery)
    {
        _next = next;
        _antiforgery = antiforgery;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if (httpContext.Request.Method.ToUpper() == "POST")
        {
            await _antiforgery.ValidateRequestAsync(httpContext);
        }

        await _next(httpContext);
    }
}

这里的问题是由于身份服务器也在进行 POST,中间件尝试验证该请求,但 POST 请求失败并出现以下错误

"所需的防伪cookie \".AspNetCore.Antiforgery.AXelvXewLHI\" 不存在。"

在 Identity Server 中,我有自定义登录页面。我已经在登录页面配置了防伪令牌。

<div ng-show="model.loginUrl">
    <div class="cr-login-dialog col-md-6 col-md-offset-3">
        <form name="form" method="post" action="{{model.loginUrl}}" class="form-horizontal" role="form">
            <anti-forgery-token token="model.antiForgery"></anti-forgery-token>
            <div class="form-group">
                //user name controls goes here
            </div>
            <div class="form-group">
                //password controls goes here
            </div>
            <div class="form-group" ng-show="model.allowRememberMe">
                // remember me controls goes here
            </div>
        </form>
    </div>
</div>

【问题讨论】:

    标签: asp.net-core-mvc identityserver3 antiforgerytoken


    【解决方案1】:

    您应该分离出您的 anti-xsrf 中间件,使其仅在您的请求上运行,而不是对 IdentityServer 的请求。 IdentityServer 自己做与 MVC 实现无关的 anti-xsrf 令牌(因为 IdentityServer 不依赖于 MVC)。

    【讨论】:

    • 这就是问题所在。中间件无法区分 POST 请求是来自 IdentityServer 还是来自用户的浏览器。
    • 然后使用 MW 作为实现的地方不是正确的选择。
    • You should separate out your anti-xsrf middleware to only run on your requests, not the requests to IdentityServer.......。请注意,中间件将尝试验证请求 from identityserver。当它重定向到客户端应用程序的起始页面时,我想要身份 POST 防伪令牌
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 2019-03-05
    • 2018-01-16
    • 2013-11-27
    相关资源
    最近更新 更多