/// <summary> /// Custom validation logic for the sign in request. /// </summary> /// <param name="request">The validated request.</param> /// <returns>The validation result</returns> public Task <SignInValidationResult> ValidateSignInRequestAsync(SignInValidationResult request) { return(Task.FromResult(new SignInValidationResult { IsError = false })); }
IHttpActionResult RedirectToLogin(SignInValidationResult result) { Uri publicRequestUri = GetPublicRequestUri(); var message = new SignInMessage(); message.ReturnUrl = publicRequestUri.AbsoluteUri; if (!String.IsNullOrWhiteSpace(result.HomeRealm)) { message.IdP = result.HomeRealm; } if (!String.IsNullOrWhiteSpace(result.Federation)) { message.AcrValues = new[] { result.Federation }; } if (!String.IsNullOrWhiteSpace(result.LoginHint)) { message.LoginHint = result.LoginHint; } var env = Request.GetOwinEnvironment(); var url = env.CreateSignInRequest(message); return(Redirect(url)); }
private async Task <SecurityToken> CreateSecurityTokenAsync(SignInValidationResult result, ClaimsIdentity outgoingSubject) { var credentials = await _keys.GetSigningCredentialsAsync().ConfigureAwait(false); var x509Key = new X509SecurityKey(credentials.Key.GetX509Certificate(_keys)); var relyingParty = result.RelyingParty; var descriptor = new SecurityTokenDescriptor { Audience = result.Client.ClientId, IssuedAt = DateTime.UtcNow, NotBefore = DateTime.UtcNow, Expires = DateTime.UtcNow.AddSeconds(result.Client.IdentityTokenLifetime), SigningCredentials = new SigningCredentials(x509Key, relyingParty.SignatureAlgorithm, relyingParty.DigestAlgorithm), Subject = outgoingSubject, #if DUENDE Issuer = await _issuerNameService.GetCurrentAsync().ConfigureAwait(false), #else Issuer = _contextAccessor.HttpContext.GetIdentityServerIssuerUri(), #endif }; if (result.RelyingParty.EncryptionCertificate != null) { descriptor.EncryptingCredentials = new X509EncryptingCredentials(result.RelyingParty.EncryptionCertificate); } var handler = CreateTokenHandler(result.RelyingParty.TokenType); return(handler.CreateToken(descriptor)); }
private SignInResponseMessage CreateResponse(SignInValidationResult validationResult, SecurityToken token) { var rstr = new RequestSecurityTokenResponse { AppliesTo = new EndpointReference(validationResult.Client.ClientId), Context = validationResult.SignInRequestMessage.Context, ReplyTo = validationResult.ReplyUrl, RequestedSecurityToken = new RequestedSecurityToken(token) }; //var serializer = new WSFederationSerializer( // new WSTrust13RequestSerializer(), // new WSTrust13ResponseSerializer()); // the asp.net core MW does currently not support WS-Trust 1.3 var serializer = new WSFederationSerializer( new WSTrustFeb2005RequestSerializer(), new WSTrustFeb2005ResponseSerializer()); var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager(); mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler(); var responseMessage = new SignInResponseMessage( new Uri(validationResult.ReplyUrl), rstr, serializer, new WSTrustSerializationContext(mgr)); return(responseMessage); }
public async Task <SignInResponseMessage> GenerateResponseAsync(SignInValidationResult validationResult) { Logger.Info("Creating WS-Federation signin response"); // create subject var outgoingSubject = await CreateSubjectAsync(validationResult); // create token for user var token = CreateSecurityToken(validationResult, outgoingSubject); // return response var rstr = new RequestSecurityTokenResponse { AppliesTo = new EndpointReference(validationResult.RelyingParty.Realm), Context = validationResult.SignInRequestMessage.Context, ReplyTo = validationResult.ReplyUrl, RequestedSecurityToken = new RequestedSecurityToken(token) }; var serializer = new WSFederationSerializer( new WSTrust13RequestSerializer(), new WSTrust13ResponseSerializer()); var responseMessage = new SignInResponseMessage( new Uri(validationResult.ReplyUrl), rstr, serializer, new WSTrustSerializationContext()); return(responseMessage); }
private async Task <ClaimsIdentity> CreateSubjectAsync(SignInValidationResult validationResult) { var claims = await _users.GetProfileDataAsync( validationResult.Subject.GetSubjectId(), validationResult.RelyingParty.ClaimMappings.Keys); var mappedClaims = new List <Claim>(); foreach (var claim in claims) { string mappedType; if (validationResult.RelyingParty.ClaimMappings.TryGetValue(claim.Type, out mappedType)) { mappedClaims.Add(new Claim(mappedType, claim.Value)); } } if (validationResult.Subject.GetAuthenticationMethod() == Constants.AuthenticationMethods.Password) { mappedClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password)); mappedClaims.Add(AuthenticationInstantClaim.Now); } return(new ClaimsIdentity(mappedClaims, "idsrv")); }
private static WsFederationMessage CreateResponse(SignInValidationResult validationResult, SecurityToken token) { var handler = CreateTokenHandler(validationResult.RelyingParty.TokenType); var client = validationResult.Client; var message = validationResult.WsFederationMessage; var rstr = new RequestSecurityTokenResponse { CreatedAt = token.ValidFrom, ExpiresAt = token.ValidTo, AppliesTo = client.ClientId, Context = message.Wctx, ReplyTo = validationResult.ReplyUrl, RequestedSecurityToken = token, SecurityTokenHandler = handler, }; var responseMessage = new WsFederationMessage { IssuerAddress = message.Wreply ?? client.RedirectUris.First(), Wa = WsFederationConstants.WsFederationActions.SignIn, Wresult = rstr.Serialize(), Wctx = message.Wctx }; return(responseMessage); }
private async Task <SecurityToken> CreateSecurityTokenAsync(SignInValidationResult result, ClaimsIdentity outgoingSubject) { var credential = await _keys.GetSigningCredentialsAsync(); var key = credential.Key as Microsoft.IdentityModel.Tokens.X509SecurityKey; var descriptor = new SecurityTokenDescriptor { Audience = result.Client.ClientId, IssuedAt = DateTime.UtcNow, NotBefore = DateTime.UtcNow, Expires = DateTime.UtcNow.AddSeconds(result.Client.IdentityTokenLifetime), SigningCredentials = new SigningCredentials(key, result.RelyingParty.SignatureAlgorithm, result.RelyingParty.DigestAlgorithm), Subject = outgoingSubject, Issuer = _contextAccessor.HttpContext.GetIdentityServerIssuerUri(), }; if (result.RelyingParty.EncryptionCertificate != null) { descriptor.EncryptingCredentials = new X509EncryptingCredentials(result.RelyingParty.EncryptionCertificate); } var handler = CreateTokenHandler(result.RelyingParty.TokenType); return(CreateToken(handler, descriptor)); }
public async Task <WsFederationMessage> GenerateResponseAsync(SignInValidationResult validationResult) { _logger.LogDebug("Creating WS-Federation signin response"); // create subject var outgoingSubject = await CreateSubjectAsync(validationResult); // create token for user var token = await CreateSecurityTokenAsync(validationResult, outgoingSubject); // return response return(CreateResponse(validationResult, token)); }
IHttpActionResult RedirectToLogin(CoreSettings settings, SignInValidationResult result) { var message = new SignInMessage(); message.ReturnUrl = Request.RequestUri.AbsoluteUri; if (result.HomeRealm.IsPresent()) { message.IdP = result.HomeRealm; } return(new LoginResult(message, this.Request, settings)); }
private SimpleWebToken CreateToken(string name, IEnumerable <Claim> claims, SignInValidationResult result) { var key = this.HexToByte(result.SiteFinityRelyingParty.Key); var sb = new StringBuilder(); foreach (var c in claims) { sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(c.Type), _httpUtility.UrlEncode(c.Value)); } sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(SitefinityClaimTypes.StsType), "wa"); sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(SitefinityClaimTypes.UserName), name); sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(SitefinityClaimTypes.Domain), result.SiteFinityRelyingParty.Domain); sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(SitefinityClaimTypes.AuthentificationMethod), _httpUtility.UrlEncode("http://schemas.microsoft.com/ws/2008/06/identity/authenticationmethod/password")); sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(SitefinityClaimTypes.AuthentificationInstant), DateTime.UtcNow); //double lifeTimeInSeconds = 3600; var loginDateClaim = claims.FirstOrDefault(x => x.Type == SitefinityClaimTypes.LastLoginDate); DateTime issueDate = DateTime.UtcNow; if (loginDateClaim != null) { if (!DateTime.TryParseExact(loginDateClaim.Value, "u", null, DateTimeStyles.None, out issueDate)) { issueDate = DateTime.UtcNow; } } sb .AppendFormat("TokenId={0}&", _httpUtility.UrlEncode(Guid.NewGuid().ToString())) .AppendFormat("Issuer={0}&", _httpUtility.UrlEncode(result.Issuer)) .AppendFormat("Audience={0}&", _httpUtility.UrlEncode(result.Realm)) .AppendFormat("ExpiresOn={0:0}", (issueDate - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + SimpleWebTokenParser.TokenLifeTime); //.AppendFormat("IssueDate={0:0}", (issueDate - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); var unsignedToken = sb.ToString(); var hmac = new HMACSHA256(key); var sig = hmac.ComputeHash(Encoding.ASCII.GetBytes(unsignedToken)); string signedToken = String.Format("{0}&HMACSHA256={1}", unsignedToken, _httpUtility.UrlEncode(Convert.ToBase64String(sig))); return(_simpleWebTokenParser.GetToken(signedToken)); }
private SecurityToken CreateSecurityToken(SignInValidationResult validationResult, ClaimsIdentity outgoingSubject) { var descriptor = new SecurityTokenDescriptor { AppliesToAddress = validationResult.RelyingParty.Realm, Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(validationResult.RelyingParty.TokenLifeTime)), ReplyToAddress = validationResult.ReplyUrl, SigningCredentials = new X509SigningCredentials(_settings.SigningCertificate), Subject = outgoingSubject, TokenIssuerName = _settings.IssuerUri, TokenType = validationResult.RelyingParty.TokenType }; return(CreateSupportedSecurityTokenHandler().CreateToken(descriptor)); }
IHttpActionResult RedirectToLogin(SignInValidationResult result) { var message = new SignInMessage(); message.ReturnUrl = Request.RequestUri.AbsoluteUri; if (result.HomeRealm.IsPresent()) { message.IdP = result.HomeRealm; } var url = LoginResult.GetRedirectUrl(message, this.Request.GetOwinContext().Environment, _wsFedOptions.DataProtector); return(Redirect(url)); }
public SignInValidationLog(SignInValidationResult result) { if (result.SiteFinityRelyingParty != null) { Realm = result.SiteFinityRelyingParty.Realm; RelyingPartyName = result.SiteFinityRelyingParty.Name; } if (Subject != null) { Subject = result.Subject.GetSubjectId(); } ReplyUrl = result.ReplyUrl; }
public SignInValidationLog(SignInValidationResult result) { if (result.RelyingParty != null) { Realm = result.RelyingParty.Realm; RelyingPartyName = result.RelyingParty.Name; } if (Subject != null) { Subject = result.Subject.GetSubjectId(); } ReplyUrl = result.ReplyUrl; HomeRealm = result.HomeRealm; Federation = result.Federation; }
private SecurityToken CreateSecurityToken(SignInValidationResult validationResult, ClaimsIdentity outgoingSubject) { var descriptor = new SecurityTokenDescriptor { AppliesToAddress = validationResult.RelyingParty.Realm, Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(validationResult.RelyingParty.TokenLifeTime)), ReplyToAddress = validationResult.ReplyUrl, SigningCredentials = new X509SigningCredentials(_options.SigningCertificate, validationResult.RelyingParty.SignatureAlgorithm, validationResult.RelyingParty.DigestAlgorithm), Subject = outgoingSubject, TokenIssuerName = _options.IssuerUri, TokenType = validationResult.RelyingParty.TokenType }; if (validationResult.RelyingParty.EncryptingCertificate != null) { descriptor.EncryptingCredentials = new EncryptedKeyEncryptingCredentials(validationResult.RelyingParty.EncryptingCertificate); } return(CreateSupportedSecurityTokenHandler().CreateToken(descriptor)); }
/// <summary> /// Generate the reponse async /// </summary> /// <param name="message">The request input message</param> /// <param name="result">The validation result</param> /// <param name="request">The original http request</param> /// <returns></returns> public async Task<IHttpActionResult> GenerateResponseAsync(SignInRequestMessage message, SignInValidationResult result,HttpRequestMessage request) { Logger.Info("Creating SiteFinity signin response"); var principal = new ClaimsPrincipal(result.Subject); var identity = ClaimsPrincipal.PrimaryIdentitySelector(principal.Identities); var token = CreateToken(identity.Name, identity.Claims, result); NameValueCollection queryString; if (!String.IsNullOrEmpty(result.ReplyUrl)) { string path; var idx = result.ReplyUrl.IndexOf('?'); if (idx != -1) { path = result.ReplyUrl.Substring(0, idx); queryString = ParseQueryString(result.ReplyUrl.Substring(idx + 1)); } else { path = result.ReplyUrl; queryString = new NameValueCollection(); } WrapSWT(queryString, token, message.Deflate); path = String.Concat(path, ToQueryString(queryString)); var uri = new Uri(new Uri(result.Realm), path); var redirectResult = new RedirectResult(uri,request); return redirectResult; } queryString = new NameValueCollection(); WrapSWT(queryString, token, message.Deflate); var content = new StringContent(ToQueryString(queryString, false), Encoding.UTF8,"application/x-www-form-urlencoded"); var responseMessage = request.CreateResponse(HttpStatusCode.OK,content); return new ResponseMessageResult(responseMessage); }
private async Task <SecurityToken> CreateSecurityTokenAsync(SignInValidationResult result, ClaimsIdentity outgoingSubject) { var credential = await _keys.GetSigningCredentialsAsync(); var key = credential.Key as Microsoft.IdentityModel.Tokens.X509SecurityKey; var descriptor = new SecurityTokenDescriptor { AppliesToAddress = result.Client.ClientId, Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddSeconds(result.Client.IdentityTokenLifetime)), ReplyToAddress = result.Client.RedirectUris.First(), SigningCredentials = new X509SigningCredentials(key.Certificate, result.RelyingParty.SignatureAlgorithm, result.RelyingParty.DigestAlgorithm), Subject = outgoingSubject, TokenIssuerName = _contextAccessor.HttpContext.GetIdentityServerIssuerUri(), TokenType = result.RelyingParty.TokenType }; if (result.RelyingParty.EncryptionCertificate != null) { descriptor.EncryptingCredentials = new EncryptedKeyEncryptingCredentials(result.RelyingParty.EncryptionCertificate); } return(CreateSupportedSecurityTokenHandler().CreateToken(descriptor)); }
private async Task <ClaimsIdentity> CreateSubjectAsync(SignInValidationResult validationResult) { var profileClaims = new List <Claim>(); var mappedClaims = new List <Claim>(); // get all claims from user service if (validationResult.RelyingParty.IncludeAllClaimsForUser) { var ctx = new ProfileDataRequestContext { Subject = validationResult.Subject }; await _users.GetProfileDataAsync(ctx); profileClaims = ctx.IssuedClaims.ToList(); } else { // get only claims that are explicitly mapped (if any) var claimTypes = validationResult.RelyingParty.ClaimMappings.Keys; if (claimTypes.Any()) { var ctx = new ProfileDataRequestContext { Subject = validationResult.Subject, RequestedClaimTypes = claimTypes }; await _users.GetProfileDataAsync(ctx); profileClaims = ctx.IssuedClaims.ToList(); } } foreach (var claim in profileClaims) { string mappedType; // if an explicit mapping exists, use it if (validationResult.RelyingParty.ClaimMappings.TryGetValue(claim.Type, out mappedType)) { // if output claim is a SAML name ID - check is any name ID format is configured if (mappedType == ClaimTypes.NameIdentifier) { var nameId = new Claim(ClaimTypes.NameIdentifier, claim.Value); if (!string.IsNullOrEmpty(validationResult.RelyingParty.SamlNameIdentifierFormat)) { nameId.Properties[ClaimProperties.SamlNameIdentifierFormat] = validationResult.RelyingParty.SamlNameIdentifierFormat; } mappedClaims.Add(nameId); } else { mappedClaims.Add(new Claim(mappedType, claim.Value)); } } else { // otherwise pass-through the claims if flag is set if (validationResult.RelyingParty.IncludeAllClaimsForUser) { string newType = claim.Type; // if prefix is configured, prefix the claim type if (!string.IsNullOrWhiteSpace(validationResult.RelyingParty.DefaultClaimTypeMappingPrefix)) { newType = validationResult.RelyingParty.DefaultClaimTypeMappingPrefix + newType; } mappedClaims.Add(new Claim(newType, claim.Value)); } } } if (validationResult.Subject.GetAuthenticationMethod() == Constants.AuthenticationMethods.Password) { mappedClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password)); mappedClaims.Add(AuthenticationInstantClaim.Now); } return(new ClaimsIdentity(mappedClaims, "idsrv")); }
protected async Task <ClaimsIdentity> CreateSubjectAsync(SignInValidationResult validationResult) { var profileClaims = new List <Claim>(); var mappedClaims = new List <Claim>(); // get all claims from user service if (validationResult.RelyingParty.IncludeAllClaimsForUser) { var ctx = new ProfileDataRequestContext { Subject = validationResult.Subject, AllClaimsRequested = true }; await _users.GetProfileDataAsync(ctx); profileClaims = ctx.IssuedClaims.ToList(); } else { // get only claims that are explicitly mapped (if any) var claimTypes = validationResult.RelyingParty.ClaimMappings.Keys; if (claimTypes.Any()) { var ctx = new ProfileDataRequestContext { Subject = validationResult.Subject, RequestedClaimTypes = claimTypes }; await _users.GetProfileDataAsync(ctx); profileClaims = ctx.IssuedClaims.ToList(); } } foreach (var claim in profileClaims) { string mappedType; // if an explicit mapping exists, use it if (validationResult.RelyingParty.ClaimMappings.TryGetValue(claim.Type, out mappedType)) { // if output claim is a SAML name ID - check is any name ID format is configured if (mappedType == ClaimTypes.NameIdentifier) { var nameId = new Claim(ClaimTypes.NameIdentifier, claim.Value); if (!string.IsNullOrEmpty(validationResult.RelyingParty.SamlNameIdentifierFormat)) { nameId.Properties[ClaimProperties.SamlNameIdentifierFormat] = validationResult.RelyingParty.SamlNameIdentifierFormat; } mappedClaims.Add(nameId); } else { mappedClaims.Add(new Claim(mappedType, claim.Value)); } } else { // otherwise pass-through the claims if flag is set if (validationResult.RelyingParty.IncludeAllClaimsForUser) { string newType = claim.Type; // if prefix is configured, prefix the claim type if (!string.IsNullOrWhiteSpace(validationResult.RelyingParty.DefaultClaimTypeMappingPrefix)) { newType = validationResult.RelyingParty.DefaultClaimTypeMappingPrefix + newType; } mappedClaims.Add(new Claim(newType, claim.Value)); } } } // The AuthnStatement statement generated from the following 2 // claims is manditory for some service providers (i.e. Shibboleth-Sp). // The value of the AuthenticationMethod claim must be one of the constants in // System.IdentityModel.Tokens.AuthenticationMethods. // Password is the only one that can be directly matched, everything // else defaults to Unspecified. if (validationResult.Subject.GetAuthenticationMethod() == Constants.AuthenticationMethods.Password) { mappedClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password)); } else { mappedClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Unspecified)); } mappedClaims.Add(AuthenticationInstantClaim.Now); var finalClaims = await _customClaimsService.TransformClaimsAsync(validationResult, mappedClaims); return(new ClaimsIdentity(finalClaims, "idsrv")); }
private SimpleWebToken CreateToken(string name,IEnumerable<Claim> claims, SignInValidationResult result) { var key = this.HexToByte(result.SiteFinityRelyingParty.Key); var sb = new StringBuilder(); foreach (var c in claims) { sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(c.Type), _httpUtility.UrlEncode(c.Value)); } sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(SitefinityClaimTypes.StsType), "wa"); sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(SitefinityClaimTypes.UserName), name); sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(SitefinityClaimTypes.Domain), result.SiteFinityRelyingParty.Domain); sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(SitefinityClaimTypes.AuthentificationMethod), _httpUtility.UrlEncode("http://schemas.microsoft.com/ws/2008/06/identity/authenticationmethod/password")); sb.AppendFormat("{0}={1}&", _httpUtility.UrlEncode(SitefinityClaimTypes.AuthentificationInstant), DateTime.UtcNow); //double lifeTimeInSeconds = 3600; var loginDateClaim = claims.FirstOrDefault(x => x.Type == SitefinityClaimTypes.LastLoginDate); DateTime issueDate = DateTime.UtcNow; if (loginDateClaim != null) { if (!DateTime.TryParseExact(loginDateClaim.Value, "u", null, DateTimeStyles.None, out issueDate)) { issueDate = DateTime.UtcNow; } } sb .AppendFormat("TokenId={0}&", _httpUtility.UrlEncode(Guid.NewGuid().ToString())) .AppendFormat("Issuer={0}&", _httpUtility.UrlEncode(result.Issuer)) .AppendFormat("Audience={0}&", _httpUtility.UrlEncode(result.Realm)) .AppendFormat("ExpiresOn={0:0}", (issueDate - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + SimpleWebTokenParser.TokenLifeTime); //.AppendFormat("IssueDate={0:0}", (issueDate - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); var unsignedToken = sb.ToString(); var hmac = new HMACSHA256(key); var sig = hmac.ComputeHash(Encoding.ASCII.GetBytes(unsignedToken)); string signedToken = String.Format("{0}&HMACSHA256={1}", unsignedToken, _httpUtility.UrlEncode(Convert.ToBase64String(sig))); return _simpleWebTokenParser.GetToken(signedToken); }
protected async Task <ClaimsIdentity> CreateSubjectAsync(SignInValidationResult result) { var requestedClaimTypes = new List <string>(); var resources = await _resources.FindEnabledIdentityResourcesByScopeAsync(result.Client.AllowedScopes); foreach (var resource in resources) { foreach (var claim in resource.UserClaims) { requestedClaimTypes.Add(claim); } } var ctx = new ProfileDataRequestContext { Subject = result.User, RequestedClaimTypes = requestedClaimTypes, Client = result.Client, Caller = "WS-Federation" }; await _profile.GetProfileDataAsync(ctx); // map outbound claims var nameid = new Claim(ClaimTypes.NameIdentifier, result.User.GetSubjectId()); nameid.Properties[Microsoft.IdentityModel.Tokens.Saml.ClaimProperties.SamlNameIdentifierFormat] = result.RelyingParty.SamlNameIdentifierFormat; var outboundClaims = new List <Claim> { nameid }; foreach (var claim in ctx.IssuedClaims) { if (result.RelyingParty.ClaimMapping.ContainsKey(claim.Type)) { var outboundClaim = new Claim(result.RelyingParty.ClaimMapping[claim.Type], claim.Value); if (outboundClaim.Type == ClaimTypes.NameIdentifier) { outboundClaim.Properties[Microsoft.IdentityModel.Tokens.Saml.ClaimProperties.SamlNameIdentifierFormat] = result.RelyingParty.SamlNameIdentifierFormat; outboundClaims.RemoveAll(c => c.Type == ClaimTypes.NameIdentifier); //remove previesly added nameid claim } outboundClaims.Add(outboundClaim); } else if (result.RelyingParty.TokenType != WsFederationConstants.TokenTypes.Saml11TokenProfile11) { outboundClaims.Add(claim); } else { _logger.LogInformation("No explicit claim type mapping for {claimType} configured. Saml11 requires a URI claim type. Skipping.", claim.Type); } } // The AuthnStatement statement generated from the following 2 // claims is manditory for some service providers (i.e. Shibboleth-Sp). // The value of the AuthenticationMethod claim must be one of the constants in // System.IdentityModel.Tokens.AuthenticationMethods. // Password is the only one that can be directly matched, everything // else defaults to Unspecified. if (result.User.GetAuthenticationMethod() == OidcConstants.AuthenticationMethods.Password) { outboundClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, SamlConstants.AuthenticationMethods.PasswordString)); } else { outboundClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, SamlConstants.AuthenticationMethods.UnspecifiedString)); } // authentication instant claim is required outboundClaims.Add(new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(result.User.GetAuthenticationTime(), "yyyy-MM-ddTHH:mm:ss.fffZ"), ClaimValueTypes.DateTime)); return(new ClaimsIdentity(outboundClaims, "idsrv")); }
/// <summary> /// Creates the subject asynchronous. /// </summary> /// <param name="result">The result.</param> /// <returns></returns> protected async Task <ClaimsIdentity> CreateSubjectAsync(SignInValidationResult result) { var requestedClaimTypes = new List <string>(); var resources = await _resources.FindEnabledIdentityResourcesByScopeAsync(result.Client.AllowedScopes).ConfigureAwait(false); foreach (var resource in resources) { foreach (var claim in resource.UserClaims) { requestedClaimTypes.Add(claim); } } var client = result.Client; var ctx = new ProfileDataRequestContext { Subject = result.User, RequestedClaimTypes = requestedClaimTypes, Client = client, Caller = "WS-Federation", RequestedResources = new ISValidation.ResourceValidationResult { Resources = new Resources { IdentityResources = resources.ToList() } } }; await _profile.GetProfileDataAsync(ctx).ConfigureAwait(false); ctx.IssuedClaims.AddRange(client.Claims.Select(c => new Claim(c.Type, c.Value, c.ValueType))); // map outbound claims var relyParty = result.RelyingParty; var mapping = relyParty.ClaimMapping; var nameid = new Claim(ClaimTypes.NameIdentifier, result.User.GetSubjectId()); nameid.Properties[ClaimProperties.SamlNameIdentifierFormat] = relyParty.SamlNameIdentifierFormat; var outboundClaims = new List <Claim> { nameid }; foreach (var claim in ctx.IssuedClaims) { if (mapping.ContainsKey(claim.Type)) { AddMappedClaim(relyParty, outboundClaims, mapping, claim); } else if (Uri.TryCreate(claim.Type, UriKind.Absolute, out Uri _) || relyParty.TokenType != IdentityServer4.WsFederation.WsFederationConstants.TokenTypes.Saml11TokenProfile11) { outboundClaims.Add(claim); } else { _logger.LogInformation("No explicit claim type mapping for {claimType} configured. Saml requires a URI claim type. Skipping.", claim.Type); } } // The AuthnStatement statement generated from the following 2 // claims is manditory for some service providers (i.e. Shibboleth-Sp). // The value of the AuthenticationMethod claim must be one of the constants in // System.IdentityModel.Tokens.AuthenticationMethods. // Password is the only one that can be directly matched, everything // else defaults to Unspecified. if (result.User.GetAuthenticationMethod() == OidcConstants.AuthenticationMethods.Password) { outboundClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, SamlConstants.AuthenticationMethods.PasswordString)); } else { outboundClaims.Add(new Claim(ClaimTypes.AuthenticationMethod, SamlConstants.AuthenticationMethods.UnspecifiedString)); } // authentication instant claim is required outboundClaims.Add(new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(DateTime.UtcNow, "yyyy-MM-ddTHH:mm:ss.fffZ"), ClaimValueTypes.DateTime)); return(new ClaimsIdentity(outboundClaims, "theidserver")); }
/// <summary> /// Generate the reponse async /// </summary> /// <param name="message">The request input message</param> /// <param name="result">The validation result</param> /// <param name="request">The original http request</param> /// <returns></returns> public async Task <IHttpActionResult> GenerateResponseAsync(SignInRequestMessage message, SignInValidationResult result, HttpRequestMessage request) { Logger.Info("Creating SiteFinity signin response"); var principal = new ClaimsPrincipal(result.Subject); var identity = ClaimsPrincipal.PrimaryIdentitySelector(principal.Identities); var token = CreateToken(identity.Name, identity.Claims, result); NameValueCollection queryString; if (!String.IsNullOrEmpty(result.ReplyUrl)) { string path; var idx = result.ReplyUrl.IndexOf('?'); if (idx != -1) { path = result.ReplyUrl.Substring(0, idx); queryString = ParseQueryString(result.ReplyUrl.Substring(idx + 1)); } else { path = result.ReplyUrl; queryString = new NameValueCollection(); } WrapSWT(queryString, token, message.Deflate); path = String.Concat(path, ToQueryString(queryString)); var uri = new Uri(new Uri(result.Realm), path); var redirectResult = new RedirectResult(uri, request); return(redirectResult); } queryString = new NameValueCollection(); WrapSWT(queryString, token, message.Deflate); var content = new StringContent(ToQueryString(queryString, false), Encoding.UTF8, "application/x-www-form-urlencoded"); var responseMessage = request.CreateResponse(HttpStatusCode.OK, content); return(new ResponseMessageResult(responseMessage)); }
/// <summary> /// Transforms claims before they are sent back to relying party in response to sign in. /// </summary> /// <param name="validationResult">The validated request.</param> /// <param name="mappedClaims">Suggested claims</param> /// <returns>Final claims to include in response</returns> public Task <IEnumerable <Claim> > TransformClaimsAsync(SignInValidationResult validationResult, IEnumerable <Claim> mappedClaims) { return(Task.FromResult(mappedClaims)); }