javax.security.auth.login.FailedLoginException Java Examples

The following examples show how to use javax.security.auth.login.FailedLoginException. 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: LegacyAuthenticationHandlerAdapter.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException, PreventedException {
    try {
        if (this.legacyHandler.authenticate(credentialsAdapter.convert(credential))) {
            final CredentialMetaData md;
            if (credential instanceof CredentialMetaData) {
                md = (CredentialMetaData) credential;
            } else {
                md = new BasicCredentialMetaData(credential);
            }
            return new DefaultHandlerResult(this, md);
        } else {
            throw new FailedLoginException(
                    String.format("%s failed to authenticate %s", this.getName(), credential));
        }
    } catch (final org.jasig.cas.authentication.handler.AuthenticationException e) {
        throw new GeneralSecurityException(
                String.format("%s failed to authenticate %s", this.getName(), credential), e);
    }
}
 
Example #2
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 #3
Source File: LCTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean login() throws LoginException {
    LCTest.logAction("login");
    if (callbackHandler == null) {
        throw new LoginException("No CallbackHandler available");
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);

    try {
        callbackHandler.handle(callbacks);
        username = ((NameCallback) callbacks[0]).getName();
        password = new String(((PasswordCallback) callbacks[1])
                .getPassword());
        if (username.equals(LCTest.USER_NAME) &&
                password.equals(LCTest.PASSWORD)) {
            succeeded = true;
            return true;
        }
        throw new FailedLoginException("Incorrect username/password!");
    } catch (IOException | UnsupportedCallbackException e) {
        throw new LoginException("Login failed: " + e.getMessage());
    }
}
 
Example #4
Source File: KryoTranscoderTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
public MockTicketGrantingTicket(final String id, final Credential credential, final Map<String, Object> principalAttributes) {
    this.id = id;
    final CredentialMetaData credentialMetaData = new BasicCredentialMetaData(credential);
    final DefaultAuthenticationBuilder builder = new DefaultAuthenticationBuilder();
    builder.setPrincipal(this.principalFactory.createPrincipal(USERNAME, principalAttributes));
    builder.setAuthenticationDate(new Date());
    builder.addCredential(credentialMetaData);
    builder.addAttribute(RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME, Boolean.TRUE);
    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 #5
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 #6
Source File: LCTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean login() throws LoginException {
    LCTest.logAction("login");
    if (callbackHandler == null) {
        throw new LoginException("No CallbackHandler available");
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);

    try {
        callbackHandler.handle(callbacks);
        username = ((NameCallback) callbacks[0]).getName();
        password = new String(((PasswordCallback) callbacks[1])
                .getPassword());
        if (username.equals(LCTest.USER_NAME) &&
                password.equals(LCTest.PASSWORD)) {
            succeeded = true;
            return true;
        }
        throw new FailedLoginException("Incorrect username/password!");
    } catch (IOException | UnsupportedCallbackException e) {
        throw new LoginException("Login failed: " + e.getMessage());
    }
}
 
Example #7
Source File: FileAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 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 (StringUtils.isBlank(passwordOnRecord)) {
            throw new AccountNotFoundException(username + " not found in backing file.");
        }
        final String password = credential.getPassword();
        if (StringUtils.isNotBlank(password) && this.getPasswordEncoder().encode(password).equals(passwordOnRecord)) {
            return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null);
        }
    } catch (final IOException e) {
        throw new PreventedException("IO error reading backing file", e);
    }
    throw new FailedLoginException();
}
 
Example #8
Source File: JConsole.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example #9
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 #10
Source File: DatawavePrincipalLoginModuleTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test(expected = FailedLoginException.class)
public void testInvalidLoginCertIssuerDenied() throws Exception {
    MockDatawaveCertVerifier.issuerSupported = false;
    DatawaveCredential datawaveCredential = new DatawaveCredential(testUserCert, null, null);
    callbackHandler.name = datawaveCredential.getUserName();
    callbackHandler.credential = datawaveCredential;
    
    expect(securityDomain.getKeyStore()).andReturn(keystore);
    expect(securityDomain.getTrustStore()).andReturn(truststore);
    
    replayAll();
    
    try {
        datawaveLoginModule.login();
    } finally {
        verifyAll();
    }
}
 
Example #11
Source File: DatawavePrincipalLoginModuleTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test(expected = FailedLoginException.class)
public void testInvalidLoginCertVerificationFailed() throws Exception {
    MockDatawaveCertVerifier.verify = false;
    DatawaveCredential datawaveCredential = new DatawaveCredential(testUserCert, null, null);
    callbackHandler.name = datawaveCredential.getUserName();
    callbackHandler.credential = datawaveCredential;
    
    expect(securityDomain.getKeyStore()).andReturn(keystore);
    expect(securityDomain.getTrustStore()).andReturn(truststore);
    
    replayAll();
    
    try {
        datawaveLoginModule.login();
    } finally {
        verifyAll();
    }
}
 
Example #12
Source File: JConsole.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example #13
Source File: OpenIdCredentialsAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException {
    final OpenIdCredential c = (OpenIdCredential) credential;

    final TicketGrantingTicket t = this.ticketRegistry.getTicket(c.getTicketGrantingTicketId(),
                    TicketGrantingTicket.class);

    if (t == null || t.isExpired()) {
        throw new FailedLoginException("TGT is null or expired.");
    }
    final Principal principal = t.getAuthentication().getPrincipal();
    if (!principal.getId().equals(c.getUsername())) {
        throw new FailedLoginException("Principal ID mismatch");
    }
    return new HandlerResult(this, new BasicCredentialMetaData(c), principal);
}
 
Example #14
Source File: LegacyAuthenticationHandlerAdapter.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException, PreventedException {
    try {
        if (this.legacyHandler.authenticate(credentialsAdapter.convert(credential))) {
            final CredentialMetaData md;
            if (credential instanceof CredentialMetaData) {
                md = (CredentialMetaData) credential;
            } else {
                md = new BasicCredentialMetaData(credential);
            }
            return new HandlerResult(this, md);
        } else {
            throw new FailedLoginException(
                    String.format("%s failed to authenticate %s", this.getName(), credential));
        }
    } catch (final AuthenticationException e) {
        throw new GeneralSecurityException(
                String.format("%s failed to authenticate %s", this.getName(), credential), e);
    }
}
 
Example #15
Source File: SimpleTestUsernamePasswordAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public HandlerResult authenticate(final Credential credential)
        throws GeneralSecurityException, PreventedException {

    final UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential;
    final String username = usernamePasswordCredential.getUsername();
    final String password = usernamePasswordCredential.getPassword();

    final Exception exception = this.usernameErrorMap.get(username);
    if (exception instanceof GeneralSecurityException) {
        throw (GeneralSecurityException) exception;
    } else if (exception instanceof PreventedException) {
        throw (PreventedException) exception;
    } else if (exception instanceof RuntimeException) {
        throw (RuntimeException) exception;
    } else if (exception != null) {
        logger.debug("Cannot throw checked exception {} since it is not declared by method signature.", exception);
    }

    if (StringUtils.hasText(username) && StringUtils.hasText(password) && username.equals(password)) {
        logger.debug("User [{}] was successfully authenticated.", username);
        return new DefaultHandlerResult(this, new BasicCredentialMetaData(credential));
    }
    logger.debug("User [{}] failed authentication", username);
    throw new FailedLoginException();
}
 
Example #16
Source File: JConsole.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example #17
Source File: LCTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean login() throws LoginException {
    LCTest.logAction("login");
    if (callbackHandler == null) {
        throw new LoginException("No CallbackHandler available");
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);

    try {
        callbackHandler.handle(callbacks);
        username = ((NameCallback) callbacks[0]).getName();
        password = new String(((PasswordCallback) callbacks[1])
                .getPassword());
        if (username.equals(LCTest.USER_NAME) &&
                password.equals(LCTest.PASSWORD)) {
            succeeded = true;
            return true;
        }
        throw new FailedLoginException("Incorrect username/password!");
    } catch (IOException | UnsupportedCallbackException e) {
        throw new LoginException("Login failed: " + e.getMessage());
    }
}
 
Example #18
Source File: HttpBasedServiceCredentialsAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException {
    final HttpBasedServiceCredential httpCredential = (HttpBasedServiceCredential) credential;
    if (!httpCredential.getService().getProxyPolicy().isAllowedProxyCallbackUrl(httpCredential.getCallbackUrl())) {
        logger.warn("Proxy policy for service [{}] cannot authorize the requested callbackurl [{}]",
                httpCredential.getService(), httpCredential.getCallbackUrl());
        throw new FailedLoginException(httpCredential.getCallbackUrl() + " cannot be authorized");
    }

    logger.debug("Attempting to authenticate {}", httpCredential);
    final URL callbackUrl = httpCredential.getCallbackUrl();
    if (!this.httpClient.isValidEndPoint(callbackUrl)) {
        throw new FailedLoginException(callbackUrl.toExternalForm() + " sent an unacceptable response status code");
    }
    return new DefaultHandlerResult(this, httpCredential, this.principalFactory.createPrincipal(httpCredential.getId()));
}
 
Example #19
Source File: JConsole.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example #20
Source File: AcceptUsersAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 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, this.principalFactory.createPrincipal(username), null);
}
 
Example #21
Source File: ClientAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected HandlerResult createResult(final ClientCredential credentials, final UserProfile profile)
    throws GeneralSecurityException, PreventedException {
    final String id;
    if (typedIdUsed) {
        id = profile.getTypedId();
    } else {
        id = profile.getId();
    }
    if (StringUtils.isNotBlank(id)) {
        credentials.setUserProfile(profile);
        return new DefaultHandlerResult(
            this,
            new BasicCredentialMetaData(credentials),
            this.principalFactory.createPrincipal(id, profile.getAttributes()));
    }
    throw new FailedLoginException("No identifier found for this user profile: " + profile);
}
 
Example #22
Source File: RejectUsersAuthenticationHandlerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test(expected=FailedLoginException.class)
public void testFailsUserInMap() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    c.setUsername("scott");
    c.setPassword("rutgers");
    this.authenticationHandler.authenticate(c);
}
 
Example #23
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 #24
Source File: QueryAndEncodeDatabaseAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test(expected = FailedLoginException.class)
public void verifyAuthenticationMultipleAccounts() throws Exception {
    final QueryAndEncodeDatabaseAuthenticationHandler q =
            new QueryAndEncodeDatabaseAuthenticationHandler(this.dataSource, buildSql(),
                    ALG_NAME);
    q.authenticateUsernamePasswordInternal(
            TestUtils.getCredentialsWithDifferentUsernameAndPassword("user0", "password0"));

}
 
Example #25
Source File: X509CredentialsAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 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
        final 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 DefaultHandlerResult(this, x509Credential, this.principalFactory.createPrincipal(x509Credential.getId()));
    }
    throw new FailedLoginException();
}
 
Example #26
Source File: AbstractPreAndPostProcessingAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 **/
@Override
public final HandlerResult authenticate(final Credential credential)
        throws GeneralSecurityException, PreventedException {

    if (!preAuthenticate(credential)) {
        throw new FailedLoginException();
    }

    return postAuthenticate(credential, doAuthentication(credential));
}
 
Example #27
Source File: RadiusAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    final String password = getPasswordEncoder().encode(credential.getPassword());
    final String username = credential.getUsername();
    
    for (final RadiusServer radiusServer : this.servers) {
        logger.debug("Attempting to authenticate {} at {}", username, radiusServer);
        try {
            final RadiusResponse response = radiusServer.authenticate(username, password);
            if (response != null) {
                 return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null);
            } 
                            
            if (!this.failoverOnAuthenticationFailure) {
                throw new FailedLoginException("Radius authentication failed for user " + username);
            }
            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("Radius authentication failed for user " + username);
}
 
Example #28
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 #29
Source File: AbstractClientAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 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 Credentials credentials = clientCredentials.getCredentials();
    final String clientName = credentials.getClientName();
    logger.debug("clientName : {}", clientName);

    // get client
    final Client<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(credentials, webContext);
    logger.debug("userProfile : {}", userProfile);

    if (userProfile != null) {
        return createResult(clientCredentials, userProfile);
    }

    throw new FailedLoginException("Provider did not produce a user profile for: " + clientCredentials);
}
 
Example #30
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);
}