如何解决直接使用对API的ApiKey或基本身份验证的IdentityServer4
我正在使用IdentityServer4让我的客户登录并从JavaScript访问网页和api,并且运行良好。但是,有一个新的要求,而不是使用用户名和密码从身份服务器获取访问令牌,然后使用该令牌通过Bearer身份验证来访问api ...我需要直接使用“基本”调用api身份验证标头和api将与身份服务器确认身份。类似于下面用于访问ZenDesk API的代码...
using (var client = new HttpClient())
{
var username = _configuration["ZenDesk:username"];
var password = _configuration["ZenDesk:password"];
var token = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",token);
var response = client.PostAsync("https://...
有关如何实现此目标的任何帮助? IdentityServer4中是否内置任何可以采用这种方法的内容?我正在将.Net Core 3.1用于api服务器和身份服务器。
另一种(看似常见的)方法是为每个用户生成一个api密钥,然后允许用户像这样调用api ...
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(URL_HOST_API);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("ApiKey","123456456123456789");
…
}
有想法吗?
解决方法
您可以实现OAuth password grant,因为这是服务器到服务器的身份验证。 要实施,请按照以下步骤操作:
- 在IdentityServer上为您的API项目注册一个客户端,这是一个示例
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "resourceownerclient",ClientSecrets= new List<Secret> { new Secret("secret".Sha256()) },AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,AccessTokenType = AccessTokenType.Jwt,AccessTokenLifetime = 120,//86400,IdentityTokenLifetime = 120,UpdateAccessTokenClaimsOnRefresh = true,SlidingRefreshTokenLifetime = 30,AllowOfflineAccess = true,RefreshTokenExpiration = TokenExpiration.Absolute,RefreshTokenUsage = TokenUsage.OneTimeOnly,AlwaysSendClientClaims = true,Enabled = true,AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile,IdentityServerConstants.StandardScopes.Email,IdentityServerConstants.StandardScopes.OfflineAccess
}
}
-
在API项目https://www.nuget.org/packages/IdentityModel/上安装
IdentityModel
软件包 -
请求在标头上收到token on API using username/password,如下所示:
private static async Task<TokenResponse> RequestTokenAsync(string user,string password)
{
var _httpClient = new HttpClient();
var _disco = await HttpClientDiscoveryExtensions.GetDiscoveryDocumentAsync(
_httpClient,_stsUrl);
var response = await _httpClient.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = _disco.TokenEndpoint,ClientId = "resourceownerclient",ClientSecret = "secret",Scope = "email openid offline_access",UserName = user,Password = password
});
return response;
}
-
检查
response
-IsError
属性以确保请求成功 -
如果您需要在IdentityServer上自定义任何内容以进行密码授予,则需要实现
IResourceOwnerPasswordValidator
,并进一步了解here
@nahidf有一个很好的方法,我只是补充说,您还可以使用自定义的“资源所有者密码”验证器。它使您可以像这样实现自己的密码验证器
[edit]:这是为了您不必使用身份模型
public class ApiResourceOwnerPasswordValidation : IResourceOwnerPasswordValidator
{
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
var user = await _dbContext.Users.FirstOrDefaultAsync(a =>
(a.UserName == context.UserName || a.Email.ToLower().Trim() == context.UserName.ToLower().Trim())
&& context.Password.VerifyHashedPassword(a.Password));
if (user != null)
{
context.Result = new GrantValidationResult(
subject: user.Id.ToString(),authenticationMethod: "custom",claims: AssambleClaims(user)
);
user.LoggedIn = DateTime.UtcNow;
await _dbContext.CommitAsync();
}
else
{
context.Result = new GrantValidationResult(
TokenRequestErrors.InvalidGrant,"Invalid credentials");
}
}
}
,
事实证明IdentityServer4没有内置对ApiKeys的支持...但是.Net Core 3.1具有IAuthorizationHandler,它允许您滚动自己对ApiKeys的授权并将其通过依赖注入插入到流中。
我的方式是...拥有一个ApiKey和一个ApiKeySecret。这样一来,UserId根本就不会暴露。我在IdentityServer4(服务器C)上有一个名为ApiKey的数据库表,其中包含字段(ApiKeyId,UserId,ApiKey和ApiKeySecret)... ApiKeySecret是一种单向哈希就像密码一样。
我在IdentityServer4项目(服务器C)中添加了一个ApiKeyController ...这将允许ApiRequest验证ApiKey。
所以...遵循流程:
服务器A:Third.Party .Net Core 3.1 Web服务器
服务器B:MyApiServer .Net Core 3.1 Web服务器
服务器C:MyIdentityerServer4 .Net Core 3.1 IndentityServer4
基于对服务器A的请求(可能来自浏览器)。
然后,服务器A使用标头中的ApiKey和ApiKeySecret调用我的API(服务器B):
using (var client = new HttpClient())
{
var url = _configuration["MyApiUrl"] + "/WeatherForecast";
var apiKey = _configuration["MyApiKey"];
var apiKeySecret = _configuration["MyApiKeySecret"];
client.DefaultRequestHeaders.Add("x-api-key",apiKey);
client.DefaultRequestHeaders.Add("secret-api-key",apiKeySecret);
var response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
var contents = response.Content.ReadAsStringAsync().Result;
return contents;
}
return "StatusCode = " + response.StatusCode;
}
在我的API服务器(服务器B)上,我添加了以下类,如果为URL设置了[Authorize]类别,则将通过在IdentityServer4(服务器C)上调用ApiKeyController来验证标头中的ApiKeys,并且将返回值(UserId)放在HttpContext.Items集合上。
基本上,系统已经为(我相信)services.AddAuthentication(“ Bearer”)定义了一个IAuthorizationHandler ...因此,当添加第二个(或多个)...时,如果返回一个成功,则将分别调用它们。将会有更多电话...如果它们全部失败,则[授权]将失败。
public class ApiKeyAuthorizationHandler : IAuthorizationHandler
{
private readonly ILogger<ApiKeyAuthorizationHandler> _logger;
private readonly IConfiguration _configuration;
private readonly IHttpContextAccessor _httpContextAccessor;
public ApiKeyAuthorizationHandler(
ILogger<ApiKeyAuthorizationHandler> logger,IConfiguration configuration,IHttpContextAccessor httpContextAccessor
)
{
_logger = logger;
_configuration = configuration;
_httpContextAccessor = httpContextAccessor;
}
public Task HandleAsync(AuthorizationHandlerContext context)
{
try
{
string apiKey = _httpContextAccessor.HttpContext.Request.Headers["x-api-key"].FirstOrDefault();
string apiKeySecret = _httpContextAccessor.HttpContext.Request.Headers["secret-api-key"].FirstOrDefault();
if (apiKey != null && apiKeySecret != null)
{
if (Authorize(apiKey,apiKeySecret))
SetSucceeded(context);
}
return Task.CompletedTask;
}
catch (Exception ex)
{
_logger.LogError(ex,"HandleAsync");
return Task.CompletedTask;
}
}
public class ValidateResponse
{
public string UserId { get; set; }
}
private bool Authorize(string apiKey,string apiKeySecret)
{
try
{
using (var client = new HttpClient())
{
var url = _configuration["AuthorizationServerUrl"] + "/api/ApiKey/Validate";
var json = JsonConvert.SerializeObject(new
{
clientId = "serverb-api",// different ApiKeys for different clients
apiKey = apiKey,apiKeySecret = apiKeySecret
});
var response = client.PostAsync(url,new StringContent(json,Encoding.UTF8,"application/json")).Result;
if (response.IsSuccessStatusCode)
{
var contents = response.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<ValidateResponse>(contents);
_httpContextAccessor.HttpContext.Items.Add("UserId",result.UserId);
}
return response.IsSuccessStatusCode;
}
}
catch (Exception ex)
{
_logger.LogError(ex,"Authorize");
return false;
}
}
private void SetSucceeded(AuthorizationHandlerContext context)
{
var pendingRequirements = context.PendingRequirements.ToList();
foreach (var requirement in pendingRequirements)
{
context.Succeed(requirement);
}
}
}
我还需要在服务器B的Startup.cs中添加以下内容:
services.AddSingleton<IAuthorizationHandler,ApiKeyAuthorizationHandler>();
为了完整起见,我在IdentityServer4(服务器C)上的代码:
ApiKeyController.cs
using System;
using MyIdentityServer.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace MyIdentityServer
{
[Route("api/[controller]")]
[ApiController]
public class ApiKeyController : ControllerBase
{
private readonly ILogger<ApiKeyController> _logger;
private readonly IApiKeyService _apiKeyService;
public ApiKeyController(
IApiKeyService apiKeyService,ILogger<ApiKeyController> logger
)
{
_apiKeyService = apiKeyService;
_logger = logger;
}
public class ValidateApiKeyRequest
{
public string ClientId { get; set; }
public string ApiKey { get; set; }
public string ApiKeySecret { get; set; }
}
[HttpPost("Validate")]
[AllowAnonymous]
[Consumes("application/json")]
public IActionResult PostBody([FromBody] ValidateApiKeyRequest request)
{
try
{
(var clientId,var userId) = _apiKeyService.Verify(request.ApiKey,request.ApiKeySecret);
if (request.ClientId == clientId && userId != null)
return Ok(new { UserId = userId });
// return new JsonResult(new { UserId = userId }); // maybe also return claims for client / user
return Unauthorized();
}
catch (Exception ex)
{
_logger.LogError(ex,"HandleValidateApiKey apiKey={request.ApiKey} apiKeySecret={request.ApiKeySecret}");
return Unauthorized();
}
}
public class GenerateApiKeyRequest
{
public string ClientId { get; set; }
public string UserId { get; set; }
}
[HttpPost("Generate")]
[AllowAnonymous]
public IActionResult Generate(GenerateApiKeyRequest request)
{
// generate and store in database
(var apiKey,var apiKeySecret) = _apiKeyService.Generate(request.ClientId,request.UserId);
return new JsonResult(new { ApiKey = apiKey,ApiKeySecret = apiKeySecret });
}
}
}
ApiKeyService.cs
using Arch.EntityFrameworkCore.UnitOfWork;
using EQIdentityServer.Data.Models;
using System;
using System.Security.Cryptography;
public namespace MyIndentityServer4.Services
public interface IApiKeyService
{
(string,string) Verify(string apiKey,string apiKeySecret);
(string,string) Generate(string clientId,string userId);
}
public class ApiKeyService : IApiKeyService
{
IUnitOfWork _unitOfWork;
public ApiKeyService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public (string,string apiKeySecret)
{
var repoApiKey = _unitOfWork.GetRepository<ClientUserApiKey>();
var item = repoApiKey.GetFirstOrDefault(predicate: p => p.ApiKey == apiKey);
if (item == null)
return (null,null);
if (!OneWayHash.Verify(item.ApiKeySecretHash,apiKeySecret))
return (null,null);
return (item?.ClientId,item?.UserId);
}
public (string,string userId)
{
var repoApiKey = _unitOfWork.GetRepository<ClientUserApiKey>();
string apiKey = null;
string apiKeySecret = null;
string apiKeySecretHash = null;
var key = new byte[30];
using (var generator = RandomNumberGenerator.Create())
generator.GetBytes(key);
apiKeySecret = Convert.ToBase64String(key);
apiKeySecretHash = OneWayHash.Hash(apiKeySecret);
var item = repoApiKey.GetFirstOrDefault(
predicate: p => p.ClientId == clientId && p.UserId == userId
);
if (item != null)
{
// regenerate only secret for existing clientId/userId
apiKey = item.ApiKey; // item.ApiKey = apiKey; // keep this the same,or you could have multiple for a clientId if you want
item.ApiKeySecretHash = apiKeySecretHash;
repoApiKey.Update(item);
}
else
{
// new for user
key = new byte[30];
while (true)
{
using (var generator = RandomNumberGenerator.Create())
generator.GetBytes(key);
apiKey = Convert.ToBase64String(key);
var existing = repoApiKey.GetFirstOrDefault(
predicate: p => p.ApiKey == apiKey
);
if (existing == null)
break;
}
item = new ClientUserApiKey() { ClientId = clientId,UserId = userId,ApiKey = apiKey,ApiKeySecretHash = apiKeySecretHash };
repoApiKey.Insert(item);
}
_unitOfWork.SaveChanges();
return (apiKey,apiKeySecret);
}
}
我的模特:
public class ClientUserApiKey
{
public long ClientUserApiKeyId { get; set; }
[IndexColumn("IX_ApiKey_ClientIdUserId",0)]
public string ClientId { get; set; }
[IndexColumn("IX_ApiKey_ClientIdUserId",1)]
public string UserId { get; set; }
[IndexColumn]
public string ApiKey { get; set; }
[StringLength(128)]
public string ApiKeySecretHash { get; set; }
}
然后,我的WeatherForecastController可以通过以下两种方式之一获取登录用户:通过Bearer access_token或我的ApiKeys:
string userId = null;
if (User?.Identity.IsAuthenticated == true)
userId = User?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier).Value;
else
userId = this.HttpContext.Items["UserId"]?.ToString(); // this comes from ApiKey validation
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。