/// <summary> /// GetToken function used to authenticate against Key Vault /// </summary> /// <param name="authority"></param> /// <param name="resource"></param> /// <param name="scope"></param> /// <returns></returns> private static async Task <string> GetToken(string authority, string resource, string scope) { var id = ConfigurationManager.AppSettings["hsma-ida:PortalClientId"]; var secret = ConfigurationManager.AppSettings["hsma-ida:PortalAppKey"]; return(await IsmUtils.GetAccessToken(authority, resource, id, secret)); }
/// <summary> /// Get public key as a PEM formatted base64 encoded string. /// </summary> /// <param name="key">Key object to be formatted.</param> /// <returns>PEM formatted string.</returns> public static string GetPublicKey(Microsoft.Azure.KeyVault.WebKey.JsonWebKey key) { TextWriter outputStream = new StringWriter(); outputStream.WriteLine("-----BEGIN PUBLIC KEY-----"); var pkcs8Key = IsmUtils.ConvertJwkToPkcs8(key); for (Int32 i = 0; i < pkcs8Key.Length; i += 64) { outputStream.WriteLine(pkcs8Key.ToCharArray(), i, (Int32)Math.Min(64, pkcs8Key.Length - i)); } outputStream.WriteLine("-----END PUBLIC KEY-----"); return(outputStream.ToString()); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { // First check if user is authenticated if (!ClaimsPrincipal.Current.Identity.IsAuthenticated) { return(false); } else if (this.Groups == null && this.GroupObjectIds == null) // If there are no groups return here { return(base.AuthorizeCore(httpContext)); } List <string> groupsList = null; List <string> groupsObjectIdsList = new List <string>(); // Split groups and group object ids into lists if (Groups != null) { // Remove spaces Groups = System.Text.RegularExpressions.Regex.Replace(Groups, " ", ""); // Split by , groupsList = Groups.Split(',').ToList(); } if (GroupObjectIds != null) { // Remove spaces GroupObjectIds = System.Text.RegularExpressions.Regex.Replace(GroupObjectIds, " ", ""); // Split by , groupsObjectIdsList = GroupObjectIds.Split(',').ToList(); } // Now check if user is in group by querying Azure AD Graph API using client bool inGroup = false; try { // Get information from user claim string signedInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; string tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; // Create graph connection ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( new Uri("https://graph.windows.net/" + tenantId),//this._resourceId), async() => { return(await IsmUtils.GetAccessToken( authority: ConfigurationManager.AppSettings["ida:AADInstance"] + tenantId, resourceId: _graphResourceID, clientId: _clientId, clientSecret: _appKey)); } ); // If we have groups we need to convert to group IDs, enter here if (groupsList != null) { // Query the Graph API to get all groups var groups = activeDirectoryClient.Groups.ExecuteAsync().Result; // Iterate over collection do { // Get current page as list List <IGroup> groupObjects = groups.CurrentPage.ToList(); // Select all object IDs that have a matching display name to our groups list var idList = groupObjects .Where(g => groupsList.Contains(g.DisplayName)) .Select(g => g.ObjectId); // Add these IDs to our ID list groupsObjectIdsList.AddRange(idList); } while (groups != null && groups.MorePagesAvailable && !inGroup); } // If we have a group ID, check if the user is member of that group if (groupsObjectIdsList.Count > 0) { // Get the user var user = activeDirectoryClient.Users .Where(u => u.ObjectId.Equals(userObjectId)) .ExecuteSingleAsync().Result; // User Fetcher to get group information IUserFetcher retrievedUserFetcher = (User)user; // Get all objects that user is member of var pagedCollection = retrievedUserFetcher.MemberOf.ExecuteAsync().Result; // Iterate over collection do { List <IDirectoryObject> directoryObjects = pagedCollection.CurrentPage.ToList(); foreach (IDirectoryObject directoryObject in directoryObjects) { // If the object is a group if (directoryObject is Group) { Group group = directoryObject as Group; // Check if that group is the group we're trying to authenticate against // If so, set inGroup to true and exit loop if (groupsObjectIdsList.Contains(group.ObjectId)) { inGroup = true; break; } } } } while (pagedCollection != null && pagedCollection.MorePagesAvailable && !inGroup); } } catch (Exception ex) { string message = string.Format("Unable to authorize AD user: {0} against group: {1}", ClaimsPrincipal.Current.Identity.Name, this.Groups); throw new Exception(message, ex); } return(inGroup); }