.net core .net core 3.1承载错误=“无效令牌”,错误描述=“受众“空”无效”
我有3个项目1-Angular SPA 2-Web API项目core 3.1,3-IdentityServer与core 3.1 但我有以下错误.net core .net core 3.1承载错误=“无效令牌”,错误描述=“受众“空”无效”,.net-core,jwt,asp.net-identity,identityserver4,.net Core,Jwt,Asp.net Identity,Identityserver4,我有3个项目1-Angular SPA 2-Web API项目core 3.1,3-IdentityServer与core 3.1 但我有以下错误 > www-authenticate: Bearer error="invalid_token", error_description="The audience 'empty' is invalid" 这是我的API启动 public void ConfigureServices(IServiceC
> www-authenticate: Bearer error="invalid_token", error_description="The audience 'empty' is invalid"
这是我的API启动
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SchemaRegistryConfig>(Configuration.GetSection("SchemaRegistryConfig"));
//identity server
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5002/";
options.RequireHttpsMetadata = false;
options.Audience = "Api";
});
IdentityModelEventSource.ShowPII = true;
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
services.AddMvc(config =>
{
config.Filters.Add(typeof(UnhandledExceptionFilter));
config.EnableEndpointRouting = false;
}).SetCompatibilityVersion(CompatibilityVersion.Latest);
services.AddServices(Configuration);
services.AddHealthChecksUI();
}
[Obsolete]
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowOrigin");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.UseMvc();
}
角度SPA oidc配置
export function configureAuth(oidcConfigService: OidcConfigService) {
return () =>
oidcConfigService.withConfig({
stsServer: 'https://localhost:5002',
redirectUrl: "http://localhost:4200/home",
postLogoutRedirectUri: window.location.origin,
clientId: '_client',
scope: 'openid profile email offline_access Api',
responseType: 'code',
silentRenew: true,
useRefreshToken: true
});
我的代币有效载荷是
我有3个控制器,我在每个控制器上添加了[授权]。
有人能帮我吗?我成功地生成了令牌,当我使用令牌调用webapi时,它会发出消息。但是里面没有观众。我也面临着同样的问题,而且?我的代币中缺少了Aud和Iss。我需要它,因为在我的Startup.cs文件中,我将它们设置为需要进行验证 在您的令牌字符串中,我没有看到Aud声明 请参见以下两个代码: Startup.cs中的ConfigureServices方法
我也面临着同样的问题,而且?我的代币中缺少了Aud和Iss。我需要它,因为在我的Startup.cs文件中,我将它们设置为需要进行验证 在您的令牌字符串中,我没有看到Aud声明 请参见以下两个代码: Startup.cs中的ConfigureServices方法
你必须设置一个听众。有帮助吗?@jps这对添加作用域没有帮助。你必须设置受众。有帮助吗?@jps这对添加的作用域没有帮助。帮助的应用与帮助的应用
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryApiScopes(Config.ApiScopes())
.AddInMemoryClients(Config.Clients)
.AddTestUsers(TestUsers.Users);
services.AddAuthentication();
services.AddCors(options => options.AddPolicy("AllowAll", p =>
p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()));
// not recommended for production - you need to store your key material somewhere secure
builder.AddDeveloperSigningCredential();
}
public void Configure(IApplicationBuilder app)
{
if (Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseCors("AllowAll");
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
export function configureAuth(oidcConfigService: OidcConfigService) {
return () =>
oidcConfigService.withConfig({
stsServer: 'https://localhost:5002',
redirectUrl: "http://localhost:4200/home",
postLogoutRedirectUri: window.location.origin,
clientId: '_client',
scope: 'openid profile email offline_access Api',
responseType: 'code',
silentRenew: true,
useRefreshToken: true
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,
--> ValidateAudience = true, <--
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),
ClockSkew = TimeSpan.Zero
};
});
private string GenerateToken(UserViewModel loginViewModel)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, loginViewModel.UserName),
new Claim("fullName", loginViewModel.FirstName + " " + loginViewModel.LastName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Aud, _configuration["Jwt:Audience"]),
new Claim(JwtRegisteredClaimNames.Iss, _configuration["Jwt:Issuer"])
};
var token = new JwtSecurityToken(
issuer: _configuration["Issuer"],
audience: _configuration["Audience"],
claims: claims,
expires: DateTime.Now.AddMonths(2),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}