简体   繁体   English

使用授权属性时的 Cors 策略错误

[英]Cors policy error when using Authorize Attribute

I am getting a cors policy error whenever I use Authorize attribute on my user controller.I am using Angular 8 as my front-end framework and asp .net core 3.0.0 as my backend.It is working fine if I remove the authorize attribute from the controller.每当我在用户控制器上使用 Authorize 属性时,我都会收到 cors 策略错误。我使用 Angular 8 作为我的前端框架,使用 asp .net core 3.0.0 作为我的后端。如果我删除授权属性,它工作正常从控制器。 控制台错误 . . Below is my startup.cs file.下面是我的startup.cs文件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
using DatingApp.API.Data;
using DatingApp.API.Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace DatingApp.API {
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader());
            });
            services.AddAutoMapper(typeof(DatingRepository).Assembly);
            services.AddScoped<IAuthRepository, AuthRepository>();
            services.AddScoped<IDatingRepository, DatingRepository>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(builder =>
                {
                    builder.Run(async context =>
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                        var error = context.Features.Get<IExceptionHandlerFeature>();
                        if (error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                // app.UseHsts();
            }
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();
            app.UseCors("CorsPolicy");
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers().RequireCors("CorsPolicy");
            });

        }
    }
}

This is my usercontroller这是我的用户控制器在此处输入图片说明

Firstly I need to add app.UseAuthentication();首先我需要添加app.UseAuthentication(); for adding the authentication as a middleware in my startup.cs file and then I also need to configure the same in my services.用于在我的 startup.cs 文件中添加身份验证作为中间件,然后我还需要在我的服务中配置相同的内容。 Here is modification in startup.cs file这是在startup.cs文件中的修改在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复 CORS 策略阻止 AJAX 调用在 MVC Core 3.1 中使用 [Authorize] 属性? - How to fix CORS policy preventing AJAX calls from using [Authorize] attribute in MVC Core 3.1? 在 .NET 中使用授权属性时出现未经授权的 HTML 错误 401 - HTML error 401 unauthorized when using Authorize Attribute in .NET 使用[授权]时出错 - Error when using [Authorize] 仅当 api 引发错误时,我才收到 CORS 策略错误 - I recieve a CORS policy error only when the api throws an error .net 核心 3.0 授权属性与 Policy、AuthenticationSchemes - .net core 3.0 authorize attribute with Policy, AuthenticationSchemes 自定义授权属性或基于策略的授权处理程序 - custom authorize attribute or policy based authorization handler JWT Auth与Authorize Attribute一起使用,但不适用于[Authorize(Policy =“ Administrator”)] - JWT Auth works with Authorize Attribute but not with [Authorize (Policy = “Administrator”)] 在 dotnet core 3.0 中使用 [Authorize]-attribute 时修改响应内容 - Modify content of response when using [Authorize]-attribute in dotnet core 3.0 使用[Authorize]属性时未读取身份验证cookie - Authentication cookie not being read when using [Authorize] attribute 带有Authorize属性的ASP.NET 5 beta8 CORS无效 - ASP.NET 5 beta8 CORS with Authorize attribute is not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM