在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...

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

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核心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天全站免登陆