如何将 .NET 4.6 上的 ASP.NET MVC 应用程序中的 OAuth 身份验证迁移到 Azure OpenId Connect 身份验证?

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

目前我的应用程序的配置如下所示:

OAuthOptions = new OAuthAuthorizationServerOptions
        {
            ApplicationCanDisplayErrors = true,                
            AuthorizeEndpointPath = new PathString("/Auth/Authorize"),
            TokenEndpointPath = new PathString("/Auth/Token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
            AccessTokenProvider = jwtProvider,
            Provider = new ApplicationOAuthProvider(PublicClientId)
        };

BearerOptions = new OAuthBearerAuthenticationOptions
        {
            AuthenticationType = OAuthDefaults.AuthenticationType,
            AuthenticationMode = AuthenticationMode.Active,
            AccessTokenProvider = jwtProvider
        };
    

app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseOAuthBearerAuthentication(BearerOptions);

我尝试了一些论坛,其中大多数都是针对.NET Core的,我尝试了带有连接服务的Visual Studio默认应用程序,但没有达到我想要的结果

asp.net-mvc azure oauth-2.0 azure-active-directory openid-connect
1个回答
0
投票

我尝试使用以下代码将 OAuth 身份验证迁移到面向 .NET Framework 4.6 的 ASP.NET MVC 应用程序中的 Azure OpenID Connect 身份验证:

代码:

Startup.Auth.cs:

using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using System;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;

[assembly: OwinStartup(typeof(WebApplication59.Startup))]
namespace WebApplication59
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }

        private void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
            string aadInstance = EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]);
            string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
            string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = $"{aadInstance}{tenantId}",
                RedirectUri = postLogoutRedirectUri,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                ResponseType = OpenIdConnectResponseType.IdToken,
                Scope = OpenIdConnectScope.OpenId,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false 
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        return Task.FromResult(0);
                    }
                }
            });
        }

        private static string EnsureTrailingSlash(string value)
        {
            if (value.EndsWith("/"))
            {
                return value;
            }
            return value + "/";
        }
    }
}

Web.config:

<configuration>
  <appSettings>
    <add key="ida:ClientId" value="<Clirn_ID>" />
    <add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
    <add key="ida:Domain" value="<Domain_Name>" />
    <add key="ida:TenantId" value="<Tenant_ID>" />
    <add key="ida:PostLogoutRedirectUri" value="https://localhost:<port>/signin-oidc" />
  </appSettings>

index.cshtml:

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
</head>
<body>
    <h2>Welcome!</h2>
</body>
</html>

_Layout.cshtml:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
        <div class="container">
            @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                    <li>@Html.ActionLink("About", "About", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                </ul>
                 @Html.Partial("_LoginPartial")
            </div>
        </div>
    </nav>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

我在应用程序中授予了openid和profile权限,如下所示:

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.