WEB API 添加jwt认证后,跨域失效问题

发布时间 2023-07-07 16:28:52作者: 追D

WEB API 添加jwt认证后,跨域失效问题

跨域配置策略如下:

//添加跨域策略
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", opt => opt.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().WithExposedHeaders("X-Pagination"));
            });

在没有加入jwt认证之前,跨域是正常的

添加jwt认证后,需要认证的接口加上了 Authorize 注解

然后出现了,The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the CORS policy by listing individual origins if credentials needs to be supported.”

经过排查和上网搜索发现有两个方法可以解决。

一、使用前端进行跨域配置的方式

代码如下:

在vue.config.js中添加

   devServer: {
     proxy: {
         '/api': {
             target: 'http://localhost:5197/api/',
             // 允许跨域
            changeOrigin: true,
             ws: true,
             pathRewrite: {
                 '^/api': ''
             }
        }
     }
 }

二、将使用跨域策略放在认证授权代码之上

//使用跨域策略
            app.UseCors("CorsPolicy");

            #region 鉴权授权
            app.UseAuthentication();
            app.UseAuthorization();
            #endregion