iT邦幫忙

0

在 asp.net Web Forms 使用 Open ID Connect 串接 Azure Active Directory

  • 分享至 

  • xImage
  •  

Step1: 使用 Nuget 安裝以下套件與相依套件

  1. Microsoft.Owin.Security.OpenIdConnect
  2. Microsoft.Owin.Security.Cookies
  3. Microsoft.Owin.Host.SystemWeb

上述安裝完畢後,可於 packages.json 檔案內發現新增了以下套件

<package id="Microsoft.IdentityModel.JsonWebTokens" version="6.5.0" targetFramework="net461" />
<package id="Microsoft.IdentityModel.Logging" version="6.5.0" targetFramework="net461" />
<package id="Microsoft.IdentityModel.Protocols" version="6.5.0" targetFramework="net461" />
<package id="Microsoft.IdentityModel.Protocols.OpenIdConnect" version="6.5.0" targetFramework="net461" />
<package id="Microsoft.IdentityModel.Tokens" version="6.5.0" targetFramework="net461" />
<package id="Microsoft.Owin" version="4.1.0" targetFramework="net461" />
<package id="Microsoft.Owin.Host.SystemWeb" version="4.1.0" targetFramework="net461" />
<package id="Microsoft.Owin.Security" version="4.1.0" targetFramework="net461" />
<package id="Microsoft.Owin.Security.Cookies" version="4.1.0" targetFramework="net461" />
<package id="Microsoft.Owin.Security.OpenIdConnect" version="4.1.0" targetFramework="net461" />
<package id="Owin" version="1.0" targetFramework="net461" />
<package id="System.IdentityModel.Tokens.Jwt" version="6.5.0" targetFramework="net461" />

Step2: 增加 Open ID Connect 設定,請於 App_Start 資料夾內,增加 Startup.Auth.cs 檔案,其內容如下

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

namespace yourNamespace
{
    public partial class Startup
    {
        private const string MSATenantId = "9188040d-6c67-4c5b-b112-36a304b66dad";
        public static readonly string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        public static readonly string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];

        private static string authority = "https://login.microsoftonline.com/common/v2.0";

        public static readonly string redirectUri = "https://localhost:44371/";

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

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = redirectUri,
                Scope = "openid profile",
                ResponseType = "id_token",
                TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, NameClaimType = "name" },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = this.OnAuthenticationFailedAsync,
                    SecurityTokenValidated = this.OnSecurityTokenValidatedAsync
                }
            });
        }

        private Task OnSecurityTokenValidatedAsync(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            // Make sure that the user didn't sign in with a personal Microsoft account
            if (notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value == MSATenantId)
            {
                notification.HandleResponse();
                notification.Response.Redirect("/Account/UserMismatch");
            }

            return Task.FromResult(0);
        }

        private Task OnAuthenticationFailedAsync(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            notification.HandleResponse();
            notification.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + notification.Exception.Message);
            return Task.FromResult(0);
        }
    }
}

Step3: 於程式啟動時,執行 Startup.Auth.cs 進行註冊,增加 Startup.cs 於專案根目錄

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(yourNamespace.Startup))]

namespace yourNamespace
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            ConfigureAuth(app);
        }
    }
}

Step4: 設定 ClientId 於 Web.config 內

<appSettings>
    <add key="ida:ClientId" value="[Your ClientId]" />
    <add key="ida:ClientSecret" value="[Your ClientSecret]" />
</appSettings>

Step5: 登入功能

HttpContext.Current.GetOwinContext()
    .Authentication.Challenge(
        new AuthenticationProperties { RedirectUri = "/RedirectUri" },
        OpenIdConnectAuthenticationDefaults.AuthenticationType
    );

Step6: 增加登出頁面(Logout.aspx),承接登出後須進行之事項

HttpContext.Current.GetOwinContext().Authentication
    .SignOut(CookieAuthenticationDefaults.AuthenticationType);
Session.Clear();
Response.Redirect("~/");

Step7: 登出功能,設定登出後轉向 Logout.aspx 頁面

string callbackUrl = $"{Request.Url.Scheme}://{Request.Url.Authority}{Page.ResolveUrl("~/Logout.aspx")}{Request.Url.Query}";

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

當使用者登入後,可使用以下方法取得簡單的資訊

// Name
System.Security.Claims.ClaimsPrincipal.Current.FindFirst("name")?.Value

// User Name
System.Security.Claims.ClaimsPrincipal.Current.FindFirst("preferred_username")?.Value

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言