首页 > 解决方案 > 身份服务器 4 使用有效的访问令牌获取 401 未经授权

问题描述

我在我的 .NET 5.0 核心 API 应用程序中使用身份服务器 4。我在本地服务器 https://localhost:[port]/connect/token 上获得了成功的令牌,当我使用承载令牌访问授权方法时,我收到 401 错误

我在添加了 [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.AddDbContext<AplicationDbContext>(options => options.UseSqlServer(Configuration["connectionString"]));
        //services.AddMvc(options =>
        //{
        //    options.Filters.Add(typeof(HttpGlobalExceptionFilter));
        //});
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "copyTrade", Version = "v1" });
        });
        services.AddLocalization(options => options.ResourcesPath = "Resources");
        services.Configure<DataProtectionTokenProviderOptions>(opt =>
                   opt.TokenLifespan = TimeSpan.FromHours(12));
        services.AddOptions();
        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.AddIdentityServer()
             .AddDeveloperSigningCredential(persistKey: false)
             .AddInMemoryApiResources(Config.GetApiResources())
             .AddInMemoryApiScopes(Config.ApiScopes)
             .AddInMemoryClients(Config.GetClients(ClientSettings))
             .AddAspNetIdentity<ApplicationUser>()
             .AddResourceOwnerValidator<OwnerPasswordValidator>();
        services.AddAuthentication(options =>
        {
            options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
        })
      .AddIdentityServerAuthentication(options =>
      {
          options.ApiName = "api1";
          options.Authority = ClientSettings.Authority;
          options.RequireHttpsMetadata = false;
          //options.TokenValidationParameters = new TokenValidationParameters
          //{
          //    ValidateAudience = false
          //};
      });
        services.AddControllers();
        
        services.AddTransient<IProfileService, IdentityClaimsProfileService>();
        services.AddMvcCore(options =>
        {
            options.Filters.Add(typeof(HttpGlobalExceptionFilter));
        })
       .AddAuthorization();
        services.AddCors(options =>
        {
            options.AddPolicy(name: "CorsPolicy",
                builder => builder
               .AllowAnyOrigin()
               //.SetIsOriginAllowed((host) => true)
               .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();
        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"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures,
            RequestCultureProviders = new List<IRequestCultureProvider>()
            {
                new QueryStringRequestCultureProvider(),
                new CookieRequestCultureProvider()
            }
        });
    }

     

我的身份服务器配置文件:

 public class Config
{
    public Config(IConfiguration configuration) => this.Configuration = configuration;

    public IConfiguration Configuration { get; }
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Email(),
            new IdentityResources.Profile(),

        };
    }
    public static IEnumerable<ApiScope> ApiScopes =>
    new List<ApiScope>
    {
        new ApiScope("api1", "api1")
    };

    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("api1", "api1"),
        };
    }

    public static IEnumerable<Client> GetClients(BearerTokensOptions bearerTokensOptions)
    {
        return new List<Client>
        {
            new Client
            {
                AccessTokenLifetime=bearerTokensOptions.AccessTokenExpirationSeconds,
                IdentityTokenLifetime = bearerTokensOptions.AccessTokenExpirationSeconds,
                ClientId = bearerTokensOptions.ClientId,
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                ClientSecrets =
                {
                    new Secret("S23Mn67".Sha256())
                },
                AllowedScopes = {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    IdentityServerConstants.StandardScopes.Address,
                    "api1"
                }
            }
        };
    }
}

应用设置文件:

 "BearerTokens": {
"Key": "This is my shared key, not so secret, secret!",
"Issuer": "http://localhost:41407/",
"Audience": "Any",
"Authority": "http://localhost:41407/",
"AccessTokenExpirationSeconds": 21600,
"RefreshTokenExpirationSeconds": 60,
"AllowMultipleLoginsFromTheSameUser": false,
"ClientId": "CopyTradeApi",
"AllowSignoutAllUserActiveClients": true
},
 "PasswordOptions": {
 "RequireDigit": false,
 "RequiredLength": 6,
 "RequireLowercase": false,
 "RequireNonAlphanumeric": false,
 "RequireUppercase": false
},

根据@Michal 的回答,我更改AddIdentityServerAuthenticationAddJwtBearer并收到 404 错误,但是当我将AddAuthentication()参数更改JwtBearerDefaults.AuthenticationScheme为如下时,我收到其他错误

.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;
        });

进行此更改后,我收到此错误:

System.InvalidOperationException:IDX20803:无法从“System.String”获取配置。---> System.IO.IOException:IDX20804:无法从“System.String”检索文档。---> System.Net.Http.HttpRequestException: 由于目标机器主动拒绝,无法建立连接。(127.0.0.1:1080) ---> System.Net.Sockets.SocketException (10061): 由于目标机器主动拒绝,无法建立连接。在 System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 令牌) 的 System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError 错误,CancellationToken cancelToken)。 Sockets.Socket.g__WaitForConnectWithCancellation|283_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask,

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

解决方案


您正在使用AddIdentityServerAuthentication,已弃用。这可能会导致问题。https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation

该库已弃用,不再维护。阅读此博客文章,了解有关更高级和更灵活方法的推理和建议:https ://leastprivilege.com/2020/07/06/flexible-access-token-validation-in-asp-net-core/

您可以AddJwtToken改用并设置Authority指向您的应用程序。

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Authority = "http://localhost:41407";
        o.TokenValidationParameters.ValidateAudience = false;
        o.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
    });

几天前,我在自己的带有 IdentityServer4 的应用程序中使用了这段代码,它运行良好。


推荐阅读