I have been trying to Integrate Identity Server 4 with SPA application. I am able to Authorize the Application in API but after the authorization the User.Claims
I have found my Solution for this problem. I was missing couple of things on my code:
IdentityServer4.AccessTokenValidation
.I was missing the DefaultChallengeScheme
on my API ConfigureServices
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "oidc";
})
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://localhost:44305";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
So my Configure Service became like below:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore().AddAuthorization().AddJsonFormatters();
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<MyContext>(o => o.UseSqlServer(connectionString));
services.AddIdentity<User, IdentityRole<Guid>>().AddEntityFrameworkStores<MyContext>().AddDefaultTokenProviders();
services.AddAuthentication(
options =>
{
options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "oidc";
})
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://localhost:44305";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.WithOrigins("http://localhost:8080")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
services.AddScoped<IContractService, ContractService>();
services.AddScoped<IClientService, ClientService>();
services.AddAutoMapper(mapperConfig => mapperConfig.AddProfiles(GetType().Assembly));
}
Changing above two things solved my problem for missing claims and Authorized
without the Bearer Token.
Try this
var user = User.Claims.First(claim => claim.Type=="Name").Value();
I am not an expert , but I think this is how you should work with Claims instead of the older versions of Asp.Net where placing User sufficed