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"); }
private void AppendUserNameToken(SecurityHeader wsSecurityHeader, string userName, SecureString password) { // Reusing the WCF UserNameSecurityToken as there is a built-in serializer for this type. UserNameSecurityToken userNameToken = null; string tokenId = CreateElementId(SECURITY_TOKEN_ID_PREFIX); userNameToken = new UserNameSecurityToken(userName, Util.ConvertSecureStringToString(password), tokenId); wsSecurityHeader.UsernameToken = SerializeToken(userNameToken); }
/// <summary> /// Validates the token. /// </summary> /// <param name="token">The token.</param> /// <returns>Collection of identity claims</returns> public override ClaimsIdentityCollection ValidateToken(System.IdentityModel.Tokens.SecurityToken token) { UserNameSecurityToken userNameSecurityToken = token as UserNameSecurityToken; MembershipProvider provider = Membership.Provider; bool isValidated = provider.ValidateUser(userNameSecurityToken.UserName, userNameSecurityToken.Password); ClaimsIdentity claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(System.IdentityModel.Claims.ClaimTypes.Name, userNameSecurityToken.UserName) }); ClaimsIdentityCollection claimIdentityCollection = new ClaimsIdentityCollection(new IClaimsIdentity[] { claimsIdentity }); return(claimIdentityCollection); }
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(); }
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> /// 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 ClaimsIdentityCollection 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.SaveBootstrapTokens) { if (this.RetainPassword) { identity.BootstrapToken = unToken; } else { var bootstrapToken = new UserNameSecurityToken(unToken.UserName, null); identity.BootstrapToken = bootstrapToken; } } return new ClaimsIdentityCollection(new ClaimsIdentity[] { identity }); }
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); }
/// <summary> /// Authenticates a user by calling the authentication provider's Authenticate API. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <returns>The <see cref="AuthenticatedToken"/>.</returns> private AuthenticatedToken AuthenticateUser(string userName, string password) { #region Parameter Validation if (string.IsNullOrEmpty(userName)) { return(null); } #endregion UserNameSecurityToken token = new UserNameSecurityToken(userName, password); AuthenticatedToken userToken = provider.Authenticate(token); return(userToken); }
/// <summary> /// This method is called at the being of the thread that processes a request. /// </summary> protected override OperationContext ValidateRequest(RequestHeader requestHeader, RequestType requestType) { OperationContext context = base.ValidateRequest(requestHeader, requestType); if (requestType == RequestType.Write) { // reject all writes if no user provided. if (context.UserIdentity.TokenType == UserTokenType.Anonymous) { // construct translation object with default text. TranslationInfo info = new TranslationInfo( "NoWriteAllowed", "en-US", "Must provide a valid windows user before calling write."); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( StatusCodes.BadUserAccessDenied, "NoWriteAllowed", Namespaces.UserAuthentication, new LocalizedText(info))); } #if TODO SecurityToken securityToken = context.UserIdentity.GetSecurityToken(); // check for a kerberso token. KerberosReceiverSecurityToken kerberosToken = securityToken as KerberosReceiverSecurityToken; if (kerberosToken != null) { ImpersonationContext impersonationContext = new ImpersonationContext(); impersonationContext.Context = kerberosToken.WindowsIdentity.Impersonate(); lock (this.m_lock) { m_contexts.Add(context.RequestId, impersonationContext); } } // check for a user name token. UserNameSecurityToken userNameToken = securityToken as UserNameSecurityToken; if (userNameToken != null) { LogonUser(context, userNameToken); } #endif } return(context); }
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 override void WriteToken(XmlWriter writer, SecurityToken token) { UserNameSecurityToken unst = token as UserNameSecurityToken; if (unst == null) { throw new ArgumentException("Token must be of type UserNameSecurityToken", "token"); } writer.WriteStartElement("UserNameSecurityToken"); writer.WriteAttributeString("Id", unst.Id); writer.WriteAttributeString("Username", unst.UserName); writer.WriteAttributeString("Password", unst.Password); writer.WriteEndElement(); }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { UserNameSecurityToken token = new UserNameSecurityToken(username, password); string pwd = token.Password; var nonce = getNonce(); var datetime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss:fffZ"); string nonceToSend = Convert.ToBase64String(Encoding.UTF8.GetBytes(nonce)); SoapAuthHeader header = new SoapAuthHeader(string.Empty, username, pwd, nonceToSend, datetime); request.Headers.RemoveAt(0); request.Headers.Add(header); return(request); }
ValidateTokenCore(SecurityToken token) { if (token == null) { throw new ArgumentNullException("token"); } UserNameSecurityToken ut = token as UserNameSecurityToken; if (ut == null) { throw new InvalidOperationException(String.Format("Security token '{0}' is not supported", token)); } return(ValidateUserNamePasswordCore(ut.UserName, ut.Password)); }
/// <summary>Validates the username and password.</summary> /// <param name="token">The token.</param> /// <returns>A ClaimsIdentityCollection representing the identity in the token</returns> public override ReadOnlyCollection <ClaimsIdentity> ValidateToken(SecurityToken token) { if (token == null) { throw new ArgumentNullException("token"); } if (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 }; var identity = new ClaimsIdentity(claims); if (Configuration.SaveBootstrapContext) { if (RetainPassword) { identity.BootstrapContext = new BootstrapContext(unToken, this); } else { identity.BootstrapContext = new BootstrapContext(new UserNameSecurityToken(unToken.UserName, null), this); } } return(new List <ClaimsIdentity> { new ClaimsIdentity(claims, "Password") }.AsReadOnly()); }
/// <summary> /// Build an identity with claims from a username security token. /// </summary> /// <param name="userNameSecurityToken">Username security token from which to build the identity.</param> /// <param name="claims">Claims for the identity.</param> /// <returns>Identity with claims build from the username security token.</returns> private static IIdentity Build(UserNameSecurityToken userNameSecurityToken, IEnumerable <Claim> claims) { if (userNameSecurityToken == null) { throw new ArgumentNullException("userNameSecurityToken"); } if (claims == null) { throw new ArgumentNullException("claims"); } return(new ClaimsIdentity(claims, AuthenticationTypes.Password, userNameSecurityToken) { Label = userNameSecurityToken.UserName, }); }
void CompleteGetToken(IAsyncResult result) { UserNameSecurityToken token = (UserNameSecurityToken)this.tokenProvider.EndGetToken(result); if (token != null) { SecurityUtils.PrepareNetworkCredential(); this.credential = new NetworkCredential(token.UserName, token.Password); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString( SR.NoUserNameTokenProvided))); } }
private void Validate() { foreach (var check in _checks) { switch (check.Type) { case CustomSecurityCheckAttribute.CheckType.FromIP: { var clientip = Helper.GetClientIP(); if (clientip != check.value) { throw new SecurityTokenException("Unauthorized"); } } break; case CustomSecurityCheckAttribute.CheckType.HasRole: { UserNameSecurityToken securityToken = OperationContext.Current.IncomingMessageProperties.Security.IncomingSupportingTokens[0].SecurityToken as System.IdentityModel.Tokens.UserNameSecurityToken; string username = securityToken.UserName; var user = UserStore.GetUserByUsername(username); if ((user == null) || (!user.Roles.Contains(check.value))) { throw new SecurityTokenException("Unauthorized"); } } break; case CustomSecurityCheckAttribute.CheckType.UserLoggedIn: { UserNameSecurityToken securityToken = OperationContext.Current.IncomingMessageProperties.Security.IncomingSupportingTokens[0].SecurityToken as System.IdentityModel.Tokens.UserNameSecurityToken; string username = securityToken.UserName; string password = securityToken.Password; if (!UserStore.ValidateUser(username, password)) { throw new SecurityTokenException("Unauthorized"); } } break; default: throw new NotImplementedException(); } } }
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 ReadOnlyCollection <ClaimsIdentity> ValidateToken(SecurityToken token) { if (token == null) { throw new ArgumentNullException("token"); } UserNameSecurityToken usernameToken = token as UserNameSecurityToken; if (usernameToken == null) { throw new ArgumentException("token", "Not a UserNameSecurityToken"); } try { string userName = usernameToken.UserName; string password = usernameToken.Password; var identity = new GenericIdentity(userName); identity.AddClaim(new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(DateTime.UtcNow, "yyyy-MM-ddTHH:mm:ss.fffZ"), ClaimValueTypes.DateTime)); identity.AddClaim(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password)); if (this.Configuration.SaveBootstrapContext) { if (RetainPassword) { identity.BootstrapContext = new BootstrapContext(usernameToken, this); } else { identity.BootstrapContext = new BootstrapContext(new UserNameSecurityToken(usernameToken.UserName, null), this); } } TraceTokenValidationSuccess(token); List <ClaimsIdentity> identities = new List <ClaimsIdentity>(1); identities.Add(identity); return(identities.AsReadOnly()); } catch (Exception e) { TraceTokenValidationFailure(token, e.Message); throw e; } }
protected override System.Collections.ObjectModel.ReadOnlyCollection <System.IdentityModel.Policy.IAuthorizationPolicy> ValidateTokenCore(SecurityToken token) { UserNameSecurityToken userNameToken = token as UserNameSecurityToken; // Validate the information contained in the username token. For demonstration // purposes, this code just checks that the user name matches the password. if (userNameToken.UserName != userNameToken.Password) { throw new SecurityTokenValidationException("Invalid user name or password"); } // Create just one Claim instance for the username token - the name of the user. List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1); policies.Add(new AuthorizationPolicy()); return(policies.AsReadOnly()); }
public void TestThatCanValidateTokenReturnsTrueWhenSecurityTokenIsUserNameSecurityToken() { var fixture = new Fixture(); var userNamePasswordValidatorMock = MockRepository.GenerateMock <UserNamePasswordValidator>(); var identityBuilderMock = MockRepository.GenerateMock <IIdentityBuilder>(); var userNameSecurityToken = new UserNameSecurityToken(fixture.Create <string>(), fixture.Create <string>()); var userNameAsMailAddressSecurityTokenAuthenticator = new UserNameAsMailAddressSecurityTokenAuthenticator(userNamePasswordValidatorMock, identityBuilderMock); Assert.That(userNameAsMailAddressSecurityTokenAuthenticator, Is.Not.Null); var result = userNameAsMailAddressSecurityTokenAuthenticator.CanValidateToken(userNameSecurityToken); Assert.That(result, Is.Not.Null); }
public void TestThatBuildBuildsIdentityForUserNameSecurityTokenWithoutIdentityProperties() { var fixture = new Fixture(); var userName = fixture.Create <string>(); var password = fixture.Create <string>(); var userNameSecurityToken = new UserNameSecurityToken(userName, password); var identityBuilder = new IdentityBuilder(); Assert.That(identityBuilder, Is.Not.Null); var identity = identityBuilder.Build(userNameSecurityToken); Assert.That(identity, Is.Not.Null); Assert.That(identity, Is.TypeOf <ClaimsIdentity>()); var claimsIdentity = (ClaimsIdentity)identity; Assert.That(claimsIdentity, Is.Not.Null); Assert.That(claimsIdentity.Name, Is.Not.Null); Assert.That(claimsIdentity.Name, Is.Not.Empty); Assert.That(claimsIdentity.Name, Is.EqualTo(userName)); Assert.That(claimsIdentity.NameClaimType, Is.Not.Null); Assert.That(claimsIdentity.NameClaimType, Is.Not.Empty); Assert.That(claimsIdentity.NameClaimType, Is.EqualTo(ClaimTypes.Name)); Assert.That(claimsIdentity.RoleClaimType, Is.Not.Null); Assert.That(claimsIdentity.RoleClaimType, Is.Not.Empty); Assert.That(claimsIdentity.RoleClaimType, Is.EqualTo(ClaimTypes.Role)); Assert.That(claimsIdentity.IsAuthenticated, Is.True); Assert.That(claimsIdentity.AuthenticationType, Is.Not.Null); Assert.That(claimsIdentity.AuthenticationType, Is.Not.Empty); Assert.That(claimsIdentity.AuthenticationType, Is.EqualTo(AuthenticationTypes.Password)); Assert.That(claimsIdentity.Label, Is.Not.Null); Assert.That(claimsIdentity.Label, Is.Not.Empty); Assert.That(claimsIdentity.Label, Is.EqualTo(userName)); Assert.That(claimsIdentity.BootstrapToken, Is.Not.Null); Assert.That(claimsIdentity.BootstrapToken, Is.EqualTo(userNameSecurityToken)); Assert.That(claimsIdentity.Actor, Is.Null); Assert.That(claimsIdentity.Claims, Is.Not.Null); Assert.That(claimsIdentity.Claims, Is.Not.Empty); Assert.That(claimsIdentity.Claims.Count, Is.EqualTo(1)); ValidateClaim(claimsIdentity.Claims.Single(claim => string.Compare(claim.ClaimType, ClaimTypes.Name, StringComparison.Ordinal) == 0), userName, ClaimValueTypes.String); }
public override ReadOnlyCollection <ClaimsIdentity> ValidateToken(SecurityToken token) { UserNameSecurityToken userNameToken = token as UserNameSecurityToken; if (!userNameToken.UserName.Equals(userNameToken.Password)) { throw new SecurityTokenValidationException("Invalid credentials"); } var claim = new Claim(System.IdentityModel.Claims.ClaimTypes.Name, userNameToken.UserName); var identity = new ClaimsIdentity(new Claim[] { claim }, "NameToken"); return(new ReadOnlyCollection <ClaimsIdentity>( new ClaimsIdentity[] { identity })); }
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 static void KeyIdentifierClauseMethods() { XmlDocument doc = new XmlDocument(); XmlElement tokenXml = doc.CreateElement("ElementName"); XmlAttribute attr = doc.CreateAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); string attrValue = "Value for Attribute Name Id"; attr.Value = attrValue; tokenXml.Attributes.Append(attr); UserNameSecurityToken proofToken = new UserNameSecurityToken("user", "password"); var keyIdentifierGuid = Guid.NewGuid(); var internalTokenReference = CreateGenericKeyIdentifierClause(keyIdentifierGuid); GenericXmlSecurityToken gxst = new GenericXmlSecurityToken(tokenXml, proofToken, DateTime.UtcNow, DateTime.MaxValue, internalTokenReference, null, null); Assert.True(gxst.CanCreateKeyIdentifierClause <GenericXmlSecurityKeyIdentifierClause>()); Assert.Equal(internalTokenReference, gxst.CreateKeyIdentifierClause <GenericXmlSecurityKeyIdentifierClause>()); Assert.True(gxst.MatchesKeyIdentifierClause(CreateGenericKeyIdentifierClause(keyIdentifierGuid))); }
/// <summary> /// Sets the current user identity. /// </summary> public void SetUserIdentity(IUserIdentity identity) { string methodName = "IOPCSecurityPrivate.Logon"; try { IOPCSecurityPrivate server = BeginComCall <IOPCSecurityPrivate>(methodName, true); if (server != null) { int bAvailable = 0; server.IsAvailablePriv(out bAvailable); if (bAvailable != 0) { bool logoff = true; if (identity != null && identity.TokenType == UserTokenType.UserName) { UserNameSecurityToken securityToken = identity.GetSecurityToken() as UserNameSecurityToken; if (securityToken != null) { server.Logon(securityToken.UserName, securityToken.Password); logoff = false; } } if (logoff) { server.Logoff(); } } } } catch (Exception e) { ComCallError(methodName, e); } finally { EndComCall(methodName); } }
/// <summary> /// This method is called at the being of the thread that processes a request. /// </summary> protected override OperationContext ValidateRequest(RequestHeader requestHeader, RequestType requestType) { OperationContext context = base.ValidateRequest(requestHeader, requestType); if (context.UserIdentity != null) { SecurityToken securityToken = context.UserIdentity.GetSecurityToken(); // check for a user name token. UserNameSecurityToken userNameToken = securityToken as UserNameSecurityToken; if (userNameToken != null) { LogonUser(context, userNameToken); } } return(context); }
public static NetworkCredential GetUserNameCredential(SecurityTokenProviderContainer tokenProvider, TimeSpan timeout) { NetworkCredential credential = null; if ((tokenProvider != null) && (tokenProvider.TokenProvider != null)) { UserNameSecurityToken token = GetToken <UserNameSecurityToken>(tokenProvider.TokenProvider, timeout); if (token != null) { System.ServiceModel.Security.SecurityUtils.PrepareNetworkCredential(); credential = new NetworkCredential(token.UserName, token.Password); } } if (credential == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("NoUserNameTokenProvided"))); } return(credential); }
/// <summary> /// Authenticates using the guest credentials. /// </summary> /// <param name="provider">The provider.</param> /// <returns>The authentication token.</returns> private static AuthenticatedToken AuthenticateGuest(IAuthenticationProvider provider) { if (provider == null) { return(null); } //Read guest credentials from config settings. string guestUserName = UserManager.GuestUserName; string guestPassword = Constants.GuestPassword; if (!string.IsNullOrEmpty(guestUserName) && !string.IsNullOrEmpty(guestPassword)) { //Authenticate guest UserNameSecurityToken guestCredentials = new UserNameSecurityToken(guestUserName, guestPassword); AuthenticatedToken guestToken = provider.Authenticate(guestCredentials); return(guestToken); } return(null); }
ValidateTokenCore(SecurityToken token) { UserNameSecurityToken userNameToken = token as UserNameSecurityToken; // Validate the information contained in the username token. For demonstration // purposes, this code just checks that the user name matches the password. if (userNameToken.UserName != userNameToken.Password) { throw new SecurityTokenValidationException("Invalid user name or password"); } // Create just one Claim instance for the username token - the name of the user. DefaultClaimSet userNameClaimSet = new DefaultClaimSet( ClaimSet.System, new Claim(ClaimTypes.Name, userNameToken.UserName, Rights.PossessProperty)); List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(1); policies.Add(new MyAuthorizationPolicy(userNameClaimSet)); return(policies.AsReadOnly()); }