如何使用Microsoft Identity Platform身份验证在ASP.NET Core Web应用程序中获取JWT令牌?

How do I get hold of a JWT token in an ASP.NET Core Web App using Microsoft identity platform authentication?(如何使用Microsoft Identity Platform身份验证在ASP.NET Core Web应用程序中获取JWT令牌?)
本文介绍了如何使用Microsoft Identity Platform身份验证在ASP.NET Core Web应用程序中获取JWT令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用Visual Studio 2022和.Net 6创建了默认的ASP.NET Core Web App项目。

作为身份验证类型,我已选择Microsoft标识平台。

如何获取AzureAD作为OpenID Connect的一部分为我生成的JWT?

我已将Program.cs中的身份验证服务更改为使用选项SaveTokens,如下所示:

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(options =>
    {
        builder.Configuration.Bind("AzureAd", options);
        options.SaveTokens = true;
    });

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();
app.MapControllers();

app.Run();

我想访问JWT令牌,这样我就可以将它们传递给我们拥有的定制服务。我不想重新生成它们,我想要Microsoft已签名的令牌。

为了测试获取它们,我尝试了Microsoft.AspNetCore.Authentication扩展中的GetTokenAsync(在Index.cshtml中)

@page
@using Microsoft.AspNetCore.Authentication
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <p>Access Token: @await HttpContext.GetTokenAsync("OpenIdConnect","access_token")</p>
    <p>Refresh Token: @await HttpContext.GetTokenAsync("OpenIdConnect", "refresh_token")</p>
</div>

但是,唉--我得到的是空值。有什么主意吗?结果如下:

推荐答案

我不知道为什么原来的SaveToken方法不起作用,但有一种方法可以让它起作用:

它不完全一样,但得到了我需要的东西。挂钩到事件OnTokenValiated,然后将其显式保存在标识上,如下所示(在Program.cs中):

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(options =>
    {
        builder.Configuration.Bind("AzureAd", options);
        options.Events.OnTokenValidated = context =>
        {
            var accessToken = context.SecurityToken as JwtSecurityToken;
           

            if (accessToken != null)
            {
                var identity = context.Principal.Identity as ClaimsIdentity;
                if (identity != null)
                {
                    identity.AddClaim(new Claim("access_token", accessToken.RawData));
                }
            }

            return Task.FromResult(0);
        };

    });

然后从用户访问它。身份-以下仅用于测试(在Index.cshtml中):

<p>Access Token: @((User.Identity as ClaimsIdentity).Claims.Where( c => c.Type == "access_token").FirstOrDefault().Value)</p>

这篇关于如何使用Microsoft Identity Platform身份验证在ASP.NET Core Web应用程序中获取JWT令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)