org.jasig.cas.authentication.principal.SimplePrincipal Java Examples

The following examples show how to use org.jasig.cas.authentication.principal.SimplePrincipal. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SearchModeSearchDatabaseAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    final String username = credential.getUsername();
    final String encyptedPassword = getPasswordEncoder().encode(credential.getPassword());
    final int count;
    try {
        count = getJdbcTemplate().queryForObject(this.sql, Integer.class, username, encyptedPassword);
    } catch (final DataAccessException e) {
        throw new PreventedException("SQL exception while executing query for " + username, e);
    }
    if (count == 0) {
        throw new FailedLoginException(username + " not found with SQL query.");
    }
    return createHandlerResult(credential, new SimplePrincipal(username), null);
}
 
Example #2
Source File: PolicyBasedAuthenticationManagerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new named mock authentication handler that either successfully validates all credentials or fails to
 * validate all credentials.
 *
 * @param name Authentication handler name.
 * @param success True to authenticate all credentials, false to fail all credentials.
 *
 * @return New mock authentication handler instance.
 *
 * @throws Exception On errors.
 */
private static AuthenticationHandler newMockHandler(final String name, final boolean success) throws Exception {
    final AuthenticationHandler mock = mock(AuthenticationHandler.class);
    when(mock.getName()).thenReturn(name);
    when(mock.supports(any(Credential.class))).thenReturn(true);
    if (success) {
        final HandlerResult result = new HandlerResult(
                mock,
                mock(CredentialMetaData.class),
                new SimplePrincipal("nobody"));
        when(mock.authenticate(any(Credential.class))).thenReturn(result);
    } else {
        when(mock.authenticate(any(Credential.class))).thenThrow(new FailedLoginException());
    }
    return mock;
}
 
Example #3
Source File: FileAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {
    try {
        
        final String username = credential.getUsername();
        final String passwordOnRecord = getPasswordOnRecord(username);
        if (passwordOnRecord == null) {
            throw new AccountNotFoundException(username + " not found in backing file.");
        }
        if (credential.getPassword() != null
                && this.getPasswordEncoder().encode(credential.getPassword()).equals(passwordOnRecord)) {
            return createHandlerResult(credential, new SimplePrincipal(username), null);
        }
    } catch (final IOException e) {
        throw new PreventedException("IO error reading backing file", e);
    }
    throw new FailedLoginException();
}
 
Example #4
Source File: RadiusAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    final String username = credential.getUsername();
    for (final RadiusServer radiusServer : this.servers) {
        logger.debug("Attempting to authenticate {} at {}", username, radiusServer);
        try {
            if (radiusServer.authenticate(username, credential.getPassword())) {
                return createHandlerResult(credential, new SimplePrincipal(username), null);
            } 
            
            if (!this.failoverOnAuthenticationFailure) {
                throw new FailedLoginException();
            }
            logger.debug("failoverOnAuthenticationFailure enabled -- trying next server");
        } catch (final PreventedException e) {
            if (!this.failoverOnException) {
                throw e;
            }
            logger.warn("failoverOnException enabled -- trying next server.", e);
        }
    }
    throw new FailedLoginException();
}
 
Example #5
Source File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();

    if (principal != null) {

        logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(new SimplePrincipal(
                principal.getName()));
    }

    logger.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
 
Example #6
Source File: PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final String remoteUser = request.getRemoteUser();

    if (StringUtils.hasText(remoteUser)) {
        logger.debug("Remote  User [{}] found in HttpServletRequest", remoteUser);
        return new PrincipalBearingCredential(new SimplePrincipal(remoteUser));
    }

    logger.debug("Remote User not found in HttpServletRequest.");

    return null;
}
 
Example #7
Source File: JCSIFSpnegoAuthenticationHandlerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSimpleCredentials() {
    String myNtlmUser = "DOMAIN\\Username";
    String myNtlmUserWithNoDomain = "Username";
    String myKerberosUser = "[email protected]";

    this.authenticationHandler.setPrincipalWithDomainName(true);
    assertEquals(new SimplePrincipal(myNtlmUser), this.authenticationHandler
            .getSimplePrincipal(myNtlmUser, true));
    assertEquals(new SimplePrincipal(myNtlmUserWithNoDomain), this.authenticationHandler
            .getSimplePrincipal(myNtlmUserWithNoDomain, false));
    assertEquals(new SimplePrincipal(myKerberosUser), this.authenticationHandler
            .getSimplePrincipal(myKerberosUser, false));

    this.authenticationHandler.setPrincipalWithDomainName(false);
    assertEquals(new SimplePrincipal("Username"), this.authenticationHandler
            .getSimplePrincipal(myNtlmUser, true));
    assertEquals(new SimplePrincipal("Username"), this.authenticationHandler
            .getSimplePrincipal(myNtlmUserWithNoDomain, true));
    assertEquals(new SimplePrincipal("Username"), this.authenticationHandler
            .getSimplePrincipal(myKerberosUser, false));
}
 
Example #8
Source File: AcceptUsersAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    final String username = credential.getUsername();
    final String cachedPassword = this.users.get(username);

    if (cachedPassword == null) {
       logger.debug("{} was not found in the map.", username);
       throw new AccountNotFoundException(username + " not found in backing map.");
    }

    final String encodedPassword = this.getPasswordEncoder().encode(credential.getPassword());
    if (!cachedPassword.equals(encodedPassword)) {
        throw new FailedLoginException();
    }
    return createHandlerResult(credential, new SimplePrincipal(username), null);
}
 
Example #9
Source File: KryoTranscoderTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
public MockTicketGrantingTicket(final String id, final Credential credential) {
    this.id = id;
    final CredentialMetaData credentialMetaData = new BasicCredentialMetaData(credential);
    final AuthenticationBuilder builder = new AuthenticationBuilder();
    final Map<String, Object> attributes = new HashMap<String, Object>();
    attributes.put("nickname", "bob");
    builder.setPrincipal(new SimplePrincipal("handymanbob", attributes));
    builder.setAuthenticationDate(new Date());
    builder.addCredential(credentialMetaData);
    final AuthenticationHandler handler = new MockAuthenticationHandler();
    try {
        builder.addSuccess(handler.getName(), handler.authenticate(credential));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
    builder.addFailure(handler.getName(), FailedLoginException.class);
    this.authentication = builder.build();
}
 
Example #10
Source File: Saml10SuccessResponseViewTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testResponseWithoutAuthMethod() throws Exception {
    final Map<String, Object> model = new HashMap<String, Object>();

    final Map<String, Object> attributes = new HashMap<String, Object>();
    attributes.put("testAttribute", "testValue");
    final SimplePrincipal principal = new SimplePrincipal("testPrincipal", attributes);

    final Authentication primary = TestUtils.getAuthentication(principal);

    final Assertion assertion = new ImmutableAssertion(
            primary, Collections.singletonList(primary), TestUtils.getService(), true);
    model.put("assertion", assertion);

    final MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    this.response.renderMergedOutputModel(model, new MockHttpServletRequest(), servletResponse);
    final String written = servletResponse.getContentAsString();

    assertTrue(written.contains("testPrincipal"));
    assertTrue(written.contains("testAttribute"));
    assertTrue(written.contains("testValue"));
    assertTrue(written.contains("urn:oasis:names:tc:SAML:1.0:am:unspecified"));
}
 
Example #11
Source File: SpnegoCredentialsTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testToStringWithPrincipal() {
    final SpnegoCredential credentials = new SpnegoCredential(new byte[] {});
    final Principal principal = new SimplePrincipal("test");
    credentials.setPrincipal(principal);
    assertEquals("test", credentials.toString());
}
 
Example #12
Source File: JCIFSSpnegoAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
protected SimplePrincipal getSimplePrincipal(final String name, final boolean isNtlm) {
    if (this.principalWithDomainName) {
        return new SimplePrincipal(name);
    }
    if (isNtlm) {
        return Pattern.matches("\\S+\\\\\\S+", name)
                ? new SimplePrincipal(name.split("\\\\")[1])
                : new SimplePrincipal(name);
    }
    return new SimplePrincipal(name.split("@")[0]);
}
 
Example #13
Source File: X509CredentialsAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected final HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {

    final X509CertificateCredential x509Credential = (X509CertificateCredential) credential;
    final X509Certificate[] certificates = x509Credential.getCertificates();

    X509Certificate clientCert = null;
    boolean hasTrustedIssuer = false;
    for (int i = certificates.length - 1; i >= 0; i--) {
        final X509Certificate certificate = certificates[i];
        logger.debug("Evaluating {}", CertUtils.toString(certificate));

        validate(certificate);

        if (!hasTrustedIssuer) {
            hasTrustedIssuer = isCertificateFromTrustedIssuer(certificate);
        }

        // getBasicConstraints returns pathLenContraint which is generally
        // >=0 when this is a CA cert and -1 when it's not
        int pathLength = certificate.getBasicConstraints();
        if (pathLength < 0) {
            logger.debug("Found valid client certificate");
            clientCert = certificate;
        } else {
            logger.debug("Found valid CA certificate");
        }
    }
    if (hasTrustedIssuer && clientCert != null) {
        x509Credential.setCertificate(clientCert);
        return new HandlerResult(this, x509Credential, new SimplePrincipal(x509Credential.getId()));
    }
    throw new FailedLoginException();
}
 
Example #14
Source File: JCIFSSpnegoAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * @deprecated As of 4.1. Use {@link #getPrincipal(String, boolean)}
 * Gets the simple principal from the given name.
 *
 * @param name the name
 * @param isNtlm the is ntlm
 * @return the simple principal
 */
@Deprecated
protected SimplePrincipal getSimplePrincipal(final String name, final boolean isNtlm) {
    logger.warn("getSimplePrincipal() is deprecated and will be removed. Consider getPrincipal() instead.");

    if (this.principalWithDomainName) {
        return (SimplePrincipal) new DefaultPrincipalFactory().createPrincipal(name);
    }
    if (isNtlm) {
        return Pattern.matches("\\S+\\\\\\S+", name)
                ? (SimplePrincipal) new DefaultPrincipalFactory().createPrincipal(name.split("\\\\")[1])
                : (SimplePrincipal) new DefaultPrincipalFactory().createPrincipal(name);
    }
    return (SimplePrincipal) new DefaultPrincipalFactory().createPrincipal(name.split("@")[0]);
}
 
Example #15
Source File: ClientAuthenticationHandler.java    From oxTrust with MIT License 5 votes vote down vote up
/**
 * {@InheritDoc}
 */
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
	final ClientCredential clientCredentials = (ClientCredential) credential;
	final OpenIdCredentials openIdCredentials = clientCredentials.getOpenIdCredentials();
	logger.debug("Client credentials : '{}'", clientCredentials);

	final String clientName = openIdCredentials.getClientName();
	logger.debug("Client name : '{}'", clientName);

	// Web context
	final ServletExternalContext servletExternalContext = (ServletExternalContext) ExternalContextHolder.getExternalContext();
	final HttpServletRequest request = (HttpServletRequest) servletExternalContext.getNativeRequest();
	final HttpServletResponse response = (HttpServletResponse) servletExternalContext.getNativeResponse();
	final WebContext webContext = new J2EContext(request, response);

	// Get user profile
	final UserProfile userProfile = this.client.getUserProfile(openIdCredentials, webContext);
	logger.debug("userProfile : {}", userProfile);

	if (userProfile != null) {
		final String id = userProfile.getId();
		if (StringHelper.isNotEmpty(id)) {
			openIdCredentials.setUserProfile(userProfile);

			return new HandlerResult(this, clientCredentials, new SimplePrincipal(id, userProfile.getAttributes()));
		}
	}

	throw new FailedLoginException("Provider did not produce profile for " + clientCredentials);
}
 
Example #16
Source File: RejectUsersAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    final String username = credential.getUsername();
    if (this.users.contains(username)) {
        throw new FailedLoginException();
    }

    return createHandlerResult(credential, new SimplePrincipal(username), null);
}
 
Example #17
Source File: RemoteAddressAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException {
    final RemoteAddressCredential c = (RemoteAddressCredential) credential;
    try {
        final InetAddress inetAddress = InetAddress.getByName(c.getRemoteAddress().trim());
        if (containsAddress(this.inetNetwork, this.inetNetmask, inetAddress)) {
            return new HandlerResult(this, c, new SimplePrincipal(c.getId()));
        }
    } catch (final UnknownHostException e) {
        logger.debug("Unknown host {}", c.getRemoteAddress());
    }
    throw new FailedLoginException(c.getRemoteAddress() + " not in allowed range.");
}
 
Example #18
Source File: Saml10SuccessResponseViewTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponse() throws Exception {
    final Map<String, Object> model = new HashMap<String, Object>();

    final Map<String, Object> attributes = new HashMap<String, Object>();
    attributes.put("testAttribute", "testValue");
    attributes.put("testEmptyCollection", Collections.emptyList());
    attributes.put("testAttributeCollection", Arrays.asList(new String[] {"tac1", "tac2"}));
    final SimplePrincipal principal = new SimplePrincipal("testPrincipal", attributes);

    final Map<String, Object> authAttributes = new HashMap<String, Object>();
    authAttributes.put(
            SamlAuthenticationMetaDataPopulator.ATTRIBUTE_AUTHENTICATION_METHOD,
            SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT);
    authAttributes.put("testSamlAttribute", "value");

    final Authentication primary = TestUtils.getAuthentication(principal, authAttributes);
    final Assertion assertion = new ImmutableAssertion(
            primary, Collections.singletonList(primary), TestUtils.getService(), true);
    model.put("assertion", assertion);

    final MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    this.response.renderMergedOutputModel(model, new MockHttpServletRequest(), servletResponse);
    final String written = servletResponse.getContentAsString();

    assertTrue(written.contains("testPrincipal"));
    assertTrue(written.contains("testAttribute"));
    assertTrue(written.contains("testValue"));
    assertFalse(written.contains("testEmptyCollection"));
    assertTrue(written.contains("testAttributeCollection"));
    assertTrue(written.contains("tac1"));
    assertTrue(written.contains("tac2"));
    assertTrue(written.contains(SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT));
    assertTrue(written.contains("AuthenticationMethod"));
    assertTrue(written.contains("AssertionID"));
}
 
Example #19
Source File: Saml10SuccessResponseViewTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseWithNoAttributes() throws Exception {
    final Map<String, Object> model = new HashMap<String, Object>();

    final SimplePrincipal principal = new SimplePrincipal("testPrincipal");

    final Map<String, Object> authAttributes = new HashMap<String, Object>();
    authAttributes.put(
            SamlAuthenticationMetaDataPopulator.ATTRIBUTE_AUTHENTICATION_METHOD,
            SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT);
    authAttributes.put("testSamlAttribute", "value");

    final Authentication primary = TestUtils.getAuthentication(principal, authAttributes);

    final Assertion assertion = new ImmutableAssertion(
            primary, Collections.singletonList(primary), TestUtils.getService(), true);
    model.put("assertion", assertion);

    final MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    this.response.renderMergedOutputModel(model, new MockHttpServletRequest(), servletResponse);
    final String written = servletResponse.getContentAsString();

    assertTrue(written.contains("testPrincipal"));
    assertTrue(written.contains(SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT));
    assertTrue(written.contains("AuthenticationMethod"));
}
 
Example #20
Source File: TestOneTimePasswordAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public HandlerResult authenticate(final Credential credential)
        throws GeneralSecurityException, PreventedException {
    final OneTimePasswordCredential otp = (OneTimePasswordCredential) credential;
    final String valueOnRecord = credentialMap.get(otp.getId());
    if (otp.getPassword().equals(credentialMap.get(otp.getId()))) {
        return new HandlerResult(this, new BasicCredentialMetaData(otp), new SimplePrincipal(otp.getId()));
    }
    throw new FailedLoginException();
}
 
Example #21
Source File: OauthPersonDirectoryPrincipalResolver.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public Principal resolve(Credential credential) {
    logger.debug("Attempting to resolve a principal...");

    if (credential instanceof ClientCredential){
        // do nothing
    } else {
        throw new RuntimeException("用户数据转换异常!");
    }

    ClientCredential oauthCredential = (ClientCredential) credential;
    UserProfile userProfile = oauthCredential.getUserProfile();
    logger.info("userProfile = {}", userProfile);


    //String principalId = oauthCredential.getUserProfile().getId();
    String principalId = oauthCredential.getId();
    if (principalId == null) {
        logger.debug("Got null for extracted principal ID; returning null.");
        return null;
    }

    logger.debug("Creating SimplePrincipal for [{}]", principalId);
    //UserProfile userProfile = oauthCredential.getUserProfile();
    final Map<String, Object> attributes = userProfile.getAttributes();

    if (attributes == null & !this.returnNullIfNoAttributes) {
        return new SimplePrincipal(principalId);
    }

    if (attributes == null) {
        return null;
    }

    return new SimplePrincipal(principalId, attributes);
}
 
Example #22
Source File: JpaTicketRegistryTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
static TicketGrantingTicket newTGT() {
    final Principal principal = new SimplePrincipal(
            "bob", Collections.singletonMap("displayName", (Object) "Bob"));
    return new TicketGrantingTicketImpl(
            ID_GENERATOR.getNewTicketId("TGT"),
            TestUtils.getAuthentication(principal),
            EXP_POLICY_TGT);
}
 
Example #23
Source File: RememberMeDelegatingExpirationPolicyTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testTicketExpirationWithRememberMe() {
    final Authentication authentication = TestUtils.getAuthentication(
            new SimplePrincipal("test"),
            Collections.<String, Object>singletonMap(
                    RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME, true));
    final TicketGrantingTicketImpl t = new TicketGrantingTicketImpl("111", authentication, this.p);
    assertFalse(t.isExpired());
    t.grantServiceTicket("55", TestUtils.getService(), this.p, false);
    assertTrue(t.isExpired());

}
 
Example #24
Source File: ClientAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final ClientCredential clientCredentials = (ClientCredential) credential;
    logger.debug("clientCredentials : {}", clientCredentials);

    final String clientName = clientCredentials.getCredentials().getClientName();
    logger.debug("clientName : {}", clientName);

    // get client
    final Client<org.pac4j.core.credentials.Credentials, UserProfile> client = this.clients.findClient(clientName);
    logger.debug("client : {}", client);

    // web context
    final ServletExternalContext servletExternalContext = (ServletExternalContext) ExternalContextHolder.getExternalContext();
    final HttpServletRequest request = (HttpServletRequest) servletExternalContext.getNativeRequest();
    final HttpServletResponse response = (HttpServletResponse) servletExternalContext.getNativeResponse();
    final WebContext webContext = new J2EContext(request, response);

    // get user profile
    final UserProfile userProfile = client.getUserProfile(clientCredentials.getCredentials(), webContext);
    logger.debug("userProfile : {}", userProfile);

    if (userProfile != null && StringUtils.isNotBlank(userProfile.getTypedId())) {
        clientCredentials.setUserProfile(userProfile);
        return new HandlerResult(
                this,
                new BasicCredentialMetaData(credential),
                new SimplePrincipal(userProfile.getTypedId(), userProfile.getAttributes()));
    }

    throw new FailedLoginException("Provider did not produce profile for " + clientCredentials);
}
 
Example #25
Source File: HttpBasedServiceCredentialsAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException {
    final HttpBasedServiceCredential httpCredential = (HttpBasedServiceCredential) credential;
    if (this.requireSecure && !httpCredential.getCallbackUrl().getProtocol().equals(PROTOCOL_HTTPS)) {
        logger.debug("Authentication failed because url was not secure.");
        throw new FailedLoginException(httpCredential.getCallbackUrl() + " is not an HTTPS endpoint as required.");
    }
    logger.debug("Attempting to authenticate {}", httpCredential);
    if (!this.httpClient.isValidEndPoint(httpCredential.getCallbackUrl())) {
        throw new FailedLoginException(
                httpCredential.getCallbackUrl() + " sent an unacceptable response status code");
    }
    return new HandlerResult(this, httpCredential, new SimplePrincipal(httpCredential.getId()));
}
 
Example #26
Source File: LdapAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CAS principal with attributes if the LDAP entry contains principal attributes.
 *
 * @param username Username that was successfully authenticated which is used for principal ID when
 *                 {@link #setPrincipalIdAttribute(String)} is not specified.
 * @param ldapEntry LDAP entry that may contain principal attributes.
 *
 * @return Principal if the LDAP entry contains at least a principal ID attribute value, null otherwise.
 *
 * @throws LoginException On security policy errors related to principal creation.
 */
protected Principal createPrincipal(final String username, final LdapEntry ldapEntry) throws LoginException {
    final String id;
    if (this.principalIdAttribute != null) {
        final LdapAttribute principalAttr = ldapEntry.getAttribute(this.principalIdAttribute);
        if (principalAttr == null || principalAttr.size() == 0) {
            throw new LoginException(this.principalIdAttribute + " attribute not found for " + username);
        }
        if (principalAttr.size() > 1) {
            if (this.allowMultiplePrincipalAttributeValues) {
                logger.warn(
                        "Found multiple values for principal ID attribute: {}. Using first value={}.",
                        principalAttr,
                        principalAttr.getStringValue());
            } else {
                throw new LoginException("Multiple principal values not allowed: " + principalAttr);
            }
        }
        id = principalAttr.getStringValue();
    } else {
        id = username;
    }
    final Map<String, Object> attributeMap = new LinkedHashMap<String, Object>(this.principalAttributeMap.size());
    for (String ldapAttrName : this.principalAttributeMap.keySet()) {
        final LdapAttribute attr = ldapEntry.getAttribute(ldapAttrName);
        if (attr != null) {
            logger.debug("Found principal attribute: {}", attr);
            final String principalAttrName = this.principalAttributeMap.get(ldapAttrName);
            if (attr.size() > 1) {
                attributeMap.put(principalAttrName, attr.getStringValues());
            } else {
                attributeMap.put(principalAttrName, attr.getStringValue());
            }
        }
    }
    return new SimplePrincipal(id, attributeMap);
}
 
Example #27
Source File: PrincipalBearingCredentialsToPrincipalResolverTests.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
@Test
public void testSupports() {
    assertTrue(this.resolver.supports(new PrincipalBearingCredential(new SimplePrincipal("test"))));
    assertFalse(this.resolver.supports(new UsernamePasswordCredential()));
    assertFalse(this.resolver.supports(null));
}
 
Example #28
Source File: SpnegoCredentialsToPrincipalResolverTests.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
@Test
public void testValidCredentials() {
    this.spnegoCredentials.setPrincipal(new SimplePrincipal("test"));
    assertEquals("test", this.resolver.resolve(this.spnegoCredentials)
            .getId());
}
 
Example #29
Source File: CentralAuthenticationServiceImpl.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
/**
 * @throws IllegalArgumentException if the ServiceTicketId or the Service
 * are null.
 */
@Audit(
    action="SERVICE_TICKET_VALIDATE",
    actionResolverName="VALIDATE_SERVICE_TICKET_RESOLVER",
    resourceResolverName="VALIDATE_SERVICE_TICKET_RESOURCE_RESOLVER")
@Profiled(tag="VALIDATE_SERVICE_TICKET", logFailuresSeparately = false)
@Transactional(readOnly = false)
public Assertion validateServiceTicket(final String serviceTicketId, final Service service) throws TicketException {
    Assert.notNull(serviceTicketId, "serviceTicketId cannot be null");
    Assert.notNull(service, "service cannot be null");
 
    final ServiceTicket serviceTicket =  this.serviceTicketRegistry.getTicket(serviceTicketId, ServiceTicket.class);

    if (serviceTicket == null) {
        logger.info("ServiceTicket [{}] does not exist.", serviceTicketId);
        throw new InvalidTicketException(serviceTicketId);
    }

    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    verifyRegisteredServiceProperties(registeredService, serviceTicket.getService());
    
    try {
        synchronized (serviceTicket) {
            if (serviceTicket.isExpired()) {
                logger.info("ServiceTicket [{}] has expired.", serviceTicketId);
                throw new InvalidTicketException(serviceTicketId);
            }

            if (!serviceTicket.isValidFor(service)) {
                logger.error("ServiceTicket [{}] with service [{}] does not match supplied service [{}]",
                        serviceTicketId, serviceTicket.getService().getId(), service);
                throw new TicketValidationException(serviceTicket.getService());
            }
        }

        final TicketGrantingTicket root = serviceTicket.getGrantingTicket().getRoot();
        final Authentication authentication = getAuthenticationSatisfiedByPolicy(
                root, new ServiceContext(serviceTicket.getService(), registeredService));
        final Principal principal = authentication.getPrincipal();

        Map<String, Object> attributesToRelease = this.defaultAttributeFilter.filter(principal.getId(),
                principal.getAttributes(), registeredService);
        if (registeredService.getAttributeFilter() != null) {
            attributesToRelease = registeredService.getAttributeFilter().filter(principal.getId(),
                    attributesToRelease, registeredService);
        }

        final String principalId = determinePrincipalIdForRegisteredService(principal, registeredService, serviceTicket);
        final Principal modifiedPrincipal = new SimplePrincipal(principalId, attributesToRelease);
        final AuthenticationBuilder builder = AuthenticationBuilder.newInstance(authentication);
        builder.setPrincipal(modifiedPrincipal);

        return new ImmutableAssertion(
                builder.build(),
                serviceTicket.getGrantingTicket().getChainedAuthentications(),
                serviceTicket.getService(),
                serviceTicket.isFromNewLogin());
    } finally {
        if (serviceTicket.isExpired()) {
            this.serviceTicketRegistry.deleteTicket(serviceTicketId);
        }
    }
}
 
Example #30
Source File: NtlmAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
@Override
protected final HandlerResult doAuthentication(
        final Credential credential) throws GeneralSecurityException, PreventedException {

    final SpnegoCredential ntlmCredential = (SpnegoCredential) credential;
    final byte[] src = ntlmCredential.getInitToken();

    UniAddress dc = null;

    boolean success = false;
    try {
        if (this.loadBalance) {
            // find the first dc that matches the includepattern
            if(this.includePattern != null){
                NbtAddress [] dcs  = NbtAddress.getAllByName(this.domainController, 0x1C, null, null);
                for (NbtAddress dc2 : dcs) {
                    if(dc2.getHostAddress().matches(this.includePattern)){
                        dc = new UniAddress(dc2);
                        break;
                    }
                }
            } else {
                dc = new UniAddress(NbtAddress.getByName(this.domainController,
                        0x1C, null));
            }
        } else {
            dc = UniAddress.getByName(this.domainController, true);
        }
        final byte[] challenge = SmbSession.getChallenge(dc);

        switch (src[8]) {
            case 1:
                logger.debug("Type 1 received");
                final Type1Message type1 = new Type1Message(src);
                final Type2Message type2 = new Type2Message(type1,
                        challenge, null);
                logger.debug("Type 2 returned. Setting next token.");
                ntlmCredential.setNextToken(type2.toByteArray());
            case 3:
                logger.debug("Type 3 received");
                final Type3Message type3 = new Type3Message(src);
                final byte[] lmResponse = type3.getLMResponse() == null ? new byte[0] : type3.getLMResponse();
                byte[] ntResponse = type3.getNTResponse() == null ? new byte[0] : type3.getNTResponse();
                final NtlmPasswordAuthentication ntlm = new NtlmPasswordAuthentication(
                        type3.getDomain(), type3.getUser(), challenge,
                        lmResponse, ntResponse);
                logger.debug("Trying to authenticate {} with domain controller", type3.getUser());
                try {
                    SmbSession.logon(dc, ntlm);
                    ntlmCredential.setPrincipal(new SimplePrincipal(type3.getUser()));
                    success = true;
                } catch (final SmbAuthException sae) {
                    throw new FailedLoginException(sae.getMessage());
                }
            default:
                logger.debug("Unknown type: {}", src[8]);
        }
    } catch (final Exception e) {
        throw new FailedLoginException(e.getMessage());
    }

    if (!success) {
        throw new FailedLoginException();
    }
    return new HandlerResult(this, new BasicCredentialMetaData(ntlmCredential), ntlmCredential.getPrincipal());
}