public static SignInRequestMessage GetSignInRequestMessage(this IRelyingParty rp, Uri baseUri) { var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(baseUri); requestMessage.Realm = requestMessage.Realm ?? rp.Realm; return(requestMessage); }
public IHttpActionResult LoginMock(string id) { if (string.IsNullOrWhiteSpace(id)) { return(BadRequest("No relying party id provided")); } IRelyingParty rp = STSConfiguration <RelyingParty> .Current.RelyingParties.FindByName(id); if (rp == null) { return(BadRequest(string.Format("Relying party with id {0} was not found", id))); } var sts = new SimpleSts(rp.GetStsConfiguration()); var rMessage = rp.GetSignInRequestMessage(Request.RequestUri); ClaimsPrincipal principal = GetMockPrincipalPrincipal(GetMockUser(rMessage)); //ClearAllCookies(); SignInResponseMessage res = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(rMessage, principal, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(res, HttpContext.Current.Response); return(StatusCode(HttpStatusCode.NoContent)); }
public ActionResult Login(LoginModel model) { try { if (model.Id == null) { model.Id = "test"; } ActionResult redirection; IRelyingParty rp = model.Id.GetRelyingPartyElement(out redirection); if (redirection != null) { return(redirection); } var result = HandleSignInRequestLocal(model, (m) => { return(true); }, rp); if (result != null) { return(result); } } catch (Exception ex) { throw; return(new RedirectResult(OnErrorRedirectUrl)); } return(new EmptyResult()); }
public Scope(ClaimsIdentity subject, IRelyingParty party) { AppliesToAddress = party.AppliesTo; Subject = subject; RelyingParty = party; }
public static SignInResponseMessage ProcessSignInRequest(this IRelyingParty rp, Uri baseUri, ClaimsPrincipal principal) { var sts = new SimpleSts(rp.GetStsConfiguration()); var rMessage = rp.GetSignInRequestMessage(baseUri); return(FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest( rMessage, principal, sts)); }
public static void HandleSignIn(this HttpResponse httpResponse, Uri baseUri, IRelyingParty rp, ClaimsPrincipal principal) { var resp = rp.ProcessSignInRequest(baseUri, principal); var httpMessage = resp.WriteFormPost() .Replace("window.setTimeout('document.forms[0].submit()', 0);", "window.setTimeout(submit, 0);function submit(){document.forms[0].submit();}"); httpResponse.Write(httpMessage); }
public static X509EncryptingCredentials GetEncryptingCredentials(this IRelyingParty rp) { var cert = rp.GetEncryptingCertificate(); if (cert == null) { return(null); } return(new X509EncryptingCredentials(cert)); }
public static IRelyingParty GetRelyingPartyElement(this string id, out ActionResult action) { IRelyingParty rp = StsConfiguration <RelyingParty> .Current.RelyingParties.FindByName(id); action = null; if (rp == null) { action = new RedirectResult(OnErrorRedirectUrl); } return(rp); }
public static SimpleStsConfiguration ForRelyingParty(IRelyingParty rp) { if (!CurrentConfigurations.ContainsKey(rp.Name)) { lock (Locker) { if (!CurrentConfigurations.ContainsKey(rp.Name)) { CurrentConfigurations.Add(rp.Name, new SimpleStsConfiguration(rp)); } } } return CurrentConfigurations[rp.Name]; }
public static SimpleStsConfiguration ForRelyingParty(IRelyingParty rp) { if (!CurrentConfigurations.ContainsKey(rp.Name)) { lock (Locker) { if (!CurrentConfigurations.ContainsKey(rp.Name)) { CurrentConfigurations.Add(rp.Name, new SimpleStsConfiguration(rp)); } } } return(CurrentConfigurations[rp.Name]); }
public SimpleStsConfiguration(IRelyingParty rp) : base(rp.IssuerName) { RelyingParty = rp; SecurityTokenService = typeof(SimpleSts); SecurityTokenHandlers.Clear(); SecurityTokenHandlers.Add(rp.TokenType.GetSecurityTokenHandler()); ServiceCertificate = rp.GetEncryptingCertificate(); if (ServiceCertificate != null) { SecurityTokenHandlers.Add(new EncryptedSecurityTokenHandler()); } }
public RequestScope(Uri uri, IRelyingParty rp): base(uri.ToString(), rp.GetSigningCertificate().GetSigningCredentials()) { RelyingParty = rp; EncryptingCredentials = rp.GetEncryptingCertificate().GetEncryptingCredentials(); if (EncryptingCredentials != null) { TokenEncryptionRequired = true; SymmetricKeyEncryptionRequired = true; } else { TokenEncryptionRequired = false; SymmetricKeyEncryptionRequired = false; } }
public RequestScope(Uri uri, IRelyingParty rp) : base(uri.ToString(), rp.GetSigningCertificate().GetSigningCredentials()) { RelyingParty = rp; EncryptingCredentials = rp.GetEncryptingCertificate().GetEncryptingCredentials(); if (EncryptingCredentials != null) { TokenEncryptionRequired = true; SymmetricKeyEncryptionRequired = true; } else { TokenEncryptionRequired = false; SymmetricKeyEncryptionRequired = false; } }
public SimpleStsConfiguration(IRelyingParty rp) : base(rp.IssuerName) { RelyingParty = rp; SecurityTokenService = typeof(SimpleSts); SecurityTokenHandlers.Clear(); SecurityTokenHandlers.Add(TokenTypes.GetSecurityTokenHandler(rp.TokenType)); ServiceCertificate = rp.GetEncryptingCertificate(); if (ServiceCertificate != null) { SecurityTokenHandlers.Add(new EncryptedSecurityTokenHandler()); } }
public IHttpActionResult Tokens([FromUri] string id) { if (string.IsNullOrWhiteSpace(id)) { return(BadRequest("No relying party id provided")); } IRelyingParty rp = STSConfiguration <RelyingParty> .Current.RelyingParties.FindByName(id); if (rp == null) { return(BadRequest(string.Format("Relying party with id {0} was not found", id))); } var sts = new SimpleSts(rp.GetStsConfiguration()); var rMessage = rp.GetSignInRequestMessage(Request.RequestUri); //ClearAllCookies(); SignInResponseMessage res = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(rMessage, GetPrincipal(), sts); //SecurityToken st = FederatedAuthentication.WSFederationAuthenticationModule.GetSecurityToken(res); //XmlReader reader = XmlReader.Create("addressdata.xml"); //XmlDictionaryReader dictReader = XmlDictionaryReader.CreateDictionaryReader(reader); //string s= FederatedAuthentication.WSFederationAuthenticationModule.GetXmlTokenFromMessage(res); //FederatedPassiveSecurityTokenServiceOperations..ProcessSignInResponse(res, HttpContext.Current.Response); var response = Request.CreateResponse(HttpStatusCode.OK); NameValueCollection nvc = WSFederationMessage.ParseQueryString(new Uri(res.WriteQueryString())); response.Content = new FormUrlEncodedContent(nvc.AllKeys.Select(f => new KeyValuePair <string, string>(f, nvc[f]))); //response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/soap+xml"); return(ResponseMessage(response)); }
ActionResult HandleSignInRequestLocal(Models.LoginModel model, Func<Models.LoginModel, bool> logonFunction, IRelyingParty rp) { try { var actualPrincipal = GetPrincipal(model); ClearAllCookies(); //except [culture, theme, font, etc] cookies System.Web.HttpContext.Current.Response.HandleSignIn(Request.Url, rp, actualPrincipal); return new EmptyResult(); } catch (Exception ex) { throw new Exception("HandleSingleInRequest Failed. ", ex); } }
public ValueTask <IEnumerable <Claim> > GetClaimsAsync(ClaimsIdentity identity, IRelyingParty party, IEnumerable <Claim> outgoingClaims) { var attributes = outgoingClaims .Where(c => c.Type != ClaimTypes.NameIdentifier) .Where(c => c.Type != ClaimTypes.AuthenticationInstant) .Where(c => c.Type != ClaimTypes.AuthenticationMethod) ; var claims = new List <Claim>(); if (!attributes.Any()) { claims.Add(new Claim("http://schemas.solidsoft.works/ws/2020/08/identity/claims/null", bool.TrueString, ClaimValueTypes.Boolean)); } return(new ValueTask <IEnumerable <Claim> >(claims)); }
ActionResult HandleSignInRequestLocal(Models.LoginModel model, Func <Models.LoginModel, bool> logonFunction, IRelyingParty rp) { try { var actualPrincipal = GetPrincipal(model); ClearAllCookies(); //except [culture, theme, font, etc] cookies System.Web.HttpContext.Current.Response.HandleSignIn(Request.Url, rp, actualPrincipal); return(new EmptyResult()); } catch (Exception ex) { throw new Exception("HandleSingleInRequest Failed. ", ex); } }
private async Task <bool> TryGetClaimsAsync(IEnumerable <string> requestedClaimTypes, string requirement, ClaimsIdentity source, IRelyingParty party, ICollection <Claim> claims) { var list = requestedClaimTypes.ToList(); var stores = new List <IRelyingPartyClaimStore>(); foreach (var type in requestedClaimTypes) { if (!_relyingPartyClaimStores.TryGetValue(type, out var relyingPartyClaimStores)) { continue; } stores.AddRange(relyingPartyClaimStores); } foreach (var store in stores.Distinct()) { if (!store.CanGenerateClaims(party.AppliesTo)) { continue; } _logger.LogDebug($"Attempting to get {requirement} claims from {store.GetType().Name}"); var requiredClaims = await store.GetClaimsAsync(source, party); foreach (var claim in requiredClaims) { _logger.LogTrace($"Adding {requirement} claim '{claim.Type}' from {store.GetType().Name}"); claims.Add(claim); if (list.Contains(claim.Type)) { list.Remove(claim.Type); } } } var copy = list.ToArray(); foreach (var type in copy) { var claim = source.FindFirst(type); if (claim == null) { continue; } _logger.LogDebug($"Adding {requirement} claim '{type}' from source identity."); claims.Add(claim); list.Remove(type); } var success = !list.Any(); if (!success) { WsTrustLogMessages.UnableToGetAllClaims(_logger, requirement, new UnableToGetAllClaims { UnpopulatedClaimTypes = list }, null); } return(success); }
public abstract ValueTask <IEnumerable <Claim> > GetClaimsAsync(ClaimsIdentity identity, IRelyingParty party);
protected virtual async ValueTask <Scope> CreateScopeAsync(ClaimsPrincipal principal, WsTrustRequest request, IRelyingParty party, CancellationToken cancellationToken) { var identity = ClaimsPrincipal.PrimaryIdentitySelector(principal.Identities); var claims = await MapIncomingClaimsAsync(principal.Claims); var user = new ClaimsIdentity(claims, identity.AuthenticationType, identity.NameClaimType, identity.RoleClaimType); var scope = new Scope(user, party); scope.SigningCredentials = await CreateSigningCredentialsAsync(party, cancellationToken); scope.EncryptingCredentials = await CreateEncryptingCredentialsAsync(party, cancellationToken); return(scope); }
public async ValueTask <ClaimsIdentity> CreateOutgoingSubjectAsync(ClaimsIdentity identity, IRelyingParty relyingParty, string tokenType) { var claims = new List <Claim>(); var required = relyingParty.RequiredClaims ?? Enumerable.Empty <string>(); var optional = relyingParty.OptionalClaims ?? Enumerable.Empty <string>(); _logger.LogInformation($"Getting required claims for party: {relyingParty.AppliesTo}"); if (required.Any()) { if (!await TryGetClaimsAsync(required, nameof(required), identity, relyingParty, claims)) { throw new SecurityException($"Unable to get all required claim values for party: {relyingParty.AppliesTo}"); } } else { _logger.LogInformation($"No required claims for party: {relyingParty.AppliesTo}"); } _logger.LogInformation($"Getting optional claims for party: {relyingParty.AppliesTo}"); if (optional.Any()) { _ = await TryGetClaimsAsync(optional, nameof(optional), identity, relyingParty, claims); } else { _logger.LogInformation($"No optional claims for party: {relyingParty.AppliesTo}"); } var tokenTypeClaimStores = _tokenTypeClaimStores.Where(s => s.CanGenerateClaims(tokenType)); if (tokenTypeClaimStores.Any()) { _logger.LogDebug($"Getting claims for token type: {tokenType}"); foreach (var store in tokenTypeClaimStores) { var tokenTypeClaims = await store.GetClaimsAsync(identity, relyingParty, claims); foreach (var claim in tokenTypeClaims) { _logger.LogTrace($"Adding {claim.Type} from {store.GetType().Name}"); claims.Add(claim); } } } var outgoing = new ClaimsIdentity(claims, identity.AuthenticationType, identity.NameClaimType, identity.RoleClaimType); return(outgoing); }
protected virtual ValueTask <EncryptingCredentials> CreateEncryptingCredentialsAsync(IRelyingParty party, CancellationToken cancellationToken) { if (!party.RequiresEncryptedToken && !party.RequiresEncryptedSymmetricKeys) { return(new ValueTask <EncryptingCredentials>()); } var key = party.EncryptingKey; var method = party.EncryptingAlgorithm ?? Options.DefaultEncryptionAlgorithm; if (key == null) { key = Options.DefaultSigningKey; method = Options.DefaultEncryptionAlgorithm; } if (key == null) { return(new ValueTask <EncryptingCredentials>()); } var credentials = method.CreateCredentials(key); var information = new EncryptingCredentialsInformation { SecurityKeyName = (key is X509SecurityKey x509) ? x509.Certificate.Subject : key.KeyId, SecurityKeyType = key.GetType().Name, DataEncryptionAlgorithm = method.EncryptionAlgorithm, KeyWrapAlgorithm = method.KeyWrapAlgorithm }; WsTrustLogMessages.EncryptingCredentialsCreated(Logger, information, null); return(new ValueTask <EncryptingCredentials>(credentials)); }
protected virtual async ValueTask ValidateRelyingPartyAsync(ClaimsPrincipal principal, WsTrustRequest request, IRelyingParty party, CancellationToken cancellationToken) { var issuer = principal.FindFirst(WsSecurityClaimTypes.Issuer)?.Value; var appliesTo = request.AppliesTo.EndpointReference.Uri; if (party.ValidateRequestedTokenType && !party.SupportedTokenTypes.Contains(request.TokenType)) { throw new SecurityException($"Identity provider ({issuer}) attempting to request a token type the relying party ({appliesTo}) doesn't support: {request.TokenType}"); } if (!await party.AuthorizeAsync(Services, principal)) { throw new SecurityException($"User is not authorized to be issued a token for {party.AppliesTo}"); } }
protected virtual ValueTask <SigningCredentials> CreateSigningCredentialsAsync(IRelyingParty party, CancellationToken cancellationToken) { var key = party.SigningKey; var method = party.SigningAlgorithm ?? Options.DefaultSigningAlgorithm; if (key == null) { key = Options.DefaultSigningKey; method = Options.DefaultSigningAlgorithm; } if (key == null) { return(new ValueTask <SigningCredentials>()); } var credentials = method.CreateCredentials(key); var information = new SigningCredentialsInformation { SecurityKeyName = (key is X509SecurityKey x509) ? x509.Certificate.Subject : key.KeyId, SecurityKeyType = key.GetType().Name, Algorithm = method.SignatureAlgortihm, Digest = method.DigestAlgorithm }; WsTrustLogMessages.SigningCredentialsCreated(Logger, information, null); return(new ValueTask <SigningCredentials>(credentials)); }
public string Issue(string relayingPartyName, string realm, string userName, string userId) { if (string.IsNullOrWhiteSpace(relayingPartyName)) { throw new ArgumentNullException("relayingPartyName"); } if (string.IsNullOrWhiteSpace(realm)) { throw new ArgumentNullException("realm"); } if (string.IsNullOrWhiteSpace(userName)) { throw new ArgumentNullException("userName"); } if (string.IsNullOrWhiteSpace(userId)) { throw new ArgumentNullException("userId"); } ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> { new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.Sid, userId) })); // Signin message for cross service -> issuer realm == home realm == issuer url SignInRequestMessage signInRequestMessage = new SignInRequestMessage(new Uri(realm), realm) { CurrentTime = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "Z", HomeRealm = realm }; IRelyingParty rp = STSConfiguration <RelyingParty> .Current.RelyingParties.FindByName(relayingPartyName); if (rp == null) { throw new ConfigurationErrorsException(string.Format("Relying party with name {0} was not found", relayingPartyName)); } if (FederatedAuthentication.WSFederationAuthenticationModule == null) { throw new ConfigurationErrorsException("WSFederationAuthenticationModule was not found"); } var sts = new SimpleSts(rp.GetStsConfiguration()); SignInResponseMessage signInResponseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(signInRequestMessage, principal, sts); string tokenXml = signInResponseMessage.Result; XmlDocument xml = new XmlDocument(); xml.LoadXml(tokenXml); string xmlSecurityToken = xml.DocumentElement.GetElementsByTagName("trust:RequestedSecurityToken").Item(0).InnerXml; // <Assertion> //WSFederationSerializer ser = new WSFederationSerializer(); //GenericXmlSecurityToken xmlt = new GenericXmlSecurityToken() //string xmlSecurityToken = FederatedAuthentication.WSFederationAuthenticationModule.GetXmlTokenFromMessage(signInResponseMessage); var xmlSecurityTokenBase64Encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(xmlSecurityToken)); return(xmlSecurityTokenBase64Encoded); }
public static SignInRequestMessage GetSignInRequestMessage(this IRelyingParty rp, Uri baseUri) { return(new SignInRequestMessage(baseUri, rp.Realm)); }
public async Task <IHttpActionResult> Login(string relyingPartyName) { if (string.IsNullOrWhiteSpace(relyingPartyName)) { return(BadRequest("No relying party id provided")); } string action; NameValueCollection content = null; NameValueCollection qs = Request.RequestUri.ParseQueryString(); action = qs.Get(WSFederationConstants.Parameters.Action); if (string.IsNullOrWhiteSpace(action)) { content = await Request.Content.ReadAsFormDataAsync(); action = content.Get(WSFederationConstants.Parameters.Action); } if (action == WSFederationConstants.Actions.SignIn) { IRelyingParty rp = STSConfiguration <RelyingParty> .Current.RelyingParties.FindByName(relyingPartyName); if (this.User != null && this.User.Identity.IsAuthenticated) { if (content == null) { content = await Request.Content.ReadAsFormDataAsync(); } WSFederationMessage responseMessageFromIssuer = WSFederationMessage.CreateFromNameValueCollection(Request.RequestUri, content); var contextId = responseMessageFromIssuer.Context; var ctxCookie = System.Web.HttpContext.Current.Request.Cookies[contextId]; if (ctxCookie == null) { throw new InvalidOperationException("Context cookie not found"); } var originalRequestUri = new Uri(ctxCookie.Value); HttpCookie cookie = DeleteContextCookie(contextId); System.Web.HttpContext.Current.Response.Cookies.Add(cookie); var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(originalRequestUri); var sts = new SimpleSts(rp.GetStsConfiguration()); SignInResponseMessage rm = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User as ClaimsPrincipal, sts); //WSTrustSerializationContext context = new WSTrustSerializationContext(FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlerCollectionManager); //WSFederationSerializer fedSer = new WSFederationSerializer(); //RequestSecurityTokenResponse token = fedSer.CreateResponse(rm, context); //token.RequestedSecurityToken.SecurityToken. FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(rm, System.Web.HttpContext.Current.Response); return(StatusCode(HttpStatusCode.NoContent)); } else { var contextId = Guid.NewGuid().ToString(); HttpCookie cookie = CreateContextCookie(contextId, HttpUtility.UrlDecode(this.Request.RequestUri.AbsoluteUri)); System.Web.HttpContext.Current.Response.Cookies.Add(cookie); var message = new SignInRequestMessage(new Uri(rp.AuthenticationUrl), FederatedAuthentication.WSFederationAuthenticationModule.Realm) { CurrentTime = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "Z", HomeRealm = rp.Realm, Context = contextId, Reply = Url.Link("Login", new { relyingPartyName = relyingPartyName }) }; message.Parameters.Add(new KeyValuePair <string, string>("originalRequest", Request.RequestUri.ToString())); return(Redirect(message.RequestUrl)); } } else { return(BadRequest(String.Format( CultureInfo.InvariantCulture, "The action '{0}' (Request.QueryString['{1}']) is unexpected. Expected actions are: '{2}' or '{3}'.", String.IsNullOrEmpty(action) ? "<EMPTY>" : action, WSFederationConstants.Parameters.Action, WSFederationConstants.Actions.SignIn, WSFederationConstants.Actions.SignOut))); } }
public static SimpleStsConfiguration GetStsConfiguration(this IRelyingParty rp) { return(SimpleStsConfiguration.ForRelyingParty(rp)); }