注销后重定向在 Asp.net Core 2 中不起作用

Mas*_*r_T 1 c# azure-active-directory asp.net-core-mvc asp.net-core asp.net-core-2.2

我将 Asp.net Core 2.2 与 AzureAD 身份验证一起使用。它工作正常,但现在我在尝试实现注销 url 时遇到问题。

我在控制器中尝试了以下操作:

[HttpGet("[action]")]
public IActionResult SignOut()
{
    return SignOut(new AuthenticationProperties { RedirectUri = Url.Action(nameof(AfterSignOut)) }, AzureADDefaults.AuthenticationScheme);
}

[HttpGet("[action]")]
[AllowAnonymous]
public IActionResult AfterSignOut()
{
    return Ok("It's working!");
}
Run Code Online (Sandbox Code Playgroud)

当我使用浏览器https://mySite/myController/SignOut登录时,注销操作正常工作(我的用户已注销,下次我转到某个页面时,我必须再次登录)

但是,问题是我没有重定向到.urlhttps://mySite/myController/AfterSignOut中指定的url AuthenticationProperties。相反/SignOut,它只返回 HTTP 代码 200,仅此而已,它不会将我重定向到任何地方。

我在这里做错了什么?

Nan*_* Yu 5

如果使用Microsoft.AspNetCore.Authentication.AzureAD.UI和使用身份验证,您可以尝试以下解决方案:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
    .AddAzureAD(options => Configuration.Bind("AzureAd", options));
Run Code Online (Sandbox Code Playgroud)

方法一:

创建帐户控制器并编写您自己的注销操作:

public readonly IOptionsMonitor<AzureADOptions> Options;
public AccountController(IOptionsMonitor<AzureADOptions> options)
{
    Options = options;
}
public IActionResult SignOut()
{
    var options = Options.Get(AzureADDefaults.AuthenticationScheme);
    var callbackUrl = Url.Action(nameof(AfterSignOut), "Account", values: null, protocol: Request.Scheme);
    return SignOut(
        new AuthenticationProperties { RedirectUri = callbackUrl },
        options.CookieSchemeName,
        options.OpenIdConnectSchemeName);
}
Run Code Online (Sandbox Code Playgroud)

方法二:

使用库中的现有注销功能,在OnSignedOutCallbackRedirect事件中设置新的重定向 URL :

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{

    options.Events.OnSignedOutCallbackRedirect = (context) =>
    {

        context.Response.Redirect("/Account/AfterSignOut");
        context.HandleResponse();

        return Task.CompletedTask;
    };
});
Run Code Online (Sandbox Code Playgroud)

并在您要执行注销的页面中添加一个链接:

<a href="~/AzureAD/Account/SignOut">SignOut</a>
Run Code Online (Sandbox Code Playgroud)

方法三:

使用自定义的URL 重写中间件通过检查路径来重定向,在前面放置以下代码app.UseMvc

app.UseRewriter(
    new RewriteOptions().Add(
        context => { if (context.HttpContext.Request.Path == "/AzureAD/Account/SignedOut")
            { context.HttpContext.Response.Redirect("/Account/AfterSignOut"); }
        })
);
Run Code Online (Sandbox Code Playgroud)

还有链接: <a href="~/AzureAD/Account/SignOut">SignOut</a>