asp.net - 身份服务器 4 使用有效访问 token 获取 401 未授权

标签 asp.net asp.net-core .net-core identityserver4 identity

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

我在解决方案和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 的回答,我将 AddIdentityServerAuthentication 更改为 AddJwtBearer 并且出现 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: Unable to obtain configuration from: 'System.String'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'System.String'. ---> System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. (127.0.0.1:1080) ---> System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it. at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken) at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token) at System.Net.Sockets.Socket.g__WaitForConnectWithCancellation|283_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)

最佳答案

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

This library is deprecated and not being maintained anymore. Read this blog post about the reasoning and recommendations for a superior and more flexible approach: 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" };
    });

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

关于asp.net - 身份服务器 4 使用有效访问 token 获取 401 未授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67163963/

相关文章:

c# - ASP.NET 如何在路径和查询完好无损的情况下对新域执行 HTTP 301

使用 .NET Core 的 Azure Apps EasyAuth 声明

c# - 网络核心 : Is it Possible to Merge TagBuilder Style Attributes with CSS Files?

c# - ASP.NET Core - 在重负载下生成 "000000..."sha256 哈希

c# - EF Core - 等效于 IQueryable 搜索的表达式树

c# - 3 层架构中的 SQL 依赖性和 SignalR

asp.net - iisExpress 本地 httpruntime.cache 始终为 null

.net - 确定是否在没有System.Web的ASP.NET或WinForms/控制台中运行

c# - 将 appsettings.json 映射到 Dictionary<string, Value>

c# - 基础连接已关闭。无法使用 HTTP.sys 运行 Asp.Net Core 2.1 Web API 应用程序?