首页 > 编程语言 >How Do ASP.NET Core Services Validate JWT Signature Signed by AAD?

How Do ASP.NET Core Services Validate JWT Signature Signed by AAD?

时间:2023-06-16 16:35:49浏览次数:71  
标签:AAD code Core JWT source ASP key signature options

Table of contents

  1. Background
  2. Configuration
  3. Handle Authentication
  4. Validate Token
  5. Summary

Background

If we need to use JWT Bearer tokens issued by AAD (to either a user or service principal) for authentication, usually we can add below code to ConfigureServices in Startup.cs.

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = $"https://login.microsoftonline.com/{tenantId}";
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = "...",
            ValidAudience = "..."
        };
    });

Then, by adding [Authorize] attribute for the Controller class, we get our APIs protected by AAD authentication. Authorization is also possible by some additional configurations.

It works without the need to provide any one of IssuerSigningKey* properties in TokenValidationParameters. It is common for us to ask below questions:

  • Is JWT signature validated after all?
  • How is JWT signature validated by ASP.NET Core?
  • Do I need to provide any signing key of certificate with public key to validate JWT signatures?
  • Does my service need to call some REST API provided by AAD to validate the signature on each request?

I try to answer these questions below, illustrated by ASP.NET Core and AAD Identity Model Extensions for .NET source code. If you want short answers to the questions, just skip to Summary section.

[!TIP] The source code links below will be out of date soon when new versions come. Please help me update them by sending pull requests. Thank you!

Configuration

As the ConfigureServices sample code in Background section shows, AddJwtBearer during configuration. In this extension method,

public static AuthenticationBuilder AddJwtBearer<TService>(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<JwtBearerOptions, TService> configureOptions) where TService : class
{
    builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<JwtBearerOptions>, JwtBearerPostConfigureOptions>());
    return builder.AddScheme<JwtBearerOptions, JwtBearerHandler, TService>(authenticationScheme, displayName, configureOptions);
}

builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<JwtBearerOptions>, JwtBearerPostConfigureOptions>()); is called to register a JwtBearerPostConfigureOptionsJwtBearerPostConfigureOptions has a PostConfigure() method (see source code). JwtBearerPostConfigureOptions.PostConfigure() is called when the first request comes, within AuthenticationHandler<JwtBearerOptions>.InitializeAsync() method (AuthenticationHandler<JwtBearerOptions> is the base class of JwtBearerHandler) -> … -> OptionsFactory.Create() (see source code).

In JwtBearerPostConfigureOptions.PostConfigure(), it sets the JwtBearerOptions.ConfigurationManager property. options.MetadataAddress is set based on options.Authority. For example, if options.Authority is https://login.microsoftonline.com/<tenandId>, then options.MetadataAddress is set to https://login.microsoftonline.com/<tenandId>/.well-known/openid-configurationIn this URL, we can find signing keys at https://login.microsoftonline.com/common/discovery/keys. options.MetadataAddress is passed to the ConfigurationManager’s constructor.

Handle Authentication

When each request comes, JwtBearerHandler.HandleAuthenticateAsync() is called to do authentication (see source code). If it is called for the first time, it will retrieve and cache a configuration by calling Options.ConfigurationManager.GetConfigurationAsync(). Then the TokenValidationParameters.IssuerSigningKeys is set to _configuration.SigningKeys (see source code). That’s why we don’t need to provide signing key ourselves in Startup.ConfigureServices().

Then it calls validator.ValidateToken() for each validator in Options.SecurityTokenValidators. There is only one validator in Options.SecurityTokenValidators - JwtSecurityTokenHandler.

Validate Token

In JwtSecurityTokenHandler.ValidateToken() -> JwtSecurityTokenHandler.ValidateSignature() (see source code), if TokenValidationParameters.IssuerSigningKeyResolver is null, ResolveIssuerSigningKey() and then JwtTokenUtilities.FindKeyMatch() will be called to find the matched key based on kid (key ID) and x5t (X.509 certificate SHA-1 thumbprint) in JWT header among the signing keys retrieved via MetadataAddress. Then the matched key will be used to validate JWT signature, with the help of the token itself, signatureheader.Alg and crypto provider.

Summary

Now it is clear that

  • JWT signature is validated without providing any key or certification in our service’s source code.
  • JWT signing key is retrieved from the well-known URL https://login.microsoftonline.com/common/discovery/keys, based on JwtBearerOptions.Authority property.
  • The signing key is cached in the JwtBearerHandler singleton instance, and so our ASP.NET Core service only needs to retrieve it once throughout its lifecycle.

 

转 https://zhiliaxu.github.io/how-do-aspnet-core-services-validate-jwt-signature-signed-by-aad.html

标签:AAD,code,Core,JWT,source,ASP,key,signature,options
From: https://www.cnblogs.com/wl-blog/p/17485882.html

相关文章

  • .net core 跨域访问
    varbuilder=WebApplication.CreateBuilder(args);builder.Services.AddCors(options=>{   //这定义了一个名为``default``的CORS策略   options.AddPolicy("default",policy=>    {       policy.AllowAnyOrigin()   ......
  • asp.net WebUploader 分块上传
    ​IE的自带下载功能中没有断点续传功能,要实现断点续传功能,需要用到HTTP协议中鲜为人知的几个响应头和请求头。 一. 两个必要响应头Accept-Ranges、ETag        客户端每次提交下载请求时,服务端都要添加这两个响应头,以保证客户端和服务端将此下载识别为可以断点续传......
  • .net core 实现简单爬虫—抓取博文列表
    概述HttpCode.Core源自于HttpCode,不同的是HttpCode.Core是基于.netstandard2.0实现的,移除了HttpCode与windows相耦合的api,且修改了异步实现,其余特性完全与HttpCode相同详细一、介绍一个Http请求框架HttpCode.CoreHttpCode.Core 源自于HttpCode(传送门),不同的是H......
  • 全面的ASP.NET Core Blazor简介和快速入门
    思维导航前言Blazor是什么?Blazor的优势和特点Blazor的劣势Blazor支持的平台Blazor三种托管模型及其各自特点如何选择要使用的托管模型?Razor语法简述新建ZeroBlazor空白解决方案使用VS2022快速创建BlazorServer应用使用VS2022快速创建BlazorWebAssembly应用课外......
  • TrueNAS CORE 13.0-U5.1 TrueNas存储平台 安装部署设置
    Truenas官网地址:https://www.truenas.com/下载TrueNASCORE13.0-U5.1服务器配置要求:CPU四核心内存8G硬盘按需求一、安装:与FREENAS一样(忽略)二、开始配置配置网卡信息说明开始配置网卡信息即可,因此我们选择第一项:三、浏览器访问TrueNas我们可以Https访问也可http访问......
  • 全面的ASP.NET Core Blazor简介和快速入门
    前言 因为咱们的MongoDB入门到实战教程Web端准备使用Blazor来作为前端展示UI,本篇文章主要是介绍Blazor是一个怎样的WebUI框架,其优势和特点在哪?并带你快速入门上手ASP.NETCoreBlazor(当然这个前提是你要有一定的C#编程基础的情况,假如你完全没有接触过C#的话建议你先从基本......
  • C#.NET CORE .NET6 RSA 私钥签名 公钥验签(验证签名) ver:20230614
    C#.NETCORE.NET6RSA私钥签名公钥验签(验证签名)ver:20230614 环境说明:.NETCORE版本:.NET6。 .NETCORE对于RSA的支持:1..NET6中内置了对PKCS1,PKCS82种私钥格式的支持。2.私钥字符串要去除"-----BEGINRSAPRIVATEKEY-----"、"-----ENDRSAPRIVATEKEY---......
  • ASP.NET Core 6框架揭秘实例演示[38]:两种不同的限流策略
    承载ASP.NET应用的服务器资源总是有限的,短时间内涌入过多的请求可能会瞬间耗尽可用资源并导致宕机。为了解决这个问题,我们需要在服务端设置一个阀门将并发处理的请求数量限制在一个可控的范围,即使会导致请求的延迟响应,在极端的情况会还不得不放弃一些请求。ASP.NET应用的流量限制......
  • 【原】iOSCoreAnimation动画系列教程(一):CABasicAnimation【包会】
    【原】iOSCoreAnimation动画系列教程(一):CABasicAnimation【包会】 在iOS中,图形可分为以下几个层次: 越上层,封装程度越高,动画实现越简洁越简单,但是自由度越低;反之亦然。本文着重介绍CoreAnimation层的基本动画实现方案。在iOS中,展示动画可以类比于显示生活中的“拍电影”。拍电影有......
  • asp中一个函数调用返回多参数
    asp中一个函数调用返回多个参数ByVal是传递值源数据不会被修改,你可以把这个值当作自己的局部变量来使用;ByRef是传递地址,源数据可能被修改,你对这个变量的操作将对你传入的那个变量产生影响,就像指针的感觉最近看很多成熟的cms系统中就用ByVal先看下面的例子文件名称:ByVal.......