直接使用对API的ApiKey或基本身份验证的IdentityServer4

如何解决直接使用对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,因为这是服务器到服务器的身份验证。 要实施,请按照以下步骤操作:

  1. 在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
            }
        }
  
  1. 在API项目https://www.nuget.org/packages/IdentityModel/上安装IdentityModel软件包

  2. 请求在标头上收到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;
}
  1. 检查response-IsError属性以确保请求成功

  2. 如果您需要在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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-