示例#1
0
        //
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        // The App Key is a credential used to authenticate the application to Azure AD.  Azure AD supports password and certificate credentials.
        // The Metadata Address is used by the application to retrieve the signing keys used by Azure AD.
        // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
        // The Authority is the sign-in URL of the tenant.
        // The Post Logout Redirect Uri is the URL where the user will be redirected after they sign out.
        //
        // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = MediaLibraryWebApp.Configuration.ClientId,
                    Authority = MediaLibraryWebApp.Configuration.Authority,
                    PostLogoutRedirectUri = MediaLibraryWebApp.Configuration.PostLogoutRedirectUri,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        //
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                        //
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;
                            System.IdentityModel.Tokens.JwtSecurityToken jwtToken = context.JwtSecurityToken;

                            string userObjectID = context.AuthenticationTicket.Identity.FindFirst(MediaLibraryWebApp.Configuration.ClaimsObjectidentifier).Value;

                            Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(MediaLibraryWebApp.Configuration.ClientId, MediaLibraryWebApp.Configuration.AppKey);

                            NaiveSessionCache cache = new NaiveSessionCache(userObjectID);
                            AuthenticationContext authContext = new AuthenticationContext(MediaLibraryWebApp.Configuration.Authority, cache);

                            //Getting a token to connect with GraphApi later on userProfile page
                            AuthenticationResult graphAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.GraphResourceId);

                            //Getting a access token which can be used to configure auth restrictions for multiple tentants since audience will be same for each web app requesting this token
                            //AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.KdResourceId);

                            //string kdAccessToken = kdAPiresult.AccessToken;

                            //Initializing  MediaServicesCredentials in order to obtain access token to be used to connect
                            var amsCredentials = new MediaServicesCredentials(MediaLibraryWebApp.Configuration.MediaAccount, MediaLibraryWebApp.Configuration.MediaKey);
                            //Forces to get access token
                            amsCredentials.RefreshToken();

                            //Adding token to a claim so it can be accessible within controller
                            context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsSignInJwtToken, jwtToken.RawData));

                            //Adding media services access token as claim so it can be accessible within controller
                            context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsAmsAcessToken, amsCredentials.AccessToken));

                            return Task.FromResult(0);
                        }

                    }

                });
        }
        private JwtSecurityToken GetJwtSecurityToken()
        {

            IOwinContext owinContext = HttpContext.GetOwinContext();
            string userObjectID = owinContext.Authentication.User.Claims.First(c => c.Type == Configuration.ClaimsObjectidentifier).Value;
            NaiveSessionCache cache = new NaiveSessionCache(userObjectID);
            AuthenticationContext authContext = new AuthenticationContext(Configuration.Authority, cache);
            var tokens = authContext.TokenCache.ReadItems();
            TokenCacheItem kdAPITokenCache = tokens.Where(c => c.Resource == Configuration.GraphResourceId).FirstOrDefault();

            if (kdAPITokenCache == null)
            {


                authContext.TokenCache.Clear();
               
                ViewBag.ErrorMessage = "AuthorizationRequired";
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                return null;
            }
            
            
            return new JwtSecurityToken(kdAPITokenCache.AccessToken);
         
        }
        //
        // GET: /UserProfile/
        public async Task<ActionResult> Index()
        {
            //
            // Retrieve the user's name, tenantID, and access token since they are parameters used to query the Graph API.
            //
            UserProfile profile;
            IOwinContext owinContext = HttpContext.GetOwinContext();
            string userObjectID = owinContext.Authentication.User.Claims.First(c => c.Type == Configuration.ClaimsObjectidentifier).Value;
            NaiveSessionCache cache = new NaiveSessionCache(userObjectID);          
            AuthenticationContext authContext = new AuthenticationContext(Configuration.Authority,cache);
                        
            try
            {
                TokenCacheItem graphAPITokenCache =authContext.TokenCache.ReadItems().Where(c => c.Resource == MediaLibraryWebApp.Configuration.GraphResourceId).FirstOrDefault();
                //TokenCacheItem kdAPITokenCache = authContext.TokenCache.ReadItems().Where(c => c.Resource == MediaLibraryWebApp.Configuration.KdResourceId).FirstOrDefault();
                           
             
                
                if (graphAPITokenCache == null )
                {

                  
                    authContext.TokenCache.Clear();
                    profile = new UserProfile();
                    ViewBag.ErrorMessage = "AuthorizationRequired";
                    if (Request.QueryString["reauth"] == "True")
                    {
                        //
                        // Send an OpenID Connect sign-in request to get a new set of tokens.
                        // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                        // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                        //
                        HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                    }

                    return View(profile);
                }


                string graphAPIAccessToken = graphAPITokenCache.AccessToken;


                JwtSecurityToken signInToken = new JwtSecurityToken(owinContext.Authentication.User.Claims.First(c => c.Type == Configuration.ClaimsSignInJwtToken).Value);

                ActiveDirectoryClient activeDirectoryClient = Factory.GetActiveDirectoryClientAsApplication(graphAPIAccessToken);
                User userProfile = (User)await activeDirectoryClient.Users.GetByObjectId(userObjectID).ExecuteAsync();
                List<string> membergroups = (await userProfile.GetMemberGroupsAsync(false)).ToList();
                var groups = await activeDirectoryClient.Groups.ExecuteAsync();
                profile = new UserProfile();               
                profile.GraphApiAccessToken = new JwtSecurityToken(graphAPIAccessToken);
                //profile.KeyDeliveryApiAccessToken = new JwtSecurityToken(kdAPITokenCache.AccessToken);
                profile.OpenConnectSignInToken = signInToken;
                profile.MemberGroups = membergroups;
                profile.AllGroups = groups.CurrentPage;
                profile.User = userProfile;
                return View(profile);
            }
            catch (Exception ex)
            {
                //
                // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again.
                //
                var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == Configuration.GraphResourceId);
                foreach (TokenCacheItem tci in todoTokens)
                    authContext.TokenCache.DeleteItem(tci);

                //
                // If refresh is set to true, the user has clicked the link to be authorized again.
                //
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                profile = new UserProfile();
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return View(profile);

            }
        }