如何不使用Microsoft.AspNetCore.Identity.UI配置OpenIddict对接AzureAd
第一步:调整身份认证配置
你当前用的AddMicrosoftIdentityWebApi是用于资源服务校验令牌的组件,不符合上游身份提供商(AzureAd)登录的场景,需要替换为web应用认证组件:
// 替换原有AddMicrosoftIdentityWebApi的代码 services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = "AzureAd"; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"), "AzureAd", CookieAuthenticationDefaults.AuthenticationScheme);
配置说明:
- 登录成功后AzureAd返回的身份信息会存在Cookie中,Scheme为
CookieAuthenticationDefaults.AuthenticationScheme - 触发登录时自动挑战AzureAd认证方案
- 你需要在AzureAd的应用注册中配置你的服务域名+/signin-oidc作为重定向URI,这个是AzureAd认证完成后回调你服务的地址,和OpenIddict客户端的回调地址完全独立,互不干扰,你的理解是正确的。
第二步:修改AuthorizeController逻辑
调整认证读取和挑战的方案即可:
[HttpGet("~/connect/authorize")] [HttpPost("~/connect/authorize")] [IgnoreAntiforgeryToken] public async Task<IActionResult> Authorize() { var request = HttpContext.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); // 读取AzureAd认证后写入Cookie的身份信息 var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); // 未登录则挑战AzureAd方案,跳转到AzureAd登录页 if (!result.Succeeded) { var authprops = new AuthenticationProperties { RedirectUri = Request.PathBase + Request.Path + QueryString.Create( Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList()) }; return Challenge( authenticationSchemes: "AzureAd", properties: authprops); } // 这里可以基于AzureAd返回的身份信息,查询你的自定义角色/权限体系,注入自定义声明 var claims = new List<Claim> { new Claim(OpenIddictConstants.Claims.Subject, result.Principal.FindFirstValue(ClaimTypes.NameIdentifier) ?? result.Principal.Identity.Name), // 你的自定义声明,设置Destinations为IdentityToken/AccessToken即可被带入对应令牌 new Claim(OpenIddictConstants.Claims.Role,"admin").SetDestinations(OpenIddictConstants.Destinations.IdentityToken), new Claim(OpenIddictConstants.Claims.Role,"gerbil wrangler").SetDestinations(OpenIddictConstants.Destinations.IdentityToken) }; var claimsIdentity = new ClaimsIdentity(claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); claimsPrincipal.SetScopes(request.GetScopes()); return SignIn(claimsPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); }
第三步:可选配置调整
如果需要自定义AzureAd的回调地址,不需要用默认的signin-oidc,可以在AddMicrosoftIdentityWebApp的配置项里修改CallbackPath参数,同步更新AzureAd应用注册里的重定向URI即可。
所有OpenIddict的原有配置不需要修改,保持现状即可。
内容的提问来源于stack exchange,提问作者Peter Wone
相关产品推荐
相关产品推荐

