IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发测试 -> .netcore webapi AzureAD 认证集成swagger -> 正文阅读

[开发测试].netcore webapi AzureAD 认证集成swagger

startup里

public void ConfigureServices(IServiceCollection services)
{

    try
    {

        string stsDiscoveryEndpoint = Configuration["AzureAd:Instance"] + "/common/v2.0/.well-known/openid-configuration";
        IConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
        OpenIdConnectConfiguration openidconfig = configManager.GetConfigurationAsync(CancellationToken.None).Result;

        services.AddAuthentication(sharedoptions =>
        {
            sharedoptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
           .AddJwtBearer(options =>
           {
               options.Authority = Configuration["AzureAd:Instance"] + "/" + Configuration["AzureAd:TenantId"];
               options.TokenValidationParameters = new TokenValidationParameters
               {
                   ValidAudience = Configuration["AzureAd:ClientId"],
                   ValidIssuer = Configuration["AzureAd:Instance"] + Configuration["AzureAd:TenantId"] + "/v2.0",
                   IssuerSigningKeys = openidconfig.SigningKeys,
                   ValidateLifetime = true
               };
               options.Events = new JwtBearerEvents()
               {
                   //收到请求会进来
                   OnMessageReceived = async c =>
                   {
                       var a = c.Request.Headers;
                       await Task.FromResult(0);
                   },
                   //token合法会进来
                   OnTokenValidated = async c =>
                   {
                       var a = c.Request.Headers;
                       await Task.FromResult(0);
                   },
                   //token过期会进来
                   OnAuthenticationFailed = async c =>
                   {

                       var ex1 = c.Exception.Message;
                       var ex2 = c.Exception.StackTrace;

                       //Log.Error("JWT Auth failed: " + c.Exception.Message + "\n" + c.Exception.StackTrace);
                       await Task.FromResult(0);
                   }
               };
           });




        //services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        //.AddMicrosoftIdentityWebApi(Configuration, "AzureAd");

        //;

        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "webapi", Version = "v1" });


            c.DocInclusionPredicate((docName, description) => true);
            c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可,注意两者之间有空格",
                Name = "Authorization",//jwt默认的参数名称
                In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                Type = SecuritySchemeType.ApiKey
            });
            //认证方式,此方式为全局添加
            c.AddSecurityRequirement(new OpenApiSecurityRequirement {

            {
                    new OpenApiSecurityScheme {
                        Reference = new OpenApiReference() {
                            Id = "Bearer",
                            Type = ReferenceType.SecurityScheme
                        }
            }, Array.Empty<string>() }

            });

        });

    }
    catch (Exception ex)
    {
        var ex1 = ex.ToString();
        throw ex;
    }
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	//这里注意launchSettings.json配置如果启动方式不是IIS Express需要把对应的环境变量调整一下,改成"ASPNETCORE_ENVIRONMENT": "Development",swagger才会出现在项目启动
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "webapi v1"));
    }
    

    app.UseHttpsRedirection();

    app.UseRouting();

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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

launchSettings.json

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:62974",
      "sslPort": 44393
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "webapi": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:52484/;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

appsetting.json

"AzureAd": {
  //"IsEnabled": "true",
  "Instance": "https://login.microsoftonline.com/",
  "Host": "https://localhost:52484/",
  "CallbackPath": "signin-oidc",
  "Domain": "...",
  "ClientId": "...",
  "TenantId": "...",
  "ClientSecret": "..."
},

效果图:

controller测试方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;

namespace webapi.Controllers
{
    //[Authorize(Roles = "HR")]
    //[Authorize(Roles = "Admin_hr")]
    //[Authorize(Roles = "Hello World!")]
    [ApiController]
    //[Route("[controller]")]
    [Route("api/[controller]/[action]")]
    //[ApiController]
    [Authorize]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ITokenAcquisition tokenAcquisition;

        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        // The Web API will only accept tokens 1) for users, and 2) having the "access_as_user" scope for this API

        //static readonly string[] scopeRequiredByApi = new string[] { "access_as_user" };

        static readonly string[] scopeRequiredByApi = new string[] { "user_impersonation" };



        public WeatherForecastController(ILogger<WeatherForecastController> logger
            )
        {
            _logger = logger;
            //this.tokenAcquisition = tokenAcquisition;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            //HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);

            //string[] scopes = new string[] { "user.read" };
            //string accessToken = tokenAcquisition.GetAccessTokenForUserAsync(scopes).ToString();

            var userId = User.FindFirst(ClaimTypes.Role).Value;
            var userName = User.FindFirst("enterpriseID").Value;
            var userName1 = User.FindAll("enterpriseID").FirstOrDefault().Value;
            var rolelist = User.FindAll(ClaimTypes.Role);
            HttpContext.Response.WriteAsync($"测试结果  {userId}---{userName}--{rolelist}");


            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

?返回结果:

引用包:

此一套虽然比官方文档麻烦些,但能最快速搭建一个架构并且快速调试出token遇到的问题,因为有事件监听。

仅供学习参考,如有侵权联系我删除?

  开发测试 最新文章
pytest系列——allure之生成测试报告(Wind
某大厂软件测试岗一面笔试题+二面问答题面试
iperf 学习笔记
关于Python中使用selenium八大定位方法
【软件测试】为什么提升不了?8年测试总结再
软件测试复习
PHP笔记-Smarty模板引擎的使用
C++Test使用入门
【Java】单元测试
Net core 3.x 获取客户端地址
上一篇文章      下一篇文章      查看所有文章
加:2022-05-05 11:49:55  更:2022-05-05 11:51:34 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 16:19:25-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码