使用代理后授权停止工作

发布于 2025-02-01 22:04:31 字数 3194 浏览 3 评论 0 原文

我们使用ASP.NET Core 3.1 MVC与React 17.0.2。另外,还使用Windows身份验证。

通过阅读本文档< /a>,我们已将代理文件添加到代理API调用到ASP.NET MVC Core,

因此我们的开发配置文件 dev.js 看起来像这样:

// development config
const package = require('../../package.json')
const { merge } = require('webpack-merge')
const webpack = require('webpack')
const commonConfig = require('./common')

module.exports = (webpackConfigEnv, argv) => {
    return merge(commonConfig(argv), {
        mode: 'development',
        entry: [
            'react-hot-loader/patch', // activate HMR for React
            'webpack-dev-server/client?http://localhost:3030', // 
            'webpack/hot/only-dev-server', // bundle the client for hot reloading,
            './index.tsx', // the entry point of our app
        ],
        devServer: {
            port: 3030,
            hot: true, // enable HMR on the server
            historyApiFallback: true, 
            proxy: {
                '/api/*': {
                    target: argv.env.mock ? '' : 'https://localhost:8800',
                    secure: false,
                },
            },
        },
        devtool: 'cheap-module-source-map',
        plugins: [
            new webpack.HotModuleReplacementPlugin(), // enable HMR globally
            new webpack.DefinePlugin({
                'process.env.appVersion': JSON.stringify(package.version),
                'process.env.isMockMode': JSON.stringify(argv?.env?.mock),
                'process.env.isDevelopment': true,
            }),
        ],
    })
}

但是,身份验证停止使用此配置。所有API调用返回401错误。

我认为COR可以解决这个问题。但是,身份验证在附加以下代码之后无法开始工作:

public void ConfigureServices(IServiceCollection services)
{
    // ... the other code is omitted for the brevity
    services.AddCors();
    // ... the other code is omitted for the brevity
    services.AddAuthorization(options =>
        {
            options.AddPolicy("MyPolicy", policy => 
                policy.Requirements.Add(new MyPolicyAuthorizationRequirement()));
        });


    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddSingleton<IAuthorizationHandler, MyPolicyAuthorizationRequirementHandler>();
    services.AddScoped<IClaimsTransformation, WindowsAuthenticationClaimsTransformation>();
}

configure()方法:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
    app.UseHttpsRedirection();
    app.UseDefaultFiles();
    app.UseCookiePolicy();
    app.UseStaticHttpContext();

    app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod());

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

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=FooAction}/{id?}");
    });
}

如果我构建React Application,则身份验证正常。 有人知道怎么了吗?任何帮助将不胜感激。

We are using ASP.NET Core 3.1 MVC with React 17.0.2. Also, Windows Authentication is used.

By reading this documentation, we've added a proxy file to proxy API calls to ASP.NET MVC Core

So our development config file dev.js looks like this:

// development config
const package = require('../../package.json')
const { merge } = require('webpack-merge')
const webpack = require('webpack')
const commonConfig = require('./common')

module.exports = (webpackConfigEnv, argv) => {
    return merge(commonConfig(argv), {
        mode: 'development',
        entry: [
            'react-hot-loader/patch', // activate HMR for React
            'webpack-dev-server/client?http://localhost:3030', // 
            'webpack/hot/only-dev-server', // bundle the client for hot reloading,
            './index.tsx', // the entry point of our app
        ],
        devServer: {
            port: 3030,
            hot: true, // enable HMR on the server
            historyApiFallback: true, 
            proxy: {
                '/api/*': {
                    target: argv.env.mock ? '' : 'https://localhost:8800',
                    secure: false,
                },
            },
        },
        devtool: 'cheap-module-source-map',
        plugins: [
            new webpack.HotModuleReplacementPlugin(), // enable HMR globally
            new webpack.DefinePlugin({
                'process.env.appVersion': JSON.stringify(package.version),
                'process.env.isMockMode': JSON.stringify(argv?.env?.mock),
                'process.env.isDevelopment': true,
            }),
        ],
    })
}

However, authentication stopped working with this configuration. All API calls return 401 error.

I thought that CORS can solve the issue. However, authentication did not start to work after appying the following code:

public void ConfigureServices(IServiceCollection services)
{
    // ... the other code is omitted for the brevity
    services.AddCors();
    // ... the other code is omitted for the brevity
    services.AddAuthorization(options =>
        {
            options.AddPolicy("MyPolicy", policy => 
                policy.Requirements.Add(new MyPolicyAuthorizationRequirement()));
        });


    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddSingleton<IAuthorizationHandler, MyPolicyAuthorizationRequirementHandler>();
    services.AddScoped<IClaimsTransformation, WindowsAuthenticationClaimsTransformation>();
}

And Configure() method:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
    app.UseHttpsRedirection();
    app.UseDefaultFiles();
    app.UseCookiePolicy();
    app.UseStaticHttpContext();

    app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod());

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

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=FooAction}/{id?}");
    });
}

If I build React application, then authentication works fine.
Does anybody know what is wrong? Any help would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不知在何时 2025-02-08 22:04:31

我找到了真的很棒文章关于我们如何通过代理发送授权标题。

因此,我们需要使用 Agent 并通过代理发送 HTTPS 标题。

有必要安装 agent keepareive npm软件包:

npm install -D agentkeepalive

完整的代理文件如下:

// development config
const package = require('../../package.json')
const { merge } = require('webpack-merge')
const webpack = require('webpack')
const commonConfig = require('./common')
const agent = require('agentkeepalive')

module.exports = (webpackConfigEnv, argv) => merge(commonConfig(argv), {
        mode: 'development',
        entry: [
            'react-hot-loader/patch',
            'webpack-dev-server/client?http://localhost:3030',
            'webpack/hot/only-dev-server',
            './index.tsx', // the entry point of our app
        ],
        devServer: {
            port: 3030,
            hot: true, // enable HMR on the server
            historyApiFallback: true,
            proxy: {
                '/api/*': {
                    target: argv.env.mock ? '' : 'https://localhost:8800/',
                    secure: false,
                    changeOrigin: true,
                    agent: new agent.HttpsAgent({
                        maxSockets: 100,
                        keepAlive: true,
                        maxFreeSockets: 10,
                        keepAliveMsecs: 100000,
                        timeout: 6000000,
                        freeSocketTimeout: 90000, // free socket keepalive for 90 seconds
                    }),
                    onProxyRes: (proxyRes) => {
                        var key = 'www-authenticate'
                        proxyRes.headers[key] =
                            proxyRes.headers[key] && proxyRes.headers[key].split(',')
                    },
                },
            },
        },
        devtool: 'cheap-module-source-map',
        plugins: [
            new webpack.HotModuleReplacementPlugin(), // enable HMR globally
            new webpack.DefinePlugin({
                'process.env.appVersion': JSON.stringify(package.version),
                'process.env.isMockMode': JSON.stringify(argv?.env?.mock),
                'process.env.isDevelopment': true,
            }),
        ],
    })

I've found a really great article about how we can send authorization headers through proxy.

So we need to use agent and send https headers through agent.

It is necessary to install the agentkeepalive npm package:

npm install -D agentkeepalive

The complete proxy file looks like this:

// development config
const package = require('../../package.json')
const { merge } = require('webpack-merge')
const webpack = require('webpack')
const commonConfig = require('./common')
const agent = require('agentkeepalive')

module.exports = (webpackConfigEnv, argv) => merge(commonConfig(argv), {
        mode: 'development',
        entry: [
            'react-hot-loader/patch',
            'webpack-dev-server/client?http://localhost:3030',
            'webpack/hot/only-dev-server',
            './index.tsx', // the entry point of our app
        ],
        devServer: {
            port: 3030,
            hot: true, // enable HMR on the server
            historyApiFallback: true,
            proxy: {
                '/api/*': {
                    target: argv.env.mock ? '' : 'https://localhost:8800/',
                    secure: false,
                    changeOrigin: true,
                    agent: new agent.HttpsAgent({
                        maxSockets: 100,
                        keepAlive: true,
                        maxFreeSockets: 10,
                        keepAliveMsecs: 100000,
                        timeout: 6000000,
                        freeSocketTimeout: 90000, // free socket keepalive for 90 seconds
                    }),
                    onProxyRes: (proxyRes) => {
                        var key = 'www-authenticate'
                        proxyRes.headers[key] =
                            proxyRes.headers[key] && proxyRes.headers[key].split(',')
                    },
                },
            },
        },
        devtool: 'cheap-module-source-map',
        plugins: [
            new webpack.HotModuleReplacementPlugin(), // enable HMR globally
            new webpack.DefinePlugin({
                'process.env.appVersion': JSON.stringify(package.version),
                'process.env.isMockMode': JSON.stringify(argv?.env?.mock),
                'process.env.isDevelopment': true,
            }),
        ],
    })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文