You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 3.1下OAuth 2.0集成introspection的实现示例及步骤求助

.NET Core 3.1 OAuth 2.0 + Token Introspection 落地实现指南

前置依赖安装

  • 首先通过NuGet包管理器安装适配.NET Core 3.1的 IdentityModel.AspNetCore.OAuth2Introspection 包,推荐使用3.0.0版本,避免版本不兼容问题
  • 确保项目已引用 Microsoft.AspNetCore.Authentication 核心库,3.1版本默认已包含在ASP.NET Core框架中

注意:所有配置中的授权服务器参数(端点、ClientId、ClientSecret)需要和你对接的OAuth2授权服务器提供的信息完全一致,否则会出现introspection失败的问题

认证服务配置

1. ConfigureServices方法配置

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    
    // 配置OAuth2 Introspection认证
    services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
        .AddOAuth2Introspection(options =>
        {
            // 授权服务器的Introspection端点地址
            options.IntrospectionEndpoint = "你的授权服务器introspection接口地址";
            // 授权服务器颁发给当前API资源的客户端ID
            options.ClientId = "你的API资源ID";
            // 授权服务器颁发给当前API资源的客户端密钥
            options.ClientSecret = "你的API资源密钥";
            // 可选配置:开启缓存introspection结果,减少请求授权服务器的次数
            options.EnableCaching = true;
            // 缓存有效期,默认5分钟
            options.CacheDuration = TimeSpan.FromMinutes(5);
            // 可选配置:开启后将token保存到Claims中方便业务逻辑调用
            options.SaveToken = true;
        });

    // 可选配置:自定义授权策略,根据业务需要添加
    services.AddAuthorization(options =>
    {
        options.AddPolicy("ApiAccess", policy =>
        {
            policy.RequireAuthenticatedUser();
            // 可自定义添加Scope、角色、自定义声明等校验规则
            policy.RequireClaim("scope", "your_api_scope");
        });
    });
}

2. Configure方法中间件配置

注意严格按照以下顺序添加中间件,顺序错误会导致认证失效:

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

    app.UseRouting();

    // 先启用认证,再启用授权
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers()
            // 全局应用认证策略,也可以单独在Controller/Action上加[Authorize]特性替代
            .RequireAuthorization("ApiAccess");
    });
}

常见场景实现

  • 自定义校验逻辑

如果需要在introspection通过后,额外添加自定义权限校验、补充用户声明等逻辑,可以实现 IClaimsTransformation 接口,示例代码:

public class CustomClaimsTransformer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var identity = principal.Identity as ClaimsIdentity;
        if (identity != null && identity.IsAuthenticated)
        {
            // 补充自定义用户信息、权限校验等逻辑
            identity.AddClaim(new Claim("custom_permission", "edit"));
        }
        return Task.FromResult(principal);
    }
}

在ConfigureServices中注册服务即可生效:
services.AddTransient<IClaimsTransformation, CustomClaimsTransformer>();

  • 匿名访问配置

如果需要部分接口允许未登录访问,直接在对应Action/Controller上添加 [AllowAnonymous] 特性即可,不需要修改全局配置。

  • 自定义认证失败返回格式

如果需要修改默认的认证失败返回内容,可以重写事件回调,示例:

.AddOAuth2Introspection(options =>
{
    // 其他基础配置省略
    options.Events = new OAuth2IntrospectionEvents
    {
        OnAuthenticationFailed = context =>
        {
            context.NoResult();
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";
            return context.Response.WriteAsync("{\"code\":401,\"message\":\"访问令牌无效或已过期\"}");
        }
    };
})

本地测试方法

  • 先从对接的OAuth2授权服务器获取有效AccessToken
  • 发起接口请求时在Header中添加 Authorization: Bearer {AccessToken}
  • 无效/过期的Token会返回401状态码,有效Token可正常访问接口,且可在Controller中通过 User.Claims 获取introspection返回的所有用户信息

内容的提问来源于stack exchange,提问作者Muhammad Usama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 20:54:06