我已經設置了我的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