我有一个Web应用程序,该应用程序旨在使用Outlook作为电子邮件提供商的列表。Web应用程序使用Microsofts外部登录API。但是任何拥有Microsoft电子邮件帐户的人都可以登录。
我假设这是Microsoft Dev Portal中的应用程序设置,或者在May代码中以某种方式覆盖。我如何过滤应用程序域或具有可以登录的严格帐户列表?
afaik,门户网站没有设置来控制它,因此,在从Microsoft的登录页面重定向到客户端后,解决方法可以限制帐户类型。
我假设您正在使用Microsoft.AspNetCore.Authentication.MicrosoftAccount
:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/social/microsoft-logins?
您可以检查ASP.NET身份的ExternalLoginCallback
功能中的电子邮件帐户是否为Outlook帐户:
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ErrorMessage = $"Error from external provider: {remoteError}";
return RedirectToAction(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
var emailAddress = info.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;
//Check whether this is outlook account .
if (!"outlook.com".Equals(emailAddress.Split('@')[1]))
{
//return to error page and show error message
}
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.IsLockedOut)
{
return RedirectToAction(nameof(Lockout));
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLogin", new ExternalLoginViewModel { Email = email });
}
}
另一种方法是在中间件中检查OnCreatingTicket
事件,如果登录用户不是Outlook帐户,请重定向用户再次登录页面:
services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
{
OnCreatingTicket = ctx =>
{
var email = ctx.Identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
if (!"outlook.com".Equals(email.Value.Split('@')[1]))
{
ctx.Response.Redirect("/");
}
return Task.FromResult(0);
}
};
microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ApplicationId"];
microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:Password"];
});
更新:
如果您使用Individual User Accounts
模板创建.NET Core应用程序,则意味着您正在使用ASP.NET身份:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/indentity?view=peaspnetcore-2&amp.amp; tabs=visual-studio
ASP.NET Core 2.1及以后提供ASP.NET Core Identity作为Razor类库。您可以在ASP.NET核心项目中脚手架身份,以修改代码并更改行为。或者,您可以尝试上面的第二个解决方案来修改OpenID Connect中间件。