private void ValidateUserCredentials(UserNameSecurityToken token) { if (!token.UserName.Equals(token.Password)) { throw new FaultException("Incorrect username or password"); } }
public IClaimsPrincipal ValidateWebToken(string token) { var decoded = DecodeBasicAuthenticationHeader(token); var securityToken = new UserNameSecurityToken(decoded.Item1, decoded.Item2); return ClaimsPrincipal.CreateFromIdentities(ValidateToken(securityToken)); }
public UserNameSecurityTokenProvider(string userName, string password) { if (userName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("userName"); } this.userNameToken = new UserNameSecurityToken(userName, password); }
private IList<ClaimsIdentity> ExtractClaims(UserNameSecurityToken token) { ClaimsIdentity outgoingIndentity = new ClaimsIdentity("UserAuthenticate"); outgoingIndentity.Label = "UserAuthenticate"; outgoingIndentity.AddClaim(new Claim(ClaimTypes.Name, token.UserName)); outgoingIndentity.AddClaim(new Claim(ClaimTypes.Email, "*****@*****.**")); var identities = new List<ClaimsIdentity> { outgoingIndentity }; return identities; }
public void DefaultValues () { UniqueId id = new UniqueId (); UserNameSecurityToken t = new UserNameSecurityToken ("mono", "poly", id.ToString ()); Assert.AreEqual (id.ToString (), t.Id, "#1"); Assert.AreEqual ("mono", t.UserName, "#2"); Assert.AreEqual ("poly", t.Password,"#3"); Assert.IsTrue (DateTime.Today.ToUniversalTime () <= t.ValidFrom && DateTime.Now.ToUniversalTime () >= t.ValidFrom, "#4"); Assert.AreEqual (DateTime.MaxValue.AddDays (-1), t.ValidTo, "#5"); Assert.AreEqual (0, t.SecurityKeys.Count, "#6"); }
public IClaimsPrincipal ValidateToken(string token) { if (string.IsNullOrWhiteSpace(token)) { throw new ArgumentNullException("token"); } var decoded = DecodeBasicAuthenticationHeader(token); var securityToken = new UserNameSecurityToken(decoded.Item1, decoded.Item2); return ClaimsPrincipal.CreateFromIdentities(ValidateToken(securityToken)); }
public void TryResolveToken () { SecurityTokenResolver r = GetResolver (true, new SecurityToken [0]); SecurityToken token; Assert.IsFalse (r.TryResolveToken (new LocalIdKeyIdentifierClause ("foo"), out token)); UserNameSecurityToken userName = new UserNameSecurityToken ("mono", "", "urn:foo"); LocalIdKeyIdentifierClause kic = new LocalIdKeyIdentifierClause ("urn:foo"); r = GetResolver (true, new SecurityToken [] {userName}); Assert.IsTrue (r.TryResolveToken (kic, out token)); r = GetResolver (false, new SecurityToken [] {userName}); Assert.IsFalse (r.TryResolveToken (kic, out token)); }
public void CreateKeyIdentifierClause () { MyUserNameSecurityTokenParameters p = new MyUserNameSecurityTokenParameters (); UserNameSecurityToken token = new UserNameSecurityToken ("mono", "pass"); SecurityKeyIdentifierClause c = p.CreateKeyClause (token, SecurityTokenReferenceStyle.Internal); Assert.IsTrue (c is LocalIdKeyIdentifierClause, "#1"); try { p.CreateKeyClause (token, SecurityTokenReferenceStyle.External); Assert.Fail ("External identifier clause cannot be created."); } catch (NotSupportedException) { } }
public override IAsyncResult BeginReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver, AsyncCallback callback, object state) { string id; string userName; string password; ParseToken(reader, out id, out userName, out password); SecurityToken token = new UserNameSecurityToken(userName, password, id); return new CompletedAsyncResult<SecurityToken>(token, callback, state); }
/// <summary> /// Impersonates the windows user identifed by the security token. /// </summary> private void LogonUser(OperationContext context, UserNameSecurityToken securityToken) { IntPtr handle = IntPtr.Zero; const int LOGON32_PROVIDER_DEFAULT = 0; // const int LOGON32_LOGON_INTERACTIVE = 2; const int LOGON32_LOGON_NETWORK = 3; // const int LOGON32_LOGON_BATCH = 4; bool result = NativeMethods.LogonUser( securityToken.UserName, String.Empty, securityToken.Password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, ref handle); if (!result) { throw ServiceResultException.Create(StatusCodes.BadUserAccessDenied, "Login failed for user: {0}", securityToken.UserName); } WindowsIdentity identity = new WindowsIdentity(handle); ImpersonationContext impersonationContext = new ImpersonationContext(); impersonationContext.Handle = handle; impersonationContext.Context = identity.Impersonate(); lock (this.m_lock) { m_contexts.Add(context.RequestId, impersonationContext); } }
/// <summary> /// Validates the username and password. /// </summary> /// <param name="token">The token.</param> /// <returns>An identity collection representing the identity in the token</returns> public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token) { if (token == null) { throw new ArgumentNullException("token"); } if (base.Configuration == null) { throw new InvalidOperationException("No Configuration set"); } var unToken = token as UserNameSecurityToken; if (unToken == null) { throw new ArgumentException("SecurityToken is not a UserNameSecurityToken"); } LMConnect.Key.User user = ValidateUserNameCredentialCore(unToken.UserName, unToken.Password); if (user == null) { return new List<ClaimsIdentity> { new ClaimsIdentity() }.AsReadOnly(); } var claims = new List<Claim> { new Claim(ClaimTypes.Name, unToken.UserName), new Claim(ClaimTypes.Role, user.Role), new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password), new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(DateTime.UtcNow, "yyyy-MM-ddTHH:mm:ss.fffZ"), ClaimValueTypes.DateTime) }; var identity = new ClaimsIdentity(claims, "Basic"); if (Configuration.SaveBootstrapContext) { if (this.RetainPassword) { identity.BootstrapContext = new BootstrapContext(unToken, this); } else { var bootstrapToken = new UserNameSecurityToken(unToken.UserName, null); identity.BootstrapContext = new BootstrapContext(bootstrapToken, this); } } return new List<ClaimsIdentity> { identity }.AsReadOnly(); }
void WriteUserNameSecurityToken (XmlWriter w, UserNameSecurityToken token) { w.WriteStartElement ("o", "UsernameToken", Constants.WssNamespace); w.WriteAttributeString ("u", "Id", Constants.WsuNamespace, token.Id); w.WriteStartElement ("o", "Username", Constants.WssNamespace); w.WriteString (token.UserName); w.WriteEndElement (); w.WriteStartElement ("o", "Password", Constants.WssNamespace); w.WriteString (token.Password); w.WriteEndElement (); w.WriteEndElement (); }
/// <summary> /// Verifies that the security token is a valid windows user. /// </summary> /// <param name="identityToken">The security token.</param> public static void VerifyPassword(UserNameSecurityToken identityToken) { if (identityToken == null) { throw ServiceResultException.Create(StatusCodes.BadIdentityTokenRejected, "Secuirty token is not a valid username token."); } // extract the username and domain from the security token. string username = identityToken.UserName; string domain = null; int index = username.IndexOf('\\'); if (index != -1) { domain = username.Substring(0, index); username = username.Substring(index + 1); } IntPtr handle = IntPtr.Zero; int result = Win32.LogonUserW( username, domain, identityToken.Password, Win32.LOGON32_LOGON_NETWORK, Win32.LOGON32_PROVIDER_DEFAULT, ref handle); if (result == 0) { throw ServiceResultException.Create(StatusCodes.BadIdentityTokenRejected, "Login failed for user: {0}", username); } Win32.CloseHandle(handle); }
/// <summary> /// Returns the windows principal associated with a user name security token. /// </summary> /// <param name="identityToken">The identity token.</param> /// <param name="interactive">Whether to logon interactively (slow).</param> /// <returns>The impersonation context (must be disposed to reverse impersonation).</returns> public static ImpersonationContext LogonUser(UserNameSecurityToken identityToken, bool interactive) { if (identityToken == null) { throw ServiceResultException.Create(StatusCodes.BadIdentityTokenRejected, "Secuirty token is not a valid username token."); } // extract the username and domain from the security token. string username = identityToken.UserName; string domain = null; int index = username.IndexOf('\\'); if (index != -1) { domain = username.Substring(0, index); username = username.Substring(index+1); } // validate the credentials. IntPtr handle = IntPtr.Zero; int result = Win32.LogonUserW( username, domain, identityToken.Password, (interactive) ? Win32.LOGON32_LOGON_INTERACTIVE : Win32.LOGON32_LOGON_NETWORK, Win32.LOGON32_PROVIDER_DEFAULT, ref handle); if (result == 0) { result = Marshal.GetLastWin32Error(); throw ServiceResultException.Create( StatusCodes.BadIdentityTokenRejected, "Could not logon as user '{0}'. Reason: {1}.", identityToken.UserName, result); } try { WindowsIdentity identity = new WindowsIdentity(handle); ImpersonationContext context = new ImpersonationContext(); context.Principal = new WindowsPrincipal(identity); context.Context = identity.Impersonate(); context.Handle = handle; return context; } catch (Exception e) { Win32.CloseHandle(handle); throw e; } }
/// <summary> /// Validates a <see cref="UserNameSecurityToken"/>. /// </summary> /// <param name="token">The <see cref="UserNameSecurityToken"/> to validate.</param> /// <returns>A <see cref="ReadOnlyCollection{T}"/> of <see cref="ClaimsIdentity"/> representing the identities contained in the token.</returns> /// <exception cref="ArgumentNullException">The parameter 'token' is null.</exception> /// <exception cref="ArgumentException">The token is not assignable from<see cref="UserNameSecurityToken"/>.</exception> /// <exception cref="InvalidOperationException">Configuration <see cref="SecurityTokenHandlerConfiguration"/>is null.</exception> /// <exception cref="ArgumentException">If username is not if the form 'user\domain'.</exception> /// <exception cref="SecurityTokenValidationException">LogonUser using the given token failed.</exception> public override ReadOnlyCollection <ClaimsIdentity> ValidateToken(SecurityToken token) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } UserNameSecurityToken usernameToken = token as UserNameSecurityToken; if (usernameToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token", SR.GetString(SR.ID0018, typeof(UserNameSecurityToken))); } if (this.Configuration == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274)); } try { string userName = usernameToken.UserName; string password = usernameToken.Password; string domain = null; string[] strings = usernameToken.UserName.Split('\\'); if (strings.Length != 1) { if (strings.Length != 2 || string.IsNullOrEmpty(strings[0])) { // Only support one slash and domain cannot be empty (consistent with windowslogon). throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token", SR.GetString(SR.ID4062)); } // This is the downlevel case - domain\userName userName = strings[1]; domain = strings[0]; } const uint LOGON32_PROVIDER_DEFAULT = 0; const uint LOGON32_LOGON_NETWORK_CLEARTEXT = 8; SafeCloseHandle tokenHandle = null; try { if (!NativeMethods.LogonUser(userName, domain, password, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_PROVIDER_DEFAULT, out tokenHandle)) { int error = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.ID4063, userName), new Win32Exception(error))); } WindowsIdentity windowsIdentity = new WindowsIdentity(tokenHandle.DangerousGetHandle(), AuthenticationTypes.Password, WindowsAccountType.Normal, true); // PARTIAL TRUST: will fail when adding claims, AddClaim is SecurityCritical. windowsIdentity.AddClaim(new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(DateTime.UtcNow, DateTimeFormats.Generated), ClaimValueTypes.DateTime)); windowsIdentity.AddClaim(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password)); if (this.Configuration.SaveBootstrapContext) { if (RetainPassword) { windowsIdentity.BootstrapContext = new BootstrapContext(usernameToken, this); } else { windowsIdentity.BootstrapContext = new BootstrapContext(new UserNameSecurityToken(usernameToken.UserName, null), this); } } this.TraceTokenValidationSuccess(token); List <ClaimsIdentity> identities = new List <ClaimsIdentity>(1); identities.Add(windowsIdentity); return(identities.AsReadOnly()); } finally { if (tokenHandle != null) { tokenHandle.Close(); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.TraceTokenValidationFailure(token, e.Message); throw e; } }
public void UserNameToken () // it does not support any encryption operation. { byte [] bytes = new byte [32]; SecurityToken wt = new UserNameSecurityToken ("eno", "enopass"); SecurityKeyIdentifierClause kic = new X509ThumbprintKeyIdentifierClause (cert); new WrappedKeySecurityToken ("urn:gyabo", bytes, SecurityAlgorithms.RsaOaepKeyWrap, wt, new SecurityKeyIdentifier (kic)); }
public void WriteUserNameSecurityToken1 () { StringWriter sw = new StringWriter (); UserNameSecurityToken t = new UserNameSecurityToken ("mono", "poly", "urn:username:1"); using (XmlWriter w = XmlWriter.Create (sw, GetWriterSettings ())) { WSSecurityTokenSerializer.DefaultInstance.WriteToken (w, t); } // Hmm, no PasswordToken (and TokenType) ? Assert.AreEqual ("<o:UsernameToken u:Id=\"urn:username:1\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:o=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><o:Username>mono</o:Username><o:Password>poly</o:Password></o:UsernameToken>", sw.ToString ()); }
public void Ctor_SecurityToken_Works () { var securityToken = new UserNameSecurityToken (user, password); var securityTokenHandler = new SimpleSecurityTokenHandler (); BootstrapContext bootstrapContext = new BootstrapContext (securityToken, securityTokenHandler); Assert.IsNotNull (bootstrapContext.SecurityToken, "#1"); Assert.AreEqual (user, securityToken.UserName, "#2"); Assert.AreEqual (password, securityToken.Password, "#3"); Assert.AreEqual (securityTokenHandler, bootstrapContext.SecurityTokenHandler, "#4"); Assert.IsNull (bootstrapContext.Token, "#5"); Assert.IsNull (bootstrapContext.TokenBytes, "#6"); }
public void Serialize_SecurityTokenAndHandler_Works () { var securityToken = new UserNameSecurityToken (user, password, "uuid-927c0b98-ba18-49d2-a653-306d60f85751-3"); var securityTokenHandler = new SimpleSecurityTokenHandler (); BootstrapContext bootstrapContext = new BootstrapContext (securityToken, securityTokenHandler); BinaryFormatter binaryFormatter = new BinaryFormatter (); using (var s = new MemoryStream ()) { binaryFormatter.Serialize (s, bootstrapContext); s.Position = 0; BootstrapContext bootstrapContext2 = binaryFormatter.Deserialize (s) as BootstrapContext; Assert.IsNotNull (bootstrapContext2, "#1"); // Deserialize does not restore the SecurityToken, but restores into the Token. Assert.IsNotNull (bootstrapContext2.Token, "#3"); // We replace ' /' by '/' to accomodate the xml writer differences between mono and .net Assert.AreEqual (SerializedBootstrapContextSecurityTokenString.Replace (" /", "/"), bootstrapContext2.Token.Replace (" /", "/"), "#2"); Assert.AreEqual (bootstrapContext.TokenBytes, bootstrapContext2.TokenBytes, "#3"); Assert.IsNull (bootstrapContext2.SecurityToken, "#4"); Assert.IsNull (bootstrapContext2.SecurityTokenHandler, "#5"); } }
/// <summary> /// Validates the username and password. /// </summary> /// <param name="token">The token.</param> /// <returns>An identity collection representing the identity in the token</returns> public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token) { if (token == null) { throw new ArgumentNullException("token"); } if (base.Configuration == null) { throw new InvalidOperationException("No Configuration set"); } UserNameSecurityToken unToken = token as UserNameSecurityToken; if (unToken == null) { throw new ArgumentException("SecurityToken is not a UserNameSecurityToken"); } if (!ValidateUserNameCredentialCore(unToken.UserName, unToken.Password)) { throw new SecurityTokenValidationException(unToken.UserName); } var claims = new List<Claim> { new Claim(ClaimTypes.Name, unToken.UserName), new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password), AuthenticationInstantClaim.Now }; if (RetainPassword) { claims.Add(new Claim("password", unToken.Password)); } var identity = new ClaimsIdentity(claims, "Basic"); if (Configuration.SaveBootstrapContext) { if (this.RetainPassword) { identity.BootstrapContext = new BootstrapContext(unToken, this); } else { var bootstrapToken = new UserNameSecurityToken(unToken.UserName, null); identity.BootstrapContext = new BootstrapContext(bootstrapToken, this); } } return new List<ClaimsIdentity> { identity }.AsReadOnly(); }
/// <summary> /// Writes the given UsernameSecurityToken to the XmlWriter. /// </summary> /// <param name="writer">XmlWriter to write the token to.</param> /// <param name="token">SecurityToken to be written.</param> /// <exception cref="InvalidOperationException">The given token is not a UsernameSecurityToken.</exception> /// <exception cref="ArgumentNullException">The parameter 'writer' or 'token' is null.</exception> public override void WriteToken(XmlWriter writer, SecurityToken token) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } UserNameSecurityToken usernameSecurityToken = token as UserNameSecurityToken; if (usernameSecurityToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("token", SR.GetString(SR.ID0018, typeof(UserNameSecurityToken))); } // <wsse:UsernameToken writer.WriteStartElement( WSSecurity10Constants.Elements.UsernameToken, WSSecurity10Constants.Namespace ); if (!string.IsNullOrEmpty(token.Id)) { // wsu:Id="..." writer.WriteAttributeString( WSUtilityConstants.Attributes.IdAttribute, WSUtilityConstants.NamespaceURI, token.Id ); } // <wsse:Username>...</wsse:Username> writer.WriteElementString( WSSecurity10Constants.Elements.Username, WSSecurity10Constants.Namespace, usernameSecurityToken.UserName ); // <wsse:Password>...</wsse:Password> if (usernameSecurityToken.Password != null) { writer.WriteStartElement( WSSecurity10Constants.Elements.Password, WSSecurity10Constants.Namespace ); writer.WriteAttributeString( WSSecurity10Constants.Attributes.Type, null, WSSecurity10Constants.UPTokenPasswordTextValue ); writer.WriteString(usernameSecurityToken.Password); writer.WriteEndElement(); } writer.WriteEndElement(); writer.Flush(); }