/// <summary> /// The Page_Load method implementation for this page. /// </summary> /// <param name="sender">Sender</param> /// <param name="e">EventArgs</param> protected void Page_Load(object sender, EventArgs e) { if (Page.User.Identity.IsAuthenticated) { IClaimsIdentity claimsIdentity = Thread.CurrentPrincipal.Identity as IClaimsIdentity; // For illustrative purposes, this sample application simply shows all the parameters of // claims (i.e. claim types and claim values), which are issued by a security token // service (STS), to its clients. In production code, security implications of echoing // the properties of claims to the clients should be carefully considered. For example, // some of the security considerations are: (i) accepting the only claim types that are // expected by relying party applications; (ii) sanitizing the claim parameters before // using them; and (iii) filtering out claims that contain sensitive personal information). // DO NOT use this sample code ‘as is’ in production code. ShowName(claimsIdentity); ShowClaimsIdentityAsIIdentity(claimsIdentity); ShowClaimsFromClaimsIdentity(claimsIdentity); } else { // Not logged in. Redirect to Login page for authentication. Response.Redirect("Login.aspx"); } }
/// <summary> /// Retrieves the issuer name of an IClaimsIdentity. /// The algorithm checks the name claim first, and if no name is found, the first claim. /// </summary> /// <param name="identity">The identity.</param> /// <returns>The issuer name</returns> public static string GetIssuerName(this IClaimsIdentity identity) { Contract.Requires(identity != null); Contract.Requires(identity.Claims != null); Contract.Ensures(Contract.Result <string>() != null); // first try the name claim var claim = identity.FindClaims(WSIdentityConstants.ClaimTypes.Name).FirstOrDefault(); if (claim != null) { if (claim.Issuer != null) { return(claim.Issuer); } } // then try the first claim if (identity.Claims.Count > 0) { claim = identity.Claims[0]; if (claim != null) { if (claim.Issuer != null) { return(claim.Issuer); } } } // empty or exception? return(""); }
/// <summary> /// Sets Windows Identify Foundation Claims /// </summary> internal static void SetClaims() { if (HttpContext.Current.ApplicationInstance.IsSTSaware()) { //Set Claims IClaimsPrincipal principal = (IClaimsPrincipal)Thread.CurrentPrincipal; IClaimsIdentity identity = (IClaimsIdentity)principal.Identity; UserProfile Profile = GetCurrentConnectionToken().Profile; if (!string.IsNullOrEmpty(Profile.DateOfBirth)) { identity.Claims.Add(new Claim(ClaimTypes.DateOfBirth.ToString(), Profile.DateOfBirth, "string", "SocialAuth.NET", Profile.Provider.ToString())); } if (!string.IsNullOrEmpty(Profile.FirstName)) { identity.Claims.Add(new Claim(ClaimTypes.GivenName.ToString(), Profile.FirstName, "string", "SocialAuth.NET", Profile.Provider.ToString())); } if (!string.IsNullOrEmpty(Profile.LastName)) { identity.Claims.Add(new Claim(ClaimTypes.Surname.ToString(), Profile.LastName, "string", "SocialAuth.NET", Profile.Provider.ToString())); } if (!string.IsNullOrEmpty(Profile.Email)) { identity.Claims.Add(new Claim(ClaimTypes.Email.ToString(), Profile.Email, "string", "SocialAuth.NET", Profile.Provider.ToString())); } if (!string.IsNullOrEmpty(Profile.Gender)) { identity.Claims.Add(new Claim(ClaimTypes.Gender.ToString(), Profile.Gender, "string", "SocialAuth.NET", Profile.Provider.ToString())); } if (!string.IsNullOrEmpty(Profile.Country)) { identity.Claims.Add(new Claim(ClaimTypes.Country.ToString(), Profile.Country, "string", "SocialAuth.NET", Profile.Provider.ToString())); } } }
/// <summary> /// Initializes a new instance of the <see cref="UserInformation"/> class from the provided <see cref="IIdentity"/> instance. /// </summary> /// <param name="identity">The identity to use to initialize the <see cref="UserInformation"/> instance.</param> /// <exception cref="SecurityException">Occurs if the identity provided is not an <see cref="IClaimsIdentity"/>.</exception> public UserInformation(IIdentity identity) { if (identity is IClaimsIdentity) this.claimsIdentity = identity as IClaimsIdentity; else throw new SecurityException("Current principal is not a claims-based principal."); }
public void ReplaceClaimsIfExist(IClaimsIdentity claimsIdentity, Claim claimToReplaceIfExists) { var existingClaim = claimsIdentity.Claims.FirstOrDefault(x=> x.ClaimType == claimToReplaceIfExists.ClaimType); if (existingClaim != null) claimsIdentity.Claims.Remove(existingClaim); claimsIdentity.Claims.Add(claimToReplaceIfExists); }
/// <summary> /// Create a new claims principal /// </summary> public SanteDBClaimsPrincipal(IClaimsIdentity identity) { this.m_identities = new List <IClaimsIdentity>() { identity }; }
private static void CopySocialClaims(IClaimsIdentity input, IClaimsIdentity output) { string issuer = input.Claims.Where(c => c.ClaimType.Equals("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider")).FirstOrDefault().Value; string nameClaimValue; string originalIssuer = "acs\\"; switch (issuer) { case "Google": nameClaimValue = input.Claims.Where(c => c.ClaimType.Equals(ClaimTypes.Name)).FirstOrDefault().Value; originalIssuer = string.Concat(originalIssuer, "Google"); break; case "uri:WindowsLiveID": nameClaimValue = input.Claims.Where(c => c.ClaimType.Equals(ClaimTypes.NameIdentifier)).FirstOrDefault().Value; originalIssuer = string.Concat(originalIssuer, "LiveID"); break; case "Facebook-194130697287302": nameClaimValue = input.Claims.Where(c => c.ClaimType.Equals(ClaimTypes.Name)).FirstOrDefault().Value; originalIssuer = string.Concat(originalIssuer, "Facebook"); break; default: throw new InvalidOperationException("Issuer not trusted."); } var claim = new Claim(ClaimTypes.Name, nameClaimValue, ClaimValueTypes.String, "adatum", originalIssuer); output.Claims.Add(claim); }
private void Initialize() { _claimsIdentity = ((IClaimsPrincipal)(Thread.CurrentPrincipal)).Identities[0]; foreach (var c in _claimsIdentity.Claims) { _strClaimType = c.ClaimType; if (_strClaimType.EndsWith("domain")) _domain = c.Value; if (_strClaimType.EndsWith("EmailAddress")) _email = c.Value; } _user = _restAPI.GetUserByEmail(_email); _employeepuid = new Guid(_user.ObjectId.ToString()); List<ReferencedObject> directReports = _restAPI.GetLinks(_employeepuid, "DirectReports"); List<ReferencedObject> manager = _restAPI.GetLinks(_employeepuid, "Manager"); if (manager != null && manager.Count != 0) { new Guid(manager[0].ObjectId.ToString()); } }
// You Could use [Authorize(Roles=)] Tags here instead of IsInRole below public ActionResult GetUserGroups() { var usergroups = new List <UserGroup>(); ViewBag.GetGroupsStatus = ""; // It is up to the application to ensure that only admins can read groups. if (!User.Identity.IsAuthenticated || !User.IsInRole(RocRole.Admin)) { ViewBag.GetGroupsStatus = "You must sign in as an admin to view Groups."; return(View(usergroups)); } try { // Get a token for the Graph API in the context of the user's tenant. Admins from hospital A can't see groups in hopital B. ClientCredential cc = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientId"], ConfigurationManager.AppSettings["ida:AppKey"]); IClaimsIdentity ci = User.Identity as IClaimsIdentity; Claim tid = ci.Claims.Where(c => c.ClaimType == "http://schemas.microsoft.com/identity/claims/tenantid").First(); AuthenticationContext authContext = new AuthenticationContext(String.Format(TenantConfig.authorityFormat, tid.Value)); AuthenticationResult ar = authContext.AcquireToken(TenantConfig.graphResourceId, cc); HttpClient httpClient = new HttpClient(); string graphRequest = TenantConfig.graphEndpoint + tid.Value + "/groups?api-version=" + TenantConfig.graphApiVersion; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, graphRequest); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ar.AccessToken); HttpResponseMessage response = httpClient.SendAsync(request).Result; if (response.IsSuccessStatusCode) { JavaScriptSerializer jss = new JavaScriptSerializer(); string serializedJson = response.Content.ReadAsStringAsync().Result; GraphGroupResult ggr = jss.Deserialize <GraphGroupResult>(serializedJson); foreach (Value group in ggr.value) { usergroups.Add(new UserGroup { Id = group.objectId, Name = group.displayName }); } } else { throw new WebException(response.Content.ReadAsStringAsync().Result); } } catch (Exception ex) { // A tenant admin needs to sign up for the app and grant it permission (via consent) before it can write to a tenant. if (ex.Message.Contains("Authorization_IdentityNotFound")) { ViewBag.GetGroupsStatus = "Your admin needs to sign in once before you can get groups."; } ViewBag.GetGroupsStatus = "An error occurred when getting groups: " + ex.Message; } return(View(usergroups)); }
public FindUserDetailsResponse FindUserDetails(FindUserDetailsRequest request) { IClaimsIdentity identity = (IClaimsIdentity)Thread.CurrentPrincipal.Identity; string upn = identity.Claims.FindAll(c => { return(c.ClaimType == ClaimTypes.Upn); }).First().Value; AuthenticationActions.FindUserDetailsAction action = PolicyInjection.Create <AuthenticationActions.FindUserDetailsAction>(); AuthenticationEntities.FindUserDetailsParameters parameters = Translators.FindUserDetailsTranslator.TranslateFromServiceToBusiness(request.FindUserDetailsParameters); parameters.UserPrincipalIdentity = upn; /* user@domain */ parameters.UserIdentity = upn.Split('@')[0]; AuthenticationEntities.FindUserDetailsResult r = action.Execute(parameters); FindUserDetailsResponse response = new FindUserDetailsResponse(); response.FindUserDetailsResult = GenericMapper.MapNew <DataContracts.FindUserDetailsResult>(r); response.FindUserDetailsResult.UserWarehouses = GenericMapper.MapListNew <DataContracts.UserWarehouseCollection, AuthenticationEntities.FindUserWarehousesResult, DataContracts.UserWarehouse>( r.Warehouses, Translators.FindUserDetailsTranslator.TranslateFromBusinessToService); response.FindUserDetailsResult.UserCompanies = GenericMapper.MapListNew <DataContracts.UserCompanyCollection, AuthenticationEntities.FindUserCompaniesResult, DataContracts.UserCompany>( r.Companies, Translators.FindUserDetailsTranslator.TranslateFromBusinessToService); return(response); }
/// <summary> /// This method returns the claims to be included in the issued token. /// </summary> /// <param name="scope">The scope that was previously returned by GetScope method</param> /// <param name="principal">The caller's principal</param> /// <param name="request">The incoming RST</param> /// <returns>The claims to be included in the issued token.</returns> protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { IClaimsIdentity callerIdentity = (IClaimsIdentity)principal.Identity; Console.WriteLine("\nRequest from: " + callerIdentity.Name + "\n"); IClaimsIdentity outputIdentity = new ClaimsIdentity(); // Create a name claim from the incoming identity. Claim nameClaim = new Claim(ClaimTypes.Name, callerIdentity.Name); // Create an 'Age' claim with a value of 25. In a real scenario, this may likely be looked up from a database. Claim ageClaim = new Claim("http://WindowsIdentityFoundationSamples/2008/05/AgeClaim", "25", ClaimValueTypes.Integer); outputIdentity.Claims.Add(nameClaim); Console.WriteLine("ClaimType : " + nameClaim.ClaimType); Console.WriteLine("ClaimValue : " + nameClaim.Value); Console.WriteLine(); Console.WriteLine("ClaimType : " + ageClaim.ClaimType); Console.WriteLine("ClaimValue : " + ageClaim.Value); Console.WriteLine("==========================="); outputIdentity.Claims.Add(ageClaim); return(outputIdentity); }
protected override bool AuthorizeTokenIssuance(Collection <Claim> resource, IClaimsIdentity id) { if (!ConfigurationRepository.Configuration.EnforceUsersGroupMembership) { var authResult = id.IsAuthenticated; if (!authResult) { Tracing.Error("Authorization for token issuance failed because the user is anonymous"); } return(authResult); } var section = ConfigurationManager.GetSection(ActiveDirectoryConfigurationSection.SectionName) as ActiveDirectoryConfigurationSection; var roleResult = false; foreach (UserGroupConfigElement group in section.UserGroups) { roleResult = id.ClaimExists(ClaimTypes.Role, group.UserGroupName); if (roleResult) { break; } } return(roleResult); }
/// <summary> /// Determines whether this claims identity has a claim that is matched by the specified predicate. /// </summary> /// <param name="identity"><see cref="IClaimsIdentity"/> identity object.</param> /// <param name="match">The function that performs the matching logic.</param> /// <returns><c>true</c> if a matching claim exists; otherwise, <c>false</c>.</returns> /// <exception cref="ArgumentNullException">Throw when <paramref name="identity"/> or <paramref name="match"/> is <c>null</c> reference.</exception> public static bool HasClaim(this IClaimsIdentity identity, Predicate <Claim> match) { if (identity == null) { throw new ArgumentNullException("identity"); } if (match == null) { throw new ArgumentNullException("match"); } if (identity.Claims == null) { return(false); } foreach (Claim claim in identity.Claims) { if (match(claim)) { return(true); } } return(false); }
private static void CopyClaims(IClaimsIdentity source, IClaimsIdentity target) { foreach (var claim in source.Claims) { // We don't copy the issuer because it is not needed in this case. The STS always issues claims // using its own identity. var newClaim = new Claim(claim.ClaimType, claim.Value, claim.ValueType); // copy all claim properties foreach (var key in claim.Properties.Keys) { newClaim.Properties.Add(key, claim.Properties[key]); } // add claim to the destination identity target.Claims.Add(newClaim); } // Recursively copy claims from the source identity delegates if (source.Actor != null) { target.Actor = new ClaimsIdentity(); CopyClaims(source.Actor, target.Actor); } }
/// <summary> /// Determines whether this claims identity has a claim with the specified claim type and value. /// </summary> /// <param name="identity"><see cref="IClaimsIdentity"/> identity object.</param> /// <param name="type">The type of the claim to match.</param> /// <param name="value">The value of the claim to match.</param> /// <returns><c>true</c> if a match is found; otherwise, <c>false</c>.</returns> /// <exception cref="ArgumentNullException">Throw when <paramref name="identity"/>, <paramref name="type"/> or <paramref name="value"/> is <c>null</c> reference.</exception> public static bool HasClaim(this IClaimsIdentity identity, string type, string value) { if (identity == null) { throw new ArgumentNullException("identity"); } if (type == null) { throw new ArgumentNullException("type"); } if (value == null) { throw new ArgumentNullException("value"); } if (identity.Claims == null) { return(false); } foreach (Claim claim in identity.Claims) { if (string.Equals(claim.ClaimType, type, StringComparison.OrdinalIgnoreCase) && string.Equals(claim.Value, value, StringComparison.Ordinal)) { return(true); } } return(false); }
protected void Page_Load(object sender, EventArgs e) { // Gets the thread's current principal IClaimsPrincipal claimsPrincipal = Thread.CurrentPrincipal as IClaimsPrincipal; // Access the interface IClaimsIdentity, which contains claims IClaimsIdentity claimsIdentity = (IClaimsIdentity)claimsPrincipal.Identity; // Access claims that associated with claims identity object foreach (Claim claim in claimsIdentity.Claims) { // Display claim type and value //Response.Write("Claim Type: " + claim.ClaimType + "</br>"); //Response.Write("Claim Value: " + claim.Value + "</br>"); // Get claims and store it in array list switch (claim.ClaimType) { case ClaimTypes.Email: case ClaimTypes.Name: case ClaimTypes.GivenName: case ClaimTypes.Role: case ClaimTypes.Prip.CommonName: alClaims.Add(new ClaimInfo(claim.ClaimType, claim.Value)); break; } // TODO //... } this.Repeater1.DataSource = alClaims; this.Repeater1.DataBind(); }
private bool CheckItemLevelAccess(RouteData routeData, IClaimsIdentity identity) { object id; var resourceId = Guid.Empty; // Get name identifier and identity provider var nameIdentifierClaim = identity.Claims.SingleOrDefault(c => c.ClaimType.Equals(ClaimTypes.NameIdentifier, StringComparison.OrdinalIgnoreCase)); var identityProviderClaim = identity.Claims.SingleOrDefault(c => c.ClaimType.Equals(AccountAssociationClaimsAuthenticationManager.IdentityProviderClaimType, StringComparison.OrdinalIgnoreCase)); if (routeData.Values.TryGetValue("BlobId", out id)) { // trying to access a blob, verify access if (Guid.TryParse(id.ToString(), out resourceId)) { return this.permissionService.CheckPermissionToBlob(nameIdentifierClaim.Value, identityProviderClaim.Value, resourceId); } } else if (routeData.Values.TryGetValue("blobSetId", out id)) { // trying to access a blob set, verify access if (Guid.TryParse(id.ToString(), out resourceId)) { return this.permissionService.CheckPermissionToBlobSet(nameIdentifierClaim.Value, identityProviderClaim.Value, resourceId); } } // not requesting for a resource return true; }
public ICredentials GetCredentials(Uri uri, ICredentials failedCredentials) { //If we're running under Claims authentication, impersonate the thread user //by calling the Claims to Windows Token Service and call the remote site using //the impersonated credentials. NOTE: The Claims to Windows Token Service must be running. if (Thread.CurrentPrincipal.Identity is ClaimsIdentity) { IClaimsIdentity identity = (ClaimsIdentity)System.Threading.Thread.CurrentPrincipal.Identity; var firstClaim = identity.Claims.FirstOrDefault(c => c.ClaimType == ClaimTypes.Upn); if (firstClaim == null) { throw new InvalidOperationException("No UPN claim found"); } string upn = firstClaim.Value; if (String.IsNullOrEmpty(upn)) { throw new InvalidOperationException("A UPN claim was found, however, the value was empty."); } var currentIdentity = S4UClient.UpnLogon(upn); m_ctxt = currentIdentity.Impersonate(); } return(CredentialCache.DefaultNetworkCredentials); }
/// <summary> /// Retrieves all of the claims that are matched by the specified predicate. /// </summary> /// <param name="identity"><see cref="IClaimsIdentity"/> identity object.</param> /// <param name="match">The function that performs the matching logic.</param> /// <returns>The matching claims. The list is read-only.</returns> /// <exception cref="ArgumentNullException">Throw when <paramref name="identity"/> or <paramref name="match"/> is <c>null</c> reference.</exception> public static IEnumerable <Claim> FindAll(this IClaimsIdentity identity, Predicate <Claim> match) { if (identity == null) { throw new ArgumentNullException("identity"); } if (match == null) { throw new ArgumentNullException("match"); } var list = new List <Claim>(); if (identity.Claims != null) { foreach (Claim claim in identity.Claims) { if (match(claim)) { list.Add(claim); } } } return(list.AsReadOnly()); }
/// <summary> /// Retrieves the first claim with the specified claim type. /// </summary> /// <param name="identity"><see cref="IClaimsIdentity"/> identity object.</param> /// <param name="type">The claim type to match.</param> /// <returns>The first matching claim or <c>null</c> if no match is found.</returns> /// <exception cref="ArgumentNullException">Throw when <paramref name="identity"/> or <paramref name="type"/> is <c>null</c> reference.</exception> public static Claim FindFirst(this IClaimsIdentity identity, string type) { if (identity == null) { throw new ArgumentNullException("identity"); } if (type == null) { throw new ArgumentNullException("type"); } if (identity.Claims == null) { return(null); } foreach (Claim claim in identity.Claims) { if (string.Equals(claim.ClaimType, type, StringComparison.OrdinalIgnoreCase)) { return(claim); } } return(null); }
protected override void OnPreRender(EventArgs e) { var UserClaims = new List <ClaimTypeListItem>(); IIdentity identity = this.Page.User.Identity; if (identity is IClaimsIdentity) { IClaimsIdentity claimsIdentity = (IClaimsIdentity)identity; foreach (var claim in claimsIdentity.Claims) { UserClaims.Add( new ClaimTypeListItem { ClaimType = claim.ClaimType, ClaimValue = claim.Value }); } TokenID.Text = claimsIdentity.BootstrapToken.Id; TokenValidFrom.Text = claimsIdentity.BootstrapToken.ValidFrom.ToString(); TokenValidTo.Text = claimsIdentity.BootstrapToken.ValidTo.ToString(); } grdClaims.DataSource = UserClaims.OrderByDescending(claim => claim.ClaimType); grdClaims.DataBind(); }
protected override void OnPreRender(EventArgs e) { IClaimsPrincipal claimsPrincipal = Page.User as IClaimsPrincipal; IClaimsIdentity claimsIdentity = (IClaimsIdentity)claimsPrincipal.Identity; bool isLid = Page.User.IsInRole("Leden"); //List<Claim> UserClaims = new List<Claim>(); IIdentity identity = this.Page.User.Identity; /* * if (identity is IClaimsIdentity) * { * IClaimsIdentity claimsIdentity = (IClaimsIdentity)identity; * foreach (var claim in claimsIdentity.Claims) * { * UserClaims.Add( * new ClaimTypeListItem * { * ClaimType = claim.ClaimType, * ClaimValue = claim.Value * }); * } * } */ grdClaims.DataSource = claimsIdentity.Claims; grdClaims.DataBind(); //base.OnPreRender(e); }
public string GetAccessToken(IClaimsIdentity identity) { var accessToken = (from claim in identity.Claims where claim.ClaimType == "http://www.facebook.com/claims/AccessToken" select (string)claim.Value).FirstOrDefault(); return accessToken; }
private bool CheckItemLevelAccess(RouteData routeData, IClaimsIdentity identity) { object id; var resourceId = Guid.Empty; // Get name identifier and identity provider var nameIdentifierClaim = identity.Claims.SingleOrDefault(c => c.ClaimType.Equals(ClaimTypes.NameIdentifier, StringComparison.OrdinalIgnoreCase)); var identityProviderClaim = identity.Claims.SingleOrDefault(c => c.ClaimType.Equals(AccountAssociationClaimsAuthenticationManager.IdentityProviderClaimType, StringComparison.OrdinalIgnoreCase)); if (routeData.Values.TryGetValue("BlobId", out id)) { // trying to access a blob, verify access if (Guid.TryParse(id.ToString(), out resourceId)) { return(this.permissionService.CheckPermissionToBlob(nameIdentifierClaim.Value, identityProviderClaim.Value, resourceId)); } } else if (routeData.Values.TryGetValue("blobSetId", out id)) { // trying to access a blob set, verify access if (Guid.TryParse(id.ToString(), out resourceId)) { return(this.permissionService.CheckPermissionToBlobSet(nameIdentifierClaim.Value, identityProviderClaim.Value, resourceId)); } } // not requesting for a resource return(true); }
protected void Page_Load(object sender, EventArgs e) { // Zero code was required for doing authorization, only assiging users to app roles in the Azure Portal. bool isAuthorizedUser = User.IsInRole(RocRole.User) || User.IsInRole(RocRole.Manager) || User.IsInRole(RocRole.Admin); bool isPowerUser = User.IsInRole(RocRole.Manager) || User.IsInRole(RocRole.Admin); bool isSuperUser = User.IsInRole(RocRole.Admin); btn_Admin.Enabled = isSuperUser; btn_Manager.Enabled = isPowerUser; btn_User.Enabled = isAuthorizedUser; txtSaml.Text = @"Please login to view SAML token content."; // The SAML token content is automatically populated in the ClaimsIdentity. if (User.Identity.IsAuthenticated) { var samlText = string.Empty; IClaimsIdentity ci = Thread.CurrentPrincipal.Identity as IClaimsIdentity; foreach (Claim claim in ci.Claims) { samlText += claim.ClaimType + ": " + claim.Value + "\n\n"; } txtSaml.Text = samlText; } }
/// <summary> /// Retrieves the first claim that is matched by the specified predicate. /// </summary> /// <param name="identity"><see cref="IClaimsIdentity"/> identity object.</param> /// <param name="match">The function that performs the matching logic.</param> /// <returns>The first matching claim or <c>null</c> if no match is found.</returns> /// <exception cref="ArgumentNullException">Throw when <paramref name="identity"/> or <paramref name="match"/> is <c>null</c> reference.</exception> public static Claim FindFirst(this IClaimsIdentity identity, Predicate <Claim> match) { if (identity == null) { throw new ArgumentNullException("identity"); } if (match == null) { throw new ArgumentNullException("match"); } if (identity.Claims == null) { return(null); } foreach (Claim claim in identity.Claims) { if (match(claim)) { return(claim); } } return(null); }
public ActionResult Index(string createUserStatus, string userCreatedStatus) { ViewBag.SamlContent = "Please login to view SAML token content."; ViewBag.CreateUserStatus = ""; ViewBag.UserCreatedStatus = ""; // The SAML token contents are automatically populated in the ClaimsIdentity. if (Request.IsAuthenticated) { var samlText = string.Empty; IClaimsIdentity ci = Thread.CurrentPrincipal.Identity as IClaimsIdentity; foreach (Claim claim in ci.Claims) { samlText += claim.ClaimType + ": " + claim.Value + "\n\n"; } ViewBag.SamlContent = samlText; } if (createUserStatus != string.Empty) { ViewBag.CreateUserStatus = createUserStatus; } if (userCreatedStatus != string.Empty) { ViewBag.UserCreatedStatus = userCreatedStatus; } return(View()); }
protected static WindowsIdentity RetrieveWindowsIdentityForCurrentUserBasedOnClaim() { IClaimsIdentity identity = Thread.CurrentPrincipal.Identity as ClaimsIdentity; if (identity == null) { throw new InvalidOperationException("Current Thread Identity is not a valid Claims Identity."); } string upn = null; var correctClaimType = identity.Claims.Where(claim => StringComparer.Ordinal.Equals(ClaimTypes.Upn, claim.ClaimType)); correctClaimType.ForEach(c => upn = c.Value); if (string.IsNullOrEmpty(upn)) { throw new InvalidOperationException("Current Thread Identity is not a valid Windows Identity."); } WindowsIdentity windowsIdentity; using (WindowsIdentity.Impersonate(IntPtr.Zero)) windowsIdentity = S4UClient.UpnLogon(upn); return(windowsIdentity); }
/// <summary> /// Validates whether the claim should be associated with a given claims identity. /// </summary> /// <param name="claimsIdentity">Claims identity.</param> /// <returns>True if the cliam should be associated with the given claims identify otherwise false.</returns> public virtual bool Validate(IClaimsIdentity claimsIdentity) { if (claimsIdentity == null || claimsIdentity.Claims == null) { return(false); } if (claimsIdentity.Claims.Any(c => string.Compare(c.ClaimType, ClaimType, StringComparison.Ordinal) == 0)) { return(false); } foreach (var condition in Conditions.OfType <RegularExpressionConfigurationElement>()) { var currentCondition = condition; foreach (var valueClaim in claimsIdentity.Claims.Where(c => string.Compare(c.ClaimType, currentCondition.ValueClaimType, StringComparison.Ordinal) == 0)) { if (string.IsNullOrEmpty(valueClaim.Value)) { continue; } var regex = new Regex(currentCondition.MatchCondition, RegexOptions.None); if (regex.IsMatch(valueClaim.Value)) { return(true); } } } return(false); }
/// <summary> /// Retrieves all of the claims that have the specified claim type. /// </summary> /// <param name="identity"><see cref="IClaimsIdentity"/> identity object.</param> /// <param name="type">The claim type against which to match claims.</param> /// <returns>The matching claims. The list is read-only.</returns> /// <exception cref="ArgumentNullException">Throw when <paramref name="identity"/> or <paramref name="type"/> is <c>null</c> reference.</exception> public static IEnumerable <Claim> FindAll(this IClaimsIdentity identity, string type) { if (identity == null) { throw new ArgumentNullException("identity"); } if (type == null) { throw new ArgumentNullException("type"); } var list = new List <Claim>(); if (identity.Claims != null) { foreach (Claim claim in identity.Claims) { if (string.Equals(claim.ClaimType, type, StringComparison.OrdinalIgnoreCase)) { list.Add(claim); } } } return(list.AsReadOnly()); }
private void TransformIPSTS2Claims(IClaimsIdentity incomingIdentity, ClaimsIdentity outgoingIdentity) { foreach (Claim claim in incomingIdentity.Claims) { // If IPSTS2/myID claim exists transform that to be a UPN format if (claim.ClaimType.Equals(IPSTS2_ID_CLAIM)) { // add the IPSTS claim as well for illustrative purposes outgoingIdentity.Claims.Add(new Claim(FPSTS_ID_CLAIM_FROM_IPSTS2, claim.Value, claim.ValueType)); // value transform outgoingIdentity.Claims.Add(new Claim(FPSTS_UPN_CLAIM, claim.Value + "@fabrikam.com", ClaimValueTypes.String)); } else if (claim.ClaimType.Equals(IPSTS2_ZIPCODE_CLAIM)) { // add the IPSTS claim as well for illustrative purposes outgoingIdentity.Claims.Add(new Claim(FPSTS_ZIPCODE_CLAIM_FROM_IPSTS2, claim.Value, claim.ValueType)); // new claim type outgoingIdentity.Claims.Add(new Claim(FPSTS_CITY_CLAIM, "Redmond WA", ClaimValueTypes.String)); } else if (claim.ClaimType.Equals(IPSTS2_IDENTIFIER_CLAIM)) { // add the IPSTS claim as well for illustrative purposes outgoingIdentity.Claims.Add(new Claim(FPSTS_IDENTIFIER_CLAIM, claim.Value, claim.ValueType)); // no transformation is performed here } else if (claim.ClaimType.Equals(ClaimTypes.Name)) { // add the name claim received from IPSTS outgoingIdentity.Claims.Add(new Claim(ClaimTypes.Name, claim.Value, claim.ValueType)); } } }
public ActionResult DownloadBlob(Guid blobId) { IClaimsIdentity identity = (IClaimsIdentity)User.Identity; // Get name identifier and identity provider var nameIdentifierClaim = identity.Claims.Where(c => c.ClaimType.Equals(ClaimTypes.NameIdentifier, StringComparison.OrdinalIgnoreCase)).SingleOrDefault(); var identityProviderClaim = identity.Claims.Where(c => c.ClaimType.Equals(IdentityProviderClaimType, StringComparison.OrdinalIgnoreCase)).SingleOrDefault(); var blob = this.blobService.GetBlobById(blobId); this.eventService.CreateEventUserDownloadBlob(nameIdentifierClaim.Value, identityProviderClaim.Value, blob); if (blob == null) { return(new RedirectResult("~/404.htm")); } Response.ContentType = this.blobService.GetContentType(blob); Response.AddHeader("Content-disposition", "attachment; filename=" + blob.OriginalFileName); var blob2 = this.blobService.GetBlob(blob); blob2.DownloadToStream(Response.OutputStream); return(null); }
/// <summary> /// Tries to retrieve the clients ClaimsIdentity from the current request context. /// </summary> /// <param name="identity">The identity.</param> /// <returns>True when a valid identity was found - otherwise false.</returns> public virtual bool TryGetClaimsIdentity(out IClaimsIdentity identity) { identity = null; // check header first - authorization and x-authorization var authZheader = HttpContext.Current.Request.Headers["cf-Authorization"]; if (!string.IsNullOrEmpty(authZheader)) { try { if (authZheader.StartsWith("cfST=")) { var tokenString = authZheader.Substring("cfST=".Length); var samlToken = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers.ReadToken(new XmlTextReader(new StringReader(tokenString))); identity = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers.ValidateToken(samlToken).First(); } else { throw new AccessViolationException("Client usage of cf-Auth is invalid. This request has been logged & legal action will be taken if the client illegally access Climbfinds systems"); } return(true); } catch { return(false); } } return(false); }
protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope) { if (principal == null) { throw new ArgumentNullException("incomingPrincipal"); } // We should have only one Identity. if (principal.Identities.Count != 1) { throw new ArgumentException("incomingPrincipal"); } IClaimsIdentity identity = principal.Identities[0]; string experienceClass = "Beginner"; experienceClassMap.TryGetValue(identity.Name, out experienceClass); return(new ClaimsIdentity( new Claim[] { new Claim(WSIdentityConstants.ClaimTypes.Name, identity.Name), new Claim(PetShopClaimTypes.ExperienceClass, experienceClass) })); }
private string GetIdentity() { string identityName = String.Empty; IClaimsIdentity claimsIdentity = Thread.CurrentPrincipal.Identity as IClaimsIdentity; if (claimsIdentity != null) { // claims identity processing foreach (Claim claim in claimsIdentity.Claims) { if (string.Equals(IdentityClaimType, claim.ClaimType, StringComparison.OrdinalIgnoreCase)) { identityName = claim.Value; break; } } } else { // non claims identity processing identityName = Thread.CurrentPrincipal.Identity.Name; } return(identityName); }
public IdentityClaim(IClaimsIdentity identity) { if (identity != null) { foreach (var claim in identity.Claims) { if (claim.ClaimType == ClaimTypes.NameIdentifier) { IdentityValue = claim.Value; } if (claim.ClaimType == ACSProviderClaim) { IdentityProvider = claim.Value; } if(claim.ClaimType == ClaimTypes.Email) { Email = claim.Value; } if(claim.ClaimType == ClaimTypes.Name) { Name = claim.Value; } } } }
private void Initialize() { _claimsIdentity = ((IClaimsPrincipal)(Thread.CurrentPrincipal)).Identities[0]; foreach (var c in _claimsIdentity.Claims) { _strClaimType = c.ClaimType; if (_strClaimType.EndsWith("domain")) { _domain = c.Value; } if (_strClaimType.EndsWith("EmailAddress")) { _email = c.Value; } } _user = _restAPI.GetUserByEmail(_email); _employeepuid = new Guid(_user.ObjectId.ToString()); List <ReferencedObject> directReports = _restAPI.GetLinks(_employeepuid, "DirectReports"); List <ReferencedObject> manager = _restAPI.GetLinks(_employeepuid, "Manager"); if (manager != null && manager.Count != 0) { new Guid(manager[0].ObjectId.ToString()); } }
protected virtual bool AuthorizeTokenIssuance(Collection<Claim> resource, IClaimsIdentity id) { var configurationRepository = ConfigurationRepositoryFactoryMethod(); if (!configurationRepository.Configuration.EnforceUsersGroupMembership) { return id.IsAuthenticated; } return (id.ClaimExists(ClaimTypes.Role, Constants.Roles.IdentityServerUsers)); }
private static void PrintClaimsTable(StringBuilder sb, IClaimsIdentity identity) { sb.Append("<table style='width:100%;'><tr><th>Claim Type</th>" + "<th>Claim Value</th><th>Claim Issuer</th></tr>\n"); foreach (Claim claim in identity.Claims) { sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>\n", claim.ClaimType, claim.Value, claim.Issuer); } sb.Append("</table>\n"); }
/// <summary> /// Creates a bearer SAML security token from an IClaimsIdentity /// </summary> /// <param name="identity">The identity.</param> /// <returns>A self-generated SAML bearer token</returns> public static SamlSecurityToken CreateToken(IClaimsIdentity identity) { var description = new SecurityTokenDescriptor { Subject = identity, TokenIssuerName = "http://self" }; var handler = new Saml11SecurityTokenHandler(); return (SamlSecurityToken)handler.CreateToken(description); }
protected override void EstablishContext() { containerMock = new WindsorContainer(); claimsAuthenticationManagerProvider = mocks.StrictMock<IClaimsAuthenticationManagerProvider>(); claimsPrincipal = mocks.DynamicMock<IClaimsPrincipal>(); notClaimsIdnentity = mocks.StrictMock<IAmNotClaimsIdenitty>(); claimsIdentity = mocks.StrictMock<IClaimsIdentity>(); containerMock.Register(Component.For<IClaimsAuthenticationManagerProvider>().Instance(claimsAuthenticationManagerProvider)); IoC.Initialize(containerMock); }
public SamlSecurityToken CreateToken(IClaimsIdentity identity) { var description = new SecurityTokenDescriptor { Subject = identity, TokenIssuerName = _issuer }; //var handler = new Saml2SecurityTokenHandler(); //return (SamlSecurityToken)handler.CreateToken(description); return (SamlSecurityToken)CreateToken(description); }
protected virtual bool AuthorizeCore(Claim action, Collection<Claim> resource, IClaimsIdentity id) { switch (action.Value) { case Constants.Actions.Issue: return AuthorizeTokenIssuance(resource, id); case Constants.Actions.Administration: return AuthorizeAdministration(resource, id); } return false; }
private void Initializer() { _claimsIdentity = ((IClaimsPrincipal)(Thread.CurrentPrincipal)).Identities[0]; if (_claimsIdentity != null) foreach (var c in _claimsIdentity.Claims) { _strClaimType = c.ClaimType; if (_strClaimType.EndsWith("EmailAddress")) _email = c.Value; } }
private IClaimsPrincipal CreateClientIdentity(IClaimsIdentity id) { // hard coded for demo purposes var claims = new List<Claim> { new Claim(ClaimTypes.Name, id.Name), new Claim(ClaimTypes.Role, "Users"), new Claim(ClaimTypes.Role, "Geek"), new Claim(ClaimTypes.Email, id.Name + "@thinktecture.com") }; var claimsIdentity = new ClaimsIdentity(claims, "Federation"); return ClaimsPrincipal.CreateFromIdentity(claimsIdentity); }
protected override void EstablishContext() { staffInformationProvider = mocks.Stub<IStaffInformationProvider>(); authenticationProvider = mocks.Stub<IAuthenticationProvider>(); dashboardUserClaimsInformationProvider = mocks.Stub<IDashboardUserClaimsInformationProvider<EdFiUserSecurityDetails>>(); httpRequestProvider = mocks.Stub<IHttpRequestProvider>(); identity = mocks.Stub<IClaimsIdentity>(); principal = mocks.Stub<IClaimsPrincipal>(); Expect.Call(identity.Name).Return(userName); Expect.Call(principal.Identity).Return(identity); Expect.Call(staffInformationProvider.ResolveStaffUSI(authenticationProvider, userName)).Return(staffUSI); }
private static void logClaimsIdentity(IClaimsIdentity ci, CustomTextTraceSource ts) { ts.TraceInformation("claimsIdentity: " + ci.Name); foreach (Claim c in ci.Claims) { ts.TraceInformation("Claim: <{0}, {1}>", c.ClaimType, c.Value); } // delegate if ( ci.Actor != null ) { ts.TraceInformation("\nDelegate:"); logClaimsIdentity(ci.Actor, ts); } }
private static string GetAnyOfTheseClaims(IClaimsIdentity identity, params string[] claimTypes) { // try first with the specified claimtypes foreach (var claimType in claimTypes) { Claim claim = identity.Claims.SingleOrDefault(c => c.ClaimType.Equals(claimType, StringComparison.OrdinalIgnoreCase)); if (claim != null) { // return the first claimtype found return claim.Value; } } return null; }
protected override void EstablishContext() { base.EstablishContext(); staffInformationProvider = mocks.Stub<IStaffInformationProvider>(); authenticationProvider = mocks.Stub<IAuthenticationProvider>(); userClaimsProvider = mocks.DynamicMock<IUserClaimsProvider>(); identity = mocks.Stub<IClaimsIdentity>(); principal = mocks.Stub<IClaimsPrincipal>(); Expect.Call(identity.Name).Return(userName); Expect.Call(principal.Identity).Return(identity); Expect.Call(staffInformationProvider.ResolveStaffUSI(authenticationProvider, userName)).Return(staffUSI); }
protected override bool AuthorizeAdministration(Collection<Claim> resource, IClaimsIdentity id) { var section = ConfigurationManager.GetSection(ActiveDirectoryConfigurationSection.SectionName) as ActiveDirectoryConfigurationSection; var roleResult = id.ClaimExists(ClaimTypes.Role, section.AdministrationGroup.AdministrationGroupName); if (!roleResult) { if (resource[0].Value != Constants.Resources.UI) { Tracing.Error(string.Format("Administration authorization failed because user {0} is not in the {1} role", id.Name, section.AdministrationGroup.AdministrationGroupName)); } } return roleResult; }
protected override void EstablishContext() { claimsIdentity = mocks.Stub<IClaimsIdentity>(); suppliedClaims = GetDefaultClaims(IncludeLeaClaim(), IncludeLeaCodeClaim()); suppliedClaimsCollect = new ClaimCollection(claimsIdentity); suppliedClaimsCollect.AddRange(suppliedClaims); identityCollection = new ClaimsIdentityCollection(Enumerable.Repeat(claimsIdentity, 1)); Expect.Call(claimsIdentity.Claims).Return(suppliedClaimsCollect); principal = mocks.Stub<IClaimsPrincipal>(); Expect.Call(principal.Identity).Return(claimsIdentity); Expect.Call(principal.Identities).Return(identityCollection); }
public static void LogClaimsIdentity(IClaimsIdentity ci, string fromMethod) { CustomTextTraceSource ts = new CustomTextTraceSource(fromMethod, "MyTraceSource", System.Diagnostics.SourceLevels.Information); try { ts.TraceInformation("Method {0}", fromMethod); logClaimsIdentity(ci, ts); } catch (Exception e) { ts.TraceInformation("Exception:" + e.Message); if (e.InnerException != null) { ts.TraceInformation("\tInnerException:" + e.InnerException.Message); } } }
// sample implementation - do not use for production ;) protected override bool ValidateUser(ClaimsIdentity id, out IClaimsIdentity newIdentity) { newIdentity = null; var usernameClaim = id.Claims.First(c => c.ClaimType == WSIdentityConstants.ClaimTypes.Name); var passwordClaim = id.Claims.First(c => c.ClaimType == _passwordClaimType); var customerIdClaim = id.Claims.First(c => c.ClaimType == _customerIdClaimType); if (usernameClaim.Value == passwordClaim.Value) { newIdentity = new ClaimsIdentity(new Claim[] { usernameClaim, customerIdClaim }, "ClientSaml"); return true; } return false; }
protected virtual bool AuthorizeTokenIssuance(Collection<Claim> resource, IClaimsIdentity id) { if (!ConfigurationRepository.Configuration.EnforceUsersGroupMembership) { var authResult = id.IsAuthenticated; if (!authResult) { Tracing.Error("Authorization for token issuance failed because the user is anonymous"); } return authResult; } var roleResult = id.ClaimExists(ClaimTypes.Role, Constants.Roles.IdentityServerUsers); if (!roleResult) { Tracing.Error(string.Format("Authorization for token issuance failed because user {0} is not in the {1} role", id.Name, Constants.Roles.IdentityServerUsers)); } return roleResult; }
private IClaimsPrincipal CreateClientIdentity(IClaimsIdentity id) { var claims = new List<Claim>(); // insert authentication method (windows, passsword, x509) as a claim var authMethod = id.Claims.SingleOrDefault(c => c.ClaimType == ClaimTypes.AuthenticationMethod); if (authMethod == null) { authMethod = new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Unspecified); } // hard coded for demo purposes if (id.Name == "dominick") { claims = new List<Claim> { new Claim(ClaimTypes.Name, id.Name), new Claim(ClaimTypes.Role, "Users"), new Claim(Constants.ClaimTypes.ReportsTo, "christian"), new Claim(ClaimTypes.Email, id.Name + "@thinktecture.com"), authMethod }; } else { claims = new List<Claim> { new Claim(ClaimTypes.Name, id.Name), new Claim(ClaimTypes.Role, "Users"), new Claim(ClaimTypes.Email, id.Name + "@thinktecture.com"), authMethod }; } var claimsIdentity = new ClaimsIdentity(claims, "Federation"); return ClaimsPrincipal.CreateFromIdentity(claimsIdentity); }
protected override bool AuthorizeTokenIssuance(Collection<Claim> resource, IClaimsIdentity id) { if (!ConfigurationRepository.Configuration.EnforceUsersGroupMembership) { var authResult = id.IsAuthenticated; if (!authResult) { Tracing.Error("Authorization for token issuance failed because the user is anonymous"); } return authResult; } var section = ConfigurationManager.GetSection(ActiveDirectoryConfigurationSection.SectionName) as ActiveDirectoryConfigurationSection; var roleResult = false; foreach (UserGroupConfigElement group in section.UserGroups) { roleResult = id.ClaimExists(ClaimTypes.Role, group.UserGroupName); if (roleResult) break; } return roleResult; }
private void Initializer() { _claimsIdentity = ((IClaimsPrincipal)(Thread.CurrentPrincipal)).Identities[0]; // We get the domain from the Claim. This is what we use to match against the domain returned in queries to the Graph API // to ensure multipe tenants can use the application. // foreach (var c in _claimsIdentity.Claims) { _strClaimType = c.ClaimType; if (_strClaimType.EndsWith("domain")) _domain = c.Value; } }
/// <summary> /// // extensibility point for authentication and claims filtering. /// </summary> /// <param name="id">The incoming identity.</param> /// <param name="newIdentity">The application identity.</param> /// <returns>Returns true when user validation succeeded - otherwise false.</returns> protected abstract bool ValidateUser(ClaimsIdentity id, out IClaimsIdentity newIdentity);
//protected override RequestSecurityTokenResponse GetResponse(RequestSecurityToken request, // Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor tokenDescriptor) //{ // CustomAdsTextTraceSource ts = new CustomAdsTextTraceSource("IdpAds.CustomSecurityTokenService.GetResponse", // "AdsTraceSource", SourceLevels.Information); // RequestSecurityTokenResponse rstr = base.GetResponse(request, tokenDescriptor); // // Need to add the RequestSecurityToken's OnBehalfOf element to RequestSecurityTokenResponse // SecurityTokenElement onBehalfOfElement = request.OnBehalfOf; // // GFIPM S2S 8.8.2.8.d // // serialize the OnBehalfOf element to the RSTR element // rstr.Properties.Add("OnBehalfOf", onBehalfOfElement.SecurityTokenXml.OuterXml); // return rstr; //} private IClaimsIdentity GetWscClaimsIdentity(IClaimsIdentity wscIdentity) { Claim[] claims = (from c in wscIdentity.Claims where c.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint" select c).ToArray<Claim>(); // must be only one Claim x509ThumbprintClaim = claims[0]; // convert to a hex string since its the standard .Net way to handle x509 thumbprints string x509HexThumbprint = Base64Util.FromBase64ToHex(x509ThumbprintClaim.Value); // get the entityId from the certificate thumbprint // GFIPM S2S 8.8.2.6.d string entityID = _trustFabric.GetWscEntityIdFromX509Thumprint(x509HexThumbprint); IClaimsIdentity claimsIdentity = new ClaimsIdentity(); claimsIdentity.Claims.Add(new Claim(ClaimTypes.Name, entityID)); string now = XmlConvert.ToString(DateTime.UtcNow, DateTimeFormats.Generated); claimsIdentity.Claims.Add(new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(DateTime.UtcNow, DateTimeFormats.Generated))); return claimsIdentity; }
protected virtual bool AuthorizeAdministration(Collection<Claim> resource, IClaimsIdentity id) { return (id.ClaimExists(ClaimTypes.Role, Constants.Roles.IdentityServerAdministrators)); }