IdentityServer4 с .Net7.0. Разделение API в SSO с помощью ApiScopeC#

Место общения программистов C#
Ответить
Anonymous
 IdentityServer4 с .Net7.0. Разделение API в SSO с помощью ApiScope

Сообщение Anonymous »

У меня 5 клиентов сервера идентификации, мне нужно отделить авторизацию 1 клиента от остальных. После входа в ClientA переключаюсь на уже авторизованный ClientB, помогите решить.
Нужно, чтобы один IdentityServer работал как два?
мой IdentityResourceStore:

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

public class IdentityResourceStore : IResourceStore {
private readonly IScopeRepository _repository;
private readonly IMemoryCache _memoryCache;

public IdentityResourceStore(IScopeRepository repository, IMemoryCache memoryCache) {
_repository = repository;
_memoryCache = memoryCache;
}

public async Task FindIdentityResourcesByScopeNameAsync(
IEnumerable scopeNames) {
var resources = await GetAllResourcesAsync();
return resources.IdentityResources.Where(r => scopeNames.Contains(r.Name));
}

public async Task FindApiScopesByNameAsync(IEnumerable scopeNames) {
var resources = await GetAllResourcesAsync();
return resources.ApiScopes.Where(s => scopeNames.Contains(s.Name));
}

public async Task FindApiResourcesByScopeNameAsync(IEnumerable scopeNames) {
var resources = await GetAllResourcesAsync();
var apiResources = resources.ApiResources.ToList();
return apiResources.Where(x => x.Scopes.Any(y => scopeNames.Contains(y)));
}

public async Task FindApiResourcesByNameAsync(IEnumerable apiResourceNames) {
var resources = await GetAllResourcesAsync();
var apiResources = resources.ApiResources.ToList();
return apiResources.Where(x => apiResourceNames.Contains(x.Name));
}

public async Task GetAllResourcesAsync() {
var defaultResources = new List {
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email()
};
ApiScope[] apiScopes = { new ApiScope("ClientA"), new ApiScope("ClientB") };
var apiResources = new List();
if (_memoryCache.TryGetValue("clients_array", out IEnumerable clients_array)) {
foreach (var clientId in clients_array) {
if (!_memoryCache.TryGetValue(clientId, out FileClient client)) continue;

if (clientId == ClientIds.ClientB) {
var apiResource = new ApiResource(clientId) {
ApiSecrets = client.IdentitySeverClient.ClientSecrets,
Scopes = new [] { "ClientB" },
};
apiResources.Add(apiResource);
}
else
{
var apiResource = new ApiResource(clientId) {
ApiSecrets = client.IdentitySeverClient.ClientSecrets,
Scopes = new [] { "ClientA" },
};
apiResources.Add(apiResource);
}
}
}

return new IdentityServer4.Models.Resources(defaultResources, apiResources, apiScopes);
}
}
Одна из конечных точек аутентификации на моем сервере идентификации

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

   public async Task AuthByPhonePassword([FromBody] AuthLoginPasswordDto authUserByPhoneDto) {
var result = await _authService.AuthByPhonePassword(authUserByPhoneDto);

await HttpContext.SignInAsync(new IdentityServerUser(result.Value.UserId) {
DisplayName = result.Value.UserName,
AdditionalClaims = new Claim[] { new Claim(CustomJwtClaimTypes.UserType, result.Value.UserType) }
}, null);

return result.AsHttpResult();
}
Области клиента A: "scopes": "openid профиля сотрудника ClientA offline_access",
Области клиента B: "scopes": "openid Profile ClientB",
Я попытался разделить разные области действия. Пытался добавить Policy на стороне API, но такой подход оказался непригодным. Похоже, что мой IdentityServer должен указывать на неподходящую область действия.
Я заметил, что после изменения ресурсов мой токен JWT начал меняться; список 'audi' был правильным (без лишних клиентов), также был исправлен список областей в токене.

Подробнее здесь: https://stackoverflow.com/questions/787 ... y-apiscope
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

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