我已经设置了我的ASP Net Core 2.0项目以使用Azure AD进行身份验证(在使用OIDC的VS2017中使用标准Azure AD身份验证模板)。一切工作正常,应用程序返回到基地址(/)并在验证成功后运行HomeController.Index操作。如何在Azure AD身份验证之后重定向到ASP中的其他控制器操作Net Core MVC
但是我现在想在验证后重定向到不同的控制器操作(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);
}
}
似乎你主张为正确的工作使用正确的工具,我喜欢它。 – JasonInVegas