[AAD]登錄認證流程配置


NuGet部分引用

 

 

 

Startup Configuration中添加基本配置

app.UseOpenIdConnectAuthentication(

                new OpenIdConnectAuthenticationOptions

                {

                    // Sets the ClientId, authority, RedirectUri as obtained from web.config

                    ClientId = SettingsHelper.ClientId,

                    Authority = SettingsHelper.Authority,

                    RedirectUri = SettingsHelper.RedirectURL,

                    // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page

                    PostLogoutRedirectUri = SettingsHelper.RedirectURL,

                    //Scope = OpenIdConnectScope.OpenIdProfile,

                    Resource = SettingsHelper.Resource,

                    // ResponseType is set to request the id_token - which contains basic information about the signed-in user

                    //ResponseType = OpenIdConnectResponseType.IdToken,

                    // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application

                    // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name

                    // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter

                    TokenValidationParameters = new TokenValidationParameters()

                    {

                        ValidateIssuer = false

                    },

                    //OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method

                    Notifications = new OpenIdConnectAuthenticationNotifications

                    {

                        AuthenticationFailed = context =>

                        {

                            context.HandleResponse();

                            context.Response.Redirect("/Home/SignOut");

                            return Task.FromResult(0);

                        },

                        RedirectToIdentityProvider = context =>

                        {

                            //context.ProtocolMessage.Prompt = "admin_consent";

                            return Task.FromResult(0);

                        },

                        SecurityTokenReceived = t => Task.FromResult(0),

                        AuthorizationCodeReceived = context =>

                        {

                            var code = context.Code;

                            var credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);

                            var orgId = context.AuthenticationTicket.Identity.Name;

                            //var tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                            var signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                            var authContext = new AuthenticationContext($"{SettingsHelper.Authority}/oauth2/authorize", new TokenCacheHelper(signInUserId, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase));

                            var result = authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(SettingsHelper.RedirectURL), credential, SettingsHelper.Resource).Result;

                            return Task.FromResult(0);

                        },

                    }

                });

 

添加自定義Token緩存

 

    public class TokenCacheHelper : TokenCache

    {

        private HttpContextBase context;

        private static readonly object FileLock = new object();

        private readonly string CacheId;

        public string UserObjectId;

 

        public TokenCacheHelper(string userId, HttpContextBase context)

        {

            this.context = context;

            this.UserObjectId = userId;

            this.CacheId = UserObjectId + "_TokenCache";

 

            AfterAccess = AfterAccessNotification;

            BeforeAccess = BeforeAccessNotification;

            Load();

        }

 

        public void Load()

        {

            lock (FileLock)

            {

                Deserialize((byte[])context.Session[CacheId]);

            }

        }

 

        public void Persist()

        {

            lock (FileLock)

            {

                // Reflect changes in the persistent store.

                var bytes = Serialize();

                var x = System.Text.Encoding.UTF8.GetString(bytes);

                context.Session[CacheId] = Serialize();

 

                // After the write operation takes place, restore the HasStateChanged bit to false.

                HasStateChanged = false;

            }

        }

 

        // Empties the persistent store.

        public void Clear(string clientId)

        {

            context.Session.Remove(CacheId);

        }

 

        // Triggered right before ADAL needs to access the cache.

        // Reload the cache from the persistent store in case it changed since the last access.

        private void BeforeAccessNotification(TokenCacheNotificationArgs args)

        {

            Load();

        }

 

        // Triggered right after ADAL accessed the cache.

        private void AfterAccessNotification(TokenCacheNotificationArgs args)

        {

            // if the access operation resulted in a cache update

            if (HasStateChanged)

            {

                Persist();

            }

        }

}

自定義網站加載中代碼:

if (!Request.IsAuthenticated)//判斷是否登錄

            {

                HttpContext.GetOwinContext().Authentication.Challenge(

                    new AuthenticationProperties { RedirectUri = "/" },

                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

            }

 

基本參數:

  <add key="ClientId" value="**" /> //Azure AD注冊后Application ID

  <add key="Resource" value="https://microsoftgraph.chinacloudapi.cn" />

  <add key="RedirectURL" value="http://localhost:125" />

  <add key="Tenant" value="common" />

  <add key="Authority" value="https://login.chinacloudapi.cn/common " />

  <add key="ClientSecret" value="**" /> //Azure AD注冊后Application Secret(Web API)

  <add key="GraphUrl" value="https://microsoftgraph.chinacloudapi.cn/v1.0" />

 

注冊AAD

  1. 進入azure門戶
  2. 打開Azure Active Directory
  3. 應用程序注冊
  4. 新應用程序注冊

配置如圖

 

 

 

 

ClientSecret在

 

 

基本登錄權限

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM