微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在ASP.NET Core 3.1中使用Azure进行多重身份验证

如何解决在ASP.NET Core 3.1中使用Azure进行多重身份验证

我正在尝试为ASP.NET Core 3.1中的Web应用程序创建多重身份验证方案。

我正在使用现成的解决方案在单个租户中连接到Azure Active Directory。

我在应用程序内部有2个“模式”。一个用于前端,另一个用于API。所有API路由均以/api开头。

在网络浏览器中,应用程序要求您先登录,然后再进行操作,同样适用于api。

我需要专门为该API创建第二个身份验证方案,以便可以从外部客户(如Postman)调用它。

我要使用的方案是Azure Active Directory承载令牌。我知道可以这样:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options => Configuration.Bind("AzureAd",options));

因此在邮递员中按原样要求时,我将Microsoft登录屏幕显示为HTML。 Postman Request

我想在Postman的授权标头请求中传递不记名令牌,并从API获取结果。

这是我的StartUp.cs文件

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options =>
            {
                Configuration.Bind("AzureAd",options);
            });

        services.AddDbContext<Context>(options => 
            options.UsesqlServer(Configuration.GetConnectionString("Azure")));

        services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme,options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                // Instead of using the default validation (validating against a single issuer value,as we do in
                // line of business apps),we inject our own multitenant validation logic
                ValidateIssuer = false,// If the app is meant to be accessed by entire organizations,add your issuer validation logic here.
                //IssuerValidator = (issuer,securityToken,validationParameters) => {
                //    if (myIssuerValidationLogic(issuer)) return issuer;
                //}
            };
            options.Authority = options.Authority + "/v2.0/";

            options.TokenValidationParameters.ValidateIssuer = false;

            options.Events = new OpenIdConnectEvents
            {
                OnTicketReceived = context =>
                {
                    // If your authentication logic is based on users then add your logic here
                    return Task.CompletedTask;
                },OnAuthenticationFailed = context =>
                {
                    context.Response.Redirect("/Error");
                    context.HandleResponse(); // Suppress the exception
                    return Task.CompletedTask;
                },OnTokenValidated = context =>
                {
                    // Access Token
                    var accesstoken = context.SecurityToken.RawData;
                    Console.WriteLine($"Token Authentication: " + accesstoken);

                    return Task.CompletedTask;
                }
                // If your application needs to authenticate single users,add your user validation below.
                //OnTokenValidated = context =>
                //{
                //    return myUserValidationLogic(context.Ticket.Principal);
                //}
            };

        });

        services.AddControllersWithViews(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new Authorizefilter(policy));
        });
        services.AddRazorPages().AddJsonoptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/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.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });
    }
}

任何帮助将不胜感激。谢谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。