如何在 Azure AD 身份验证后重定向到 ASP Net Core MVC 中的不同控制器操作 [英] How to redirect after Azure AD authentication to different controller action in ASP Net Core MVC

本文介绍了如何在 Azure AD 身份验证后重定向到 ASP Net Core MVC 中的不同控制器操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了我的 ASP Net Core 2.0 项目以使用 Azure AD 进行身份验证(使用 VS2017 中使用 OIDC 的标准 Azure AD 身份验证模板).一切正常,应用程序返回到基本 url (/) 并在身份验证成功后运行 HomeController.Index 操作.

I have setup my ASP Net Core 2.0 project to authenticate with Azure AD (using the standard Azure AD Identity Authentication template in VS2017 which uses OIDC). Everything is working fine and the app returns to the base url (/) and runs the HomeController.Index action after authentication is successful.

但是我现在想在身份验证后重定向到不同的控制器操作(AccountController.CheckSignIn),以便我可以检查用户是否已经存在于我的本地数据库表中,如果不存在(即它是一个新用户)创建一个本地用户记录然后重定向到 HomeController.Index 操作.

However I now want to redirect to a different controller action (AccountController.CheckSignIn) after authentication so that I can check if the user already exists in my local database table and if not (ie it's a new user) create a local user record and then redirect to HomeController.Index action.

我可以将此检查放入 HomeController.Index 操作本身,但我想避免每次用户单击主页按钮时运行此检查.

I could put this check in the HomeController.Index action itself but I want to avoid this check from running every time the user clicks on Home button.

这里有一些代码片段可能有助于清晰...

Here are some code snippets which may help give clarity...

appsettings.json 中的 AAD 设置

AAD settings in appsettings.json

"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 添加了一个新操作来处理此要求,但我找不到在身份验证后调用它的方法.

I added a new action to my AccountController.CheckSignIn to handle this requirement but I cannot find a way to call it after authentication.

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);
    }

}

推荐答案

我找到了一种通过使用重定向使其工作的方法,如下所示...

I have found a way to make it work by using a redirect as follows...

内部启动

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Account}/{action=SignIn}/{id?}");
});

AccountController 内部

Inside AccountController

// GET: /Account/CheckSignIn
[HttpGet]
[Authorize]
public IActionResult CheckSignIn()
{
    //add code here to check if AzureAD identity exists in user table in local database
    //if not then insert new user record into local user table

    return RedirectToAction(nameof(HomeController.Index), "Home");
}

//
// GET: /Account/SignIn
[HttpGet]
public IActionResult SignIn()
{
    return Challenge(
        new AuthenticationProperties { RedirectUri = "/Account/CheckSignIn" }, OpenIdConnectDefaults.AuthenticationScheme);
}

在 AzureAdServiceCollectionExtensions (.net core 2.0) 中

Inside AzureAdServiceCollectionExtensions (.net core 2.0)

private static Task RedirectToIdentityProvider(RedirectContext context)
{
    if (context.Request.Path != new PathString("/"))
    {
        context.Properties.RedirectUri = new PathString("/Account/CheckSignIn");
    }
    return Task.FromResult(0);
}

这篇关于如何在 Azure AD 身份验证后重定向到 ASP Net Core MVC 中的不同控制器操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆