Identity Server 4 Claims empty on API

后端 未结 2 943
梦毁少年i
梦毁少年i 2020-12-21 07:51

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

相关标签:
2条回答
  • 2020-12-21 08:32

    I have found my Solution for this problem. I was missing couple of things on my code:

    1. There was the Duplicate references to IdentityServer4.AccessTokenValidation.
    2. 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.

    0 讨论(0)
  • 2020-12-21 08:52

    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

    0 讨论(0)
提交回复
热议问题