Reputation: 41
I am using Identity server 4 in my .NET 5.0 core API Application. i am getting successful token on local server https://localhost:[port]/connect/token and when i use the bearer token to access authorize method , i getting 401 error
I only have one application in Solution and APIs that [Authorize] is added
startup.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()
}
});
}
my identity server config file:
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"
}
}
};
}
}
appsetting file:
"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
},
According to @Michal's answer , i change AddIdentityServerAuthentication
to AddJwtBearer
and i getting 404 error but when i change AddAuthentication()
parameter of JwtBearerDefaults.AuthenticationScheme
to as follows, i getting other error
.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;
});
after this change, i getting this error:
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)
Upvotes: 4
Views: 2858
Reputation: 2061
You're using AddIdentityServerAuthentication
, which is deprecated. It may cause the problem. 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/
You can use AddJwtToken
instead and set up Authority
pointing to your app.
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.Authority = "http://localhost:41407";
o.TokenValidationParameters.ValidateAudience = false;
o.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
});
I used this chunk of code a couple of days before in my own app with IdentityServer4 and it worked fine.
Upvotes: 1