簡體   English   中英

身份服務器 4 使用有效的訪問令牌獲取 401 未經授權

[英]identity server 4 Getting 401 Unauthorized with valid access token

我在我的 .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's answer,我將AddIdentityServerAuthentication更改為AddJwtBearer並且我收到 404 錯誤但是當我將 JwtBearerDefaults.AuthenticationScheme 的JwtBearerDefaults.AuthenticationScheme AddAuthentication()參數更改為如下時,我收到其他錯誤

.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.TaskInt16 令牌在 System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError 錯誤,CancellationToken cancelToken)。 Sockets.Socket.g__WaitForConnectWithCancellation|283_0(AwaitableSocketAsyncEventArgs saea,ValueTask connectTask,CancellationToken cancelToken)

您正在使用已棄用的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 的應用程序中使用了這段代碼,它運行良好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM