我已将 ASP Net Core 2.0 项目设置为使用 Azure AD 进行身份验证(使用 VS2017 中使用 OIDC 的标准 Azure AD 身份验证模板)。一切工作正常,应用程序返回到基本 url (/) 并在身份验证成功后运行 HomeController.Index 操作。
但是,我现在想在身份验证后重定向到不同的控制器操作(AccountController.CheckSignIn),以便我可以检查用户是否已存在于我的本地数据库表中,如果不存在(即它是新用户),则创建本地用户记录,然后重定向到 HomeController.Index 操作。
我可以将此检查放在 HomeController.Index 操作本身中,但我想避免每次用户单击“主页”按钮时运行此检查。
以下是一些代码片段,可能有助于澄清......
appsettings.json 中的 AAD 设置
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "<my-domain>.onmicrosoft.com",
"TenantId": "<my-tennant-id>",
"ClientId": "<my-client-id>",
"CallbackPath": "/signin-oidc" // I don't know where this goes but it doesn't exist anywhere in my app and authentication fails if i change it
}
我向 AccountController.CheckSignIn 添加了一个新操作来处理此要求,但我找不到在身份验证后调用它的方法。
public class AccountController : Controller
{
// I want to call this action after authentication is successful
// GET: /Account/CheckSignIn
[HttpGet]
public IActionResult CheckSignIn()
{
var provider = OpenIdConnectDefaults.AuthenticationScheme;
var key = User.FindFirstValue(ClaimTypes.NameIdentifier);
var info = new ExternalLoginInfo(User, provider, key, User.Identity.Name);
if (info == null)
{
return BadRequest("Something went wrong");
}
var user = new ApplicationUser { UserName = User.Identity.Name };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (!result.Succeeded)
{
return BadRequest("Something else went wrong");
}
}
return RedirectToAction(nameof(HomeController.Index), "Home");
}
// This action only gets called when user clicks on Sign In link but not when user first navigates to site
// GET: /Account/SignIn
[HttpGet]
public IActionResult SignIn()
{
return Challenge(
new AuthenticationProperties { RedirectUri = "/Account/CheckSignIn" }, OpenIdConnectDefaults.AuthenticationScheme);
}
}