本文介绍了如何使用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令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 03:08