带有asp .net核心的防伪令牌jquery ajax

     2023-04-12     94

关键词:

【中文标题】带有asp .net核心的防伪令牌jquery ajax【英文标题】:Anti forgery token jquery ajax with asp .net core 【发布时间】:2020-06-22 02:26:59 【问题描述】:

我正在使用 jQuery 执行 ajax 请求,将其发送到 asp .net 核心控制器。我将请求与防伪令牌一起发送,如下所示:

    $('#btnSyncDictionary').click(function (event) 
    $.ajax(
        type: "POST",
        url: "HealthPanel/SyncDictionary",
        headers:  "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() 
    );

    event.stopImmediatePropagation();
    event.stopPropagation();
);

问题是它只适用于第一个 ajax 调用。随后的 ajax 调用未能通过 asp .net 核心控制器的防伪验证。

为什么会这样?我想我可能需要在每次请求后更新令牌。

【问题讨论】:

您能否分享有关您的视图和 SyncDictionary 操作的更多详细信息? 嗨@Alecu,你还有问题吗?你能分享更多可以重现你的问题的细节吗? 【参考方案1】:

TestMiddleware.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;

namespace Test.Middleware

    public class TestMiddleware
    
        private readonly RequestDelegate _next;
        public TestMiddleware(RequestDelegate next)
        
            _next = next;
        
        public async Task InvokeAsync(HttpContext httpContext, AppDbContext dataContext, UserManager<User> userManager, IAntiforgery antiforgery)
        
            SetAntiForgeryTokenCookie();
            // Move forward into the pipeline
            await _next(httpContext);
        
        private void SetAntiForgeryTokenCookie(HttpContext httpContext, IAntiforgery antiforgery)
        
            var tokens = antiforgery.GetAndStoreTokens(httpContext);
            httpContext.Response.Cookies.Append("CSRF-TOKEN", tokens.RequestToken, new CookieOptions()  HttpOnly = false );
        
    
    public static class TestMiddlewareExtensions
    
        public static IApplicationBuilder UseTestMiddleware(this IApplicationBuilder builder)
        
            return builder.UseMiddleware<TestMiddleware>();
        
    
    #endregion

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Test.Middleware;

namespace Test

    public class Startup
    
        public Startup(IConfiguration configuration)
        
            Configuration = configuration;
        

        public IConfiguration Configuration  get; 

        public void ConfigureServices(IServiceCollection services)
        
            services.AddControllersWithViews();

            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("Database"), b => b.MigrationsAssembly("Test")));

            services.AddIdentity<User, Role>()
                .AddEntityFrameworkStores<AppDbContext>()
                .AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
            
                // Password settings
                options.Password.RequireDigit = true;
                options.Password.RequiredLength = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = true;
                options.Password.RequireLowercase = false;
                options.Password.RequiredUniqueChars = 6;
                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers = true;
                // User settings
                options.User.RequireUniqueEmail = true;
            );
            services.ConfigureApplicationCookie(options =>
            
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(480);
                options.LoginPath = "/Account/Login";
                options.AccessDeniedPath = "/Account/AccessDenied";
                options.SlidingExpiration = true;
            );
            services.AddAntiforgery(options =>
            
                // Antiforgety settings
                options.HeaderName = "X-CSRF-TOKEN";
            );
        

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)
        
            if (env.IsDevelopment())
            
                app.UseDeveloperExceptionPage();
            
            else
            
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseTestMiddleware();
            app.UseEndpoints(endpoints =>
            
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "controller=Home/action=Index/id?");
            );
        
    

script.js

self.saveSurvey = function (userId) 
        var csrfToken = self.getCookie("CSRF-TOKEN");
        var ajaxUrl = "Account/Save",
            ajaxData = 
                UserId: userId
            ;
        $.ajax(
            type: "POST",
            url: ajaxUrl,
            data: JSON.stringify(ajaxData),
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            headers: 
                "X-CSRF-TOKEN": csrfToken
            ,
            success: function (viewModel) 
                console.log("Eureka!")
            ,
            error: function (error) 
                console.log("Not Eureka!")
            
        );
    ;

【讨论】:

如何使用带有 OpenId Connect 的刷新令牌在 asp.net 核心中处理过期的访问令牌

】如何使用带有OpenIdConnect的刷新令牌在asp.net核心中处理过期的访问令牌【英文标题】:Howtohandleexpiredaccesstokeninasp.netcoreusingrefreshtokenwithOpenIdConnect【发布时间】:2017-02-2306:39:08【问题描述】:我已经使用“Microsoft.AspNetCore.Authentic... 查看详情

使用防伪令牌将 JSON 模型发布到 ASP.Net MVC3

】使用防伪令牌将JSON模型发布到ASP.NetMVC3【英文标题】:PostingaJSONmodeltoASP.NetMVC3withAnti-forgerytoken【发布时间】:2012-08-2419:05:01【问题描述】:所以,我一直在用这个撞墙,我找不到任何好的来源。也许我忘记了模型绑定的东西在... 查看详情

带有 ASP.NET Identity 3 的 JWT 不记名令牌

】带有ASP.NETIdentity3的JWT不记名令牌【英文标题】:JWTbearertokensw/ASP.NETIdentity3【发布时间】:2016-03-0601:07:45【问题描述】:基于ShaunLuttin在https://***.com/a/30857524的出色示例,我能够使用该代码来生成和使用不记名令牌。小改动是为... 查看详情

ASP.NET 核心中是不是支持刷新令牌?

】ASP.NET核心中是不是支持刷新令牌?【英文标题】:IsthereanysupportofrefreshtokeninASP.NETcore?ASP.NET核心中是否支持刷新令牌?【发布时间】:2019-09-2321:10:12【问题描述】:我需要ASP.NETCore应用程序中的刷新令牌。目前,我已经实现了... 查看详情

asp.net 核心身份 - 2 种类型的 jwt 令牌

】asp.net核心身份-2种类型的jwt令牌【英文标题】:asp.netcoreidentity-2typesofjwttokens【发布时间】:2018-03-0322:06:45【问题描述】:我只是想知道,是否可以为2个不同的受众配置JWT令牌?第一个将设置令牌到期日期,而第二个则没有。... 查看详情

asp.net 核心中的 jwt 令牌无效

】asp.net核心中的jwt令牌无效【英文标题】:InvalidjwtTokeninasp.netcore【发布时间】:2020-11-1919:09:06【问题描述】:我正在尝试在我的Angular应用程序和ASP.net核心中使用JWT。对于初学者,我使用“邮递员”来测试我的端点。在我的API... 查看详情

带有 ViewModel 和两个表单的页面上的“防伪 cookie 令牌和表单字段令牌不匹配”

】带有ViewModel和两个表单的页面上的“防伪cookie令牌和表单字段令牌不匹配”【英文标题】:"Theanti-forgerycookietokenandformfieldtokendonotmatch"onpagewithViewModelandtwoforms【发布时间】:2015-06-1723:20:25【问题描述】:在Mono上运行的MVC... 查看详情

如何在发送响应之前获取防伪令牌?

】如何在发送响应之前获取防伪令牌?【英文标题】:HowtogetAntiforgerytokenbeforesendingresponse?【发布时间】:2021-08-3020:11:49【问题描述】:我有ASP.NETCore应用程序,它会自动验证AntiforgeryToken的每个POST请求:services.AddMvc(options=>option... 查看详情

带有取消令牌的自定义 ASP.NET Core 中间件

】带有取消令牌的自定义ASP.NETCore中间件【英文标题】:CustomASP.NETCoreMiddlewarewithcancellationToken【发布时间】:2016-11-0102:24:44【问题描述】:我有一个自定义ASP.NETCore中间件,我想检索请求的取消令牌。我尝试将它添加到调用的签... 查看详情

带有 Durandal SPA 模板的 MVC 身份验证和防伪令牌

】带有DurandalSPA模板的MVC身份验证和防伪令牌【英文标题】:MVCAuthenticationandAntiforgerytokenwithDurandalSPAtemplate【发布时间】:2013-03-2714:47:39【问题描述】:我的SPA的某些区域需要对所有用户开放,而某些区域需要身份验证。在这些... 查看详情

带有 ASP.NET Core WebAPI 的 Dart 中的令牌刷新并发问题

】带有ASP.NETCoreWebAPI的Dart中的令牌刷新并发问题【英文标题】:TokenrefreshconcurrencyissueinDartwithASP.NETCoreWebAPI【发布时间】:2019-03-1218:09:00【问题描述】:我使用Dart在Flutter中编写了一个简单的应用程序。我使用JWT令牌对用户进行身... 查看详情

ASP.NET 核心 JWT 令牌验证在同一来源上失败

】ASP.NET核心JWT令牌验证在同一来源上失败【英文标题】:ASP.NETcoreJWTTokenValidationfailsonsameorigin【发布时间】:2020-02-1610:16:34【问题描述】:我正在使用AngularWeb客户端编写一个ASP.NET核心(2.2)应用程序。对于身份验证,我使用JWT令牌... 查看详情

ASP.NET 核心中的密码重置令牌提供程序 - 找不到 IUserTokenProvider

】ASP.NET核心中的密码重置令牌提供程序-找不到IUserTokenProvider【英文标题】:PasswordresettokenproviderinASP.NETcore-IUserTokenProvidernotfound【发布时间】:2017-03-1915:55:06【问题描述】:你好,为了进行密码重置工作,我需要在DI中注册一个IU... 查看详情

带有 rc-1 的 jwtBearer 不记名令牌更新到 ASP.Net 5

】带有rc-1的jwtBearer不记名令牌更新到ASP.Net5【英文标题】:jwtBearerbearertokenwithrc-1updatetoASP.Net5【发布时间】:2016-03-2418:06:38【问题描述】:让我的asp.net5Web应用程序能够接受JWTtokens时遇到了很多麻烦。我的代码已经使用mvc5完全正... 查看详情

Jquery禁用Asp.net核心中的选定选项无法正常工作

...:2021-10-1710:03:46【问题描述】:在我的项目中,我有一个带有添加新行的按钮的表格。当我选择一个选项时,在每一行中都有一个选择框,它应该在所有其他选择框(包括新选择框)中被禁用。当我在这里尝试此代码时enterlinkde 查看详情

使用带有参数的jquery mobile的asp.net mvc提交表单

】使用带有参数的jquerymobile的asp.netmvc提交表单【英文标题】:asp.netmvcsubmitformusingjquerymobilewithparameter【发布时间】:2013-10-0800:16:37【问题描述】:我有一个带有单个位置下拉列表的移动表单。当我从DDL中选择一个位置时,我希望... 查看详情

带有列表的 asp.net 核心 ioptions

】带有列表的asp.net核心ioptions【英文标题】:asp.netcoreioptionswithalist【发布时间】:2017-08-0106:11:20【问题描述】:我正在尝试从appsettings.json文件中读取值列表。我可以毫无问题地读取Logging值,但列表值(即Servers)为空:appsettings... 查看详情

ASP.NET 核心 blazor webassembly 为 Identity Server 4 Postman 测试获取令牌

】ASP.NET核心blazorwebassembly为IdentityServer4Postman测试获取令牌【英文标题】:ASP.NETcoreblazorwebassemblygettingtokenforIdentityServer4Postmantesting【发布时间】:2021-09-1008:11:12【问题描述】:我正在尝试在具有身份服务器4个个人帐户的blazorwebasse... 查看详情