Сервис для обслуживания не принимает токен от IdentityServer ⇐ C#

Место общения программистов C#
Anonymous
Сервис для обслуживания не принимает токен от IdentityServer

Сообщение Anonymous »

Я изучаю asp.net и adentintyserver4
Я сделал сервер, который генерирует для меня токен в соответствии с учебником, я получаю его как от почтальона, так и от контроллера моего «клиента», но когда я пытаюсь сделать запрос на «бэкэнд», где требуется авторизация, я получаю ошибку 401, я не понимаю, что я ошибался < /p>
< /p> < /p> < /p>

Код: Выделить всё

public static class Configuration
{
public static IEnumerable ApiScopes => new List
{
new ApiScope("NotesWebAPI", "Web API")
};

public static IEnumerable IdentityResources =>
new List
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};

public static IEnumerable ApiResources =>
new List
{
new ApiResource("NotesWebAPI", "Web API", new []{ JwtClaimTypes.Name })
{
Scopes = { "NotesWebAPI" }
}
};

public static IEnumerable Clients =>
new List
{
new Client
{
ClientId = "client_id",
ClientSecrets = { new Secret("client_secret".ToSha256()) },

AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes =
{
"NotesWebAPI",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
}
},
};
}
< /code>
starttup IndetityServer < /p>
public class Startup
{
IConfiguration AppConfiguration { get; }
public Startup(IConfiguration config)
{
AppConfiguration = config;
}

public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity(config =>
{
config.Password.RequiredLength = 6;
config.Password.RequireDigit = false;
config.Password.RequireNonAlphanumeric = false;
config.Password.RequireUppercase = false;
config.Password.RequireLowercase = false;
})
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();

services.AddDbContext(options =>
options.UseSqlServer(
AppConfiguration.GetConnectionString("DefaultConnection")));

services.AddIdentityServer()
.AddAspNetIdentity()
.AddInMemoryApiResources(Configuration.ApiResources)
.AddInMemoryIdentityResources(Configuration.IdentityResources)
.AddInMemoryApiScopes(Configuration.ApiScopes)
.AddInMemoryClients(Configuration.Clients)
.AddDeveloperSigningCredential();

services.ConfigureApplicationCookie(config =>
{
config.Cookie.Name = "Notes.Identity.Cookie";
//config.LoginPath = "/Auth/Login";
//config.LogoutPath = "/Auth/Logout";
});

services.AddControllersWithViews();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "Styles")),
RequestPath = "/styles"
});

app.UseRouting();
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
< /code>
my "Backend" < /p>
private IConfiguration Configuration { get;  }

public Startup(IConfiguration config)
{
Configuration = config;
}

public void ConfigureServices(IServiceCollection services)
{

services.AddAutoMapper(config =>
{
config.AddProfile(new AssemblyMappingProfile(Assembly.GetExecutingAssembly()));
config.AddProfile(new AssemblyMappingProfile(typeof(INotesDbContext).Assembly));
});
services.AddApplication();
services.AddPersistence(Configuration);
services.AddControllers();
services.AddCors(config =>
{
config.AddPolicy("DefaultPolicy",
builder =>
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, config =>
{
config.TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.FromMinutes(1),
ValidateAudience = false
};

config.Authority = "https://localhost:5001";
config.Audience = "NotesWebAPI";
//config.Audience = "https://localhost:5001";
});
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCustomExceptionHandler();
app.UseRouting();
app.UseHttpsRedirection();

app.UseCors("DefaultPolicy");

app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
< /code>
"Client" Controller < /p>
[Route("[action]")]
public async Task GetNotes()
{
var authClient = _httpClientFactory.CreateClient();

var discoverDocument = await authClient.GetDiscoveryDocumentAsync("http://localhost:5000");

var tokenResponse = await authClient.RequestClientCredentialsTokenAsync(
new ClientCredentialsTokenRequest
{
Address = discoverDocument.TokenEndpoint,
ClientId = "client_id",
ClientSecret = "client_secret",
Scope = "NotesWebAPI",
});

var requestClient = _httpClientFactory.CreateClient();

requestClient.SetBearerToken(tokenResponse.AccessToken);

var responce = await requestClient.GetAsync("http://localhost:1321/api/note");

if (!responce.IsSuccessStatusCode)
{
ViewBag.Message = responce.StatusCode.ToString();
return View();
}

var message = await responce.Content.ReadAsStringAsync();
ViewBag.Message = message;
return View();
}
Обновлено: Если я отправляю запрос через почтальона, он пройдет, он не проходит только запрос «клиент»

Подробнее здесь: https://stackoverflow.com/questions/748 ... tityserver

Вернуться в «C#»