.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遇到的问题,因为有事件监听。

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值