在 ASP.NET MVC 应用程序中重定向到身份验证页面的问题

问题描述 投票:0回答:1

我在 ASP.NET MVC 应用程序中重定向到身份验证页面时遇到问题。以下是我的设置的简要概述:

  • 我已将我的应用程序配置为使用 AAD 进行身份验证。
  • 我已在 Azure 门户中设置重定向 URI,以匹配我的应用程序中使用的重定向 URI(
    https://localhost:44341/signin-oidc
    https://localhost:44387/signin-oidc
    https://localhost:44320/signin-oidc
    )。
  • 我使用 Microsoft.Owin.Security 和 Microsoft.Owin.Security.OpenIdConnect 作为身份验证中间件。

但是,当我运行应用程序并尝试访问受身份验证保护的路由时,我没有按预期重定向到 AAD 身份验证页面。相反,我保持在同一页面上,没有任何重定向或错误消息。

这是我的代码的相关片段:

Startup.Auth.cs

public partial class Startup
{
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string aadInstance = EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]);
    private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
    private static string authority = aadInstance + tenantId + "/v2.0";

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    SecurityTokenValidated = (context) =>
                    {
                        string name = context.AuthenticationTicket.Identity.FindFirst("preferred_username").Value;
                        context.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Name, name, string.Empty));
                        return System.Threading.Tasks.Task.FromResult(0);
                    }
                }
            });
    }

    private static string EnsureTrailingSlash(string value)
    {
        if (value == null)
        {
            value = string.Empty;
        }

        if (!value.EndsWith("/", StringComparison.Ordinal))
        {
            return value + "/";
        }

        return value;
    }
}

Startup.cs

namespace OidcTestDemo
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

Web.config

<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="ida:ClientId" value="" />
    <add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
    <add key="ida:Domain" value="" />
    <add key="ida:TenantId" value="" />
    <add key="ida:PostLogoutRedirectUri" value="https://localhost:44341/signin-oidc" />
</appSettings>

此外,

AccountControlller
未被调用:

namespace OidcTestDemo.Controllers
{
    public class AccountController : Controller
    {
        public void SignIn()
        {
            if (!Request.IsAuthenticated)
            {
                HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
        }

        public void SignOut()
        {
            string callbackUrl = Url.Action("SignOutCallback", "Account", routeValues: null, protocol: Request.Url.Scheme);

            HttpContext.GetOwinContext().Authentication.SignOut(
               new AuthenticationProperties { RedirectUri = callbackUrl },
               OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
        }

        public ActionResult SignOutCallback()
        {
            if (Request.IsAuthenticated)
            {
                // Redirect to home page if the user is authenticated.
                return RedirectToAction("Index", "Home");
            }

            return View();
        }
    }
}
.net asp.net-mvc authentication azure-active-directory openid-connect
1个回答
0
投票

我能够重定向到 ASP.NET MVC 应用程序中的身份验证页面。

下面是我的 _LoginPartial.cshtml 代码。

@if (Request.IsAuthenticated)
{
    <text>
    <ul class="navbar-nav navbar-right">
        <li class="navbar-text">
            Hello, @User.Identity.Name!
        </li>
        <li>
            @Html.ActionLink("Sign out", "SignOut", "Account", new { area = "" }, new { @class = "nav-link" })
        </li>
    </ul>
    </text>
}
else
{
    <ul class="navbar-nav navbar-right">
        <li>@Html.ActionLink("Sign in", "SignIn", "Account", routeValues: null, htmlAttributes: new { id = "loginLink", @class ="nav-link" })</li>
    </ul>
}

SignOutCallback.cshtml:

@{
    ViewBag.Title = "Sign Out";
}
<main aria-labelledby="title">
    <h2 id="title">@ViewBag.Title.</h2>
    <p class="text-success">You have successfully signed out.</p>
</main>

将以下行添加到 _Layout.cshtml 中。

_Layout.cshtml:

@Html.Partial("_LoginPartial")

enter image description here

输出:

运行成功,我可以登录如下。

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.