[英]ASP NET API - Authenticate users using Azure AD SAML Protocol without open Microsoft Login Page
[英]Redirect user to Microsoft Azure AD Login Page from ASP .NET Core API manually
我们有一个多租户应用程序,我们在其中存储每个租户的 AzureAD 详细信息。 我们不需要一启动就设置Azure AD认证。 因此,在一些操作之后,我们从数据库中获取了这些详细信息,我们需要为每个租户动态配置 Microsoft Azure AD 登录页面。
我们不会在appsettings.json中存储任何租户的广告详细信息
所以场景是这样的。
[HttpGet]
public async Task<IActionResult> GetUsers()
{
// Challenge user to log in using Microsoft AzureAD Login
// If passed the challenge, the user will be able to receive the users
var users = new List<string>{ "Mike, Jhon"};
return Ok(users);
}
React js 应用程序将请求从我们的 API 获取一些东西,如果租户用户未被授权,我们会将用户重定向到他们所属的租户登录页面。
有可能吗? 我研究了很多。 我会说我经历了每一个 Azure AD 登录页面相关的问题。 但是没有找到任何结果。
如果您有任何想法或实践,请温和并解释实现此目标的方法。
谢谢
我也尝试以这种方式挑战用户,但没有像我预期的那样工作。
var response = await new HttpClient().GetAsync(@"https://login.microsoftonline.com/xxx43de-b3fb-efdea0768eb7/oauth2/v2.0/authorize?
client_id=xxxxx-efdea0768eb7&
response_type=id_token&
redirect_uri=https://localhost:7008/signin-oidc&
scope=openid&
response_mode=form_post&
state=12345&
nonce=678910");
我也尝试过这种方式,但此请求需要 App Bootstrap Azure AD 配置
return Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);
我试图检查我的环境中的场景:
在我的 API 中,我给出了 appsettings.json,包括秘密。
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "xxxx.onmicrosoft.com",
"ClientId": "xxx",
"TenantId": "xxx-f3a0cxxb0",
"ClientSecret": "xxxxx",
"ClientCertificates": [
],
"CallbackPath": "/signin-oidc"
},
"DownstreamApi": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "https://graph.microsoft.com/.default"
},
上面我们只有在应用注册完成后才获取,以便添加 azure 广告认证。
所以当我尝试访问该应用程序时,我可以在浏览器中看到授权 URL:
在那里你会看到只有clientId
暴露给试图进行身份验证的用户,但是客户端密码只从后端服务器获取,并没有在 web api 中暴露(不要在 SPA 的情况下使用)
我们有
app.UseAuthentication();
app.UseAuthorization();
这里 app.UseAuthentication(); 处理用户登录的身份验证功能。
所以你可以使用 app.UseAuthorization(); 仅在您的 web api 中间件中检查用户访问资源。
因此,如果您需要授权用户使用所有操作方法,请将[Authorize]
属性用于整个 controller,
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class HomeController : Controller
并且要调用的第一个操作方法可以像下面这样在 startup.cs 中进行映射
在我的例子中:索引
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
........
app.UseHttpsRedirection();
app.UseStaticFiles();
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
如果仅检查特定操作,如果某些操作不需要用户检查,您可以仅在这些方法上调用 [Authorize] 属性。
为了在调用时仅通过验证访问该操作。
[Authorize]
public async Task<IActionResult> Index()
{
var user = await _graphServiceClient.Me.Request().GetAsync();
ViewData["ApiResult"] = user.DisplayName;
return View();
}
如果不是,请不要使用 [Authorize] 属性修饰操作,这在访问 api 之前不需要验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.