首页 > 解决方案 > 在身份服务器 4 中使用 Authorize 时,将 api 重定向到 Account/Login

问题描述

我在我的 .NET 5.0 核心 API 应用程序中使用身份服务器 4。我在本地服务器 https://localhost:[port]/connect/token 上获得了成功的令牌,当我使用承载令牌访问授权方法时,我得到 302 状态 HTTP 响应,然后重定向到其他链接: http://localhost:41407/Account/Login?ReturnUrl=/api/Auth/getUserInfo

没有 Authorize 的 API 运行良好

启动.cs:

 public void ConfigureServices(IServiceCollection services)
    {
        var ClientSettings = this.Configuration.GetSection("BearerTokens").Get<BearerTokensOptions>();
        var PasswordOptions = this.Configuration.GetSection("PasswordOptions").Get<PasswordOptions>();
        services.Configure<AntiDosConfig>(options => Configuration.GetSection("AntiDosConfig").Bind(options));
        services.Configure<AntiXssConfig>(options => Configuration.GetSection("AntiXssConfig").Bind(options));
        services.AddDbContext<AplicationDbContext>(options => options.UseSqlServer(Configuration["connectionString"]));
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "copyTrade", Version = "v1" });
        });

      
        services.AddHtmlReaderService();
        services.AddAntiXssService();

        services.AddLocalization(options => options.ResourcesPath = "Resources");
        

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(o =>
        {
            o.Authority = "http://localhost:41407";
            o.TokenValidationParameters.ValidateAudience = false;

            o.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
            o.RequireHttpsMetadata = false;
        });
        services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
        {
            options.Password.RequireDigit = PasswordOptions.RequireDigit;
            options.Password.RequireLowercase = false;
            options.Password.RequireUppercase = false;
            options.Password.RequiredLength = 6;
            options.Password.RequireNonAlphanumeric = false;
            options.Lockout.AllowedForNewUsers = true;
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
            options.Lockout.MaxFailedAccessAttempts = 4;
        })
            .AddEntityFrameworkStores<AplicationDbContext>()
            .AddDefaultTokenProviders();
        services.Configure<DataProtectionTokenProviderOptions>(opt =>
                   opt.TokenLifespan = TimeSpan.FromHours(12));

        services.AddTransient<IProfileService, IdentityClaimsProfileService>();
        services.AddMvc(options =>
        {
            options.Filters.Add(typeof(HttpGlobalExceptionFilter));
        });
        services.AddIdentityServer()
             .AddDeveloperSigningCredential(persistKey: false)
             .AddInMemoryApiResources(Config.GetApiResources())
             .AddInMemoryClients(Config.GetClients(ClientSettings))
             .AddAspNetIdentity<ApplicationUser>()
             .AddResourceOwnerValidator<OwnerPasswordValidator>(); 
        services.AddCors(options =>
        {
            options.AddPolicy(name: "CorsPolicy",
                builder => builder
               .AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader()

              );
        });
       
    }

    // 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();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "copyTrade v1"));
        }
        app.UseCors("CorsPolicy");
        app.UseRouting();
        app.UseIdentityServer();
        app.UseAuthentication();
        this.ConfigureAuth(app);
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
        var supportedCultures = new[]
           {
            new CultureInfo("en-US"),
            new CultureInfo("fa-IR"),
        };
        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("fa-IR"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures,
            RequestCultureProviders = new List<IRequestCultureProvider>()
            {
                new QueryStringRequestCultureProvider(),
                new CookieRequestCultureProvider()
            }
        });
    }
    protected virtual void ConfigureAuth(IApplicationBuilder app)
    {
        if (this.Configuration.GetValue<bool>("UseLoadTest"))
        {
            app.UseMiddleware<ByPassAuthMiddleware>();
        }
        app.UseAuthentication();
    }

标签: asp.netasp.net-core.net-coreidentityserver4identity

解决方案


推荐阅读