Java Code Examples for javax.security.auth.login.FailedLoginException

The following are top voted examples for showing how to use javax.security.auth.login.FailedLoginException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: cas-5.1.0   File: DefaultWebflowConfigurer.java   View source code 6 votes vote down vote up
/**
 * Create handle authentication failure action.
 *
 * @param flow the flow
 */
protected void createHandleAuthenticationFailureAction(final Flow flow) {
    final ActionState handler = createActionState(flow,
            "handleAuthenticationFailure",
            createEvaluateAction("authenticationExceptionHandler"));
    createTransitionForState(handler, AccountDisabledException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_ACCOUNT_DISABLED);
    createTransitionForState(handler, AccountLockedException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_ACCOUNT_LOCKED);
    createTransitionForState(handler, AccountPasswordMustChangeException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_MUST_CHANGE_PASSWORD);
    createTransitionForState(handler, CredentialExpiredException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_EXPIRED_PASSWORD);
    createTransitionForState(handler, InvalidLoginLocationException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_INVALID_WORKSTATION);
    createTransitionForState(handler, InvalidLoginTimeException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_INVALID_AUTHENTICATION_HOURS);
    createTransitionForState(handler, FailedLoginException.class.getSimpleName(), CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM);
    createTransitionForState(handler, AccountNotFoundException.class.getSimpleName(), CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM);
    createTransitionForState(handler, UnauthorizedServiceForPrincipalException.class.getSimpleName(), CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM);
    createTransitionForState(handler, PrincipalException.class.getSimpleName(), CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM);
    createTransitionForState(handler, UnsatisfiedAuthenticationPolicyException.class.getSimpleName(), CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM);
    createTransitionForState(handler, UnauthorizedAuthenticationException.class.getSimpleName(), CasWebflowConstants.VIEW_ID_AUTHENTICATION_BLOCKED);
    createStateDefaultTransition(handler, CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM);

}
 
Example 2
Project: cas-5.1.0   File: AcceptUsersAuthenticationHandler.java   View source code 6 votes vote down vote up
@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential,
                                                             final String originalPassword)
        throws GeneralSecurityException, PreventedException {
    if (this.users == null || this.users.isEmpty()) {
        throw new FailedLoginException("No user can be accepted because none is defined");
    }
    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.");
    }

    if (!StringUtils.equals(credential.getPassword(), cachedPassword)) {
        throw new FailedLoginException();
    }
    final List<MessageDescriptor> list = new ArrayList<>();
    return createHandlerResult(credential, this.principalFactory.createPrincipal(username), list);
}
 
Example 3
Project: springboot-shiro-cas-mybatis   File: PolicyBasedAuthenticationManagerTests.java   View source code 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 Principal p = new DefaultPrincipalFactory().createPrincipal("nobody");

        final HandlerResult result = new DefaultHandlerResult(
                mock,
                mock(CredentialMetaData.class),
                p);
        when(mock.authenticate(any(Credential.class))).thenReturn(result);
    } else {
        when(mock.authenticate(any(Credential.class))).thenThrow(new FailedLoginException());
    }
    return mock;
}
 
Example 4
Project: springboot-shiro-cas-mybatis   File: AbstractPac4jAuthenticationHandler.java   View source code 6 votes vote down vote up
/**
 * Build the handler result.
 *
 * @param credentials the provided credentials
 * @param profile the retrieved user profile
 * @return the built handler result
 * @throws GeneralSecurityException On authentication failure.
 * @throws PreventedException On the indeterminate case when authentication is prevented.
 */
protected HandlerResult createResult(final ClientCredential credentials, final UserProfile profile)
        throws GeneralSecurityException, PreventedException {

    if (profile != null) {
        final String id;
        if (typedIdUsed) {
            id = profile.getTypedId();
        } else {
            id = profile.getId();
        }
        if (StringUtils.isNotBlank(id)) {
            credentials.setUserProfile(profile);
            credentials.setTypedIdUsed(typedIdUsed);
            return new DefaultHandlerResult(
                    this,
                    new BasicCredentialMetaData(credentials),
                    this.principalFactory.createPrincipal(id, profile.getAttributes()));
        }

        throw new FailedLoginException("No identifier found for this user profile: " + profile);
    }

    throw new FailedLoginException("Authentication did not produce a user profile for: " + credentials);
}
 
Example 5
Project: jdk8u-jdk   File: JConsole.java   View source code 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 6
Project: cas-server-4.2.1   File: SearchModeSearchDatabaseAuthenticationHandler.java   View source code 6 votes vote down vote up
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    if (StringUtils.isBlank(this.sql) || getJdbcTemplate() == null) {
        throw new GeneralSecurityException("Authentication handler is not configured correctly");
    }

    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, this.principalFactory.createPrincipal(username), null);
}
 
Example 7
Project: springboot-shiro-cas-mybatis   File: OpenIdCredentialsAuthenticationHandler.java   View source code 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 DefaultHandlerResult(this, new BasicCredentialMetaData(c), principal);
}
 
Example 8
Project: cas-server-4.2.1   File: ShiroAuthenticationHandler.java   View source code 6 votes vote down vote up
/**
 * Check subject roles and permissions.
 *
 * @param currentUser the current user
 * @throws FailedLoginException the failed login exception in case roles or permissions are absent
 */
protected void checkSubjectRolesAndPermissions(final Subject currentUser) throws FailedLoginException {
    if (this.requiredRoles != null) {
        for (final String role : this.requiredRoles) {
            if (!currentUser.hasRole(role)) {
                throw new FailedLoginException("Required role " + role + " does not exist");
            }
        }
    }

    if (this.requiredPermissions != null) {
        for (final String perm : this.requiredPermissions) {
            if (!currentUser.isPermitted(perm)) {
                throw new FailedLoginException("Required permission " + perm + " does not exist");
            }
        }
    }
}
 
Example 9
Project: springboot-shiro-cas-mybatis   File: ShiroAuthenticationHandler.java   View source code 6 votes vote down vote up
/**
 * Check subject roles and permissions.
 *
 * @param currentUser the current user
 * @throws FailedLoginException the failed login exception in case roles or permissions are absent
 */
protected void checkSubjectRolesAndPermissions(final Subject currentUser) throws FailedLoginException {
    if (this.requiredRoles != null) {
        for (final String role : this.requiredRoles) {
            if (!currentUser.hasRole(role)) {
                throw new FailedLoginException("Required role " + role + " does not exist");
            }
        }
    }

    if (this.requiredPermissions != null) {
        for (final String perm : this.requiredPermissions) {
            if (!currentUser.isPermitted(perm)) {
                throw new FailedLoginException("Required permission " + perm + " does not exist");
            }
        }
    }
}
 
Example 10
Project: cas-server-4.2.1   File: AbstractPac4jAuthenticationHandler.java   View source code 6 votes vote down vote up
/**
 * Build the handler result.
 *
 * @param credentials the provided credentials
 * @param profile the retrieved user profile
 * @return the built handler result
 * @throws GeneralSecurityException On authentication failure.
 * @throws PreventedException On the indeterminate case when authentication is prevented.
 */
protected HandlerResult createResult(final ClientCredential credentials, final UserProfile profile)
        throws GeneralSecurityException, PreventedException {

    if (profile != null) {
        final String id;
        if (typedIdUsed) {
            id = profile.getTypedId();
        } else {
            id = profile.getId();
        }
        if (StringUtils.isNotBlank(id)) {
            credentials.setUserProfile(profile);
            credentials.setTypedIdUsed(typedIdUsed);
            return new DefaultHandlerResult(
                    this,
                    new BasicCredentialMetaData(credentials),
                    this.principalFactory.createPrincipal(id, profile.getAttributes()));
        }

        throw new FailedLoginException("No identifier found for this user profile: " + profile);
    }

    throw new FailedLoginException("Authentication did not produce a user profile for: " + credentials);
}
 
Example 11
Project: cas4.0.x-server-wechat   File: KryoTranscoderTests.java   View source code 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 12
Project: cas-server-4.2.1   File: FileAuthenticationHandler.java   View source code 6 votes vote down vote up
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    try {
        if (this.fileName == null || !this.fileName.exists()) {
            throw new FileNotFoundException("Filename does not exist");
        }

        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 13
Project: cas-server-4.2.1   File: AcceptUsersAuthenticationHandler.java   View source code 6 votes vote down vote up
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    if (users == null || users.isEmpty()) {
        throw new FailedLoginException("No user can be accepted because none is defined");
    }
    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 14
Project: springboot-shiro-cas-mybatis   File: LegacyAuthenticationHandlerAdapter.java   View source code 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 15
Project: cas-server-4.2.1   File: KryoTranscoderTests.java   View source code 6 votes vote down vote up
MockTicketGrantingTicket(final String id, final Credential credential, final Map<String, Object> principalAttributes) {
    this.id = id;
    final CredentialMetaData credentialMetaData = new BasicCredentialMetaData(credential);
    final AuthenticationBuilder builder = new DefaultAuthenticationBuilder();
    builder.setPrincipal(this.principalFactory.createPrincipal(USERNAME, principalAttributes));
    builder.setAuthenticationDate(new DateTime());
    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 16
Project: springboot-shiro-cas-mybatis   File: ClientAuthenticationHandler.java   View source code 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 17
Project: cas4.0.x-server-wechat   File: RadiusAuthenticationHandler.java   View source code 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 18
Project: cas4.0.x-server-wechat   File: SimpleTestUsernamePasswordAuthenticationHandler.java   View source code 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 HandlerResult(this, new BasicCredentialMetaData(credential));
    }
    logger.debug("User [{}] failed authentication", username);
    throw new FailedLoginException();
}
 
Example 19
Project: cas-5.1.0   File: X509CredentialsAuthenticationHandler.java   View source code 6 votes vote down vote up
/**
 * Validate the X509Certificate received.
 *
 * @param cert the cert
 * @throws GeneralSecurityException the general security exception
 */
private void validate(final X509Certificate cert) throws GeneralSecurityException {
    cert.checkValidity();
    this.revocationChecker.check(cert);

    final int pathLength = cert.getBasicConstraints();
    if (pathLength < 0) {
        if (!isCertificateAllowed(cert)) {
            throw new FailedLoginException(
                    "Certificate subject does not match pattern " + this.regExSubjectDnPattern.pattern());
        }
        if (this.checkKeyUsage && !isValidKeyUsage(cert)) {
            throw new FailedLoginException(
                    "Certificate keyUsage constraint forbids SSL client authentication.");
        }
    } else {
        // Check pathLength for CA cert
        if (pathLength == Integer.MAX_VALUE && !this.maxPathLengthAllowUnspecified) {
            throw new FailedLoginException("Unlimited certificate path length not allowed by configuration.");
        }
        if (pathLength > this.maxPathLength && pathLength < Integer.MAX_VALUE) {
            throw new FailedLoginException(String.format(
                    "Certificate path length %s exceeds maximum value %s.", pathLength, this.maxPathLength));
        }
    }
}
 
Example 20
Project: OpenJSharp   File: JConsole.java   View source code 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 21
Project: springboot-shiro-cas-mybatis   File: FileAuthenticationHandler.java   View source code 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 22
Project: cas4.0.x-server-wechat   File: X509CredentialsAuthenticationHandler.java   View source code 6 votes vote down vote up
private void validate(final X509Certificate cert) throws GeneralSecurityException {
    cert.checkValidity();
    this.revocationChecker.check(cert);

    int pathLength = cert.getBasicConstraints();
    if (pathLength < 0) {
        if (!isCertificateAllowed(cert)) {
            throw new FailedLoginException(
                    "Certificate subject does not match pattern " + this.regExSubjectDnPattern.pattern());
        }
        if (this.checkKeyUsage && !isValidKeyUsage(cert)) {
            throw new FailedLoginException(
                    "Certificate keyUsage constraint forbids SSL client authentication.");
        }
    } else {
        // Check pathLength for CA cert
        if (pathLength == Integer.MAX_VALUE && this.maxPathLengthAllowUnspecified != true) {
            throw new FailedLoginException("Unlimited certificate path length not allowed by configuration.");
        } else if (pathLength > this.maxPathLength && pathLength < Integer.MAX_VALUE) {
            throw new FailedLoginException(String.format(
                    "Certificate path length %s exceeds maximum value %s.", pathLength, this.maxPathLength));
        }
    }
}
 
Example 23
Project: cas4.0.x-server-wechat   File: FileAuthenticationHandler.java   View source code 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 24
Project: cas-server-4.2.1   File: AbstractWrapperAuthenticationHandler.java   View source code 6 votes vote down vote up
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    CommonHelper.assertNotNull("profileCreator", this.profileCreator);

    final C credentials = convertToPac4jCredentials((I) credential);
    logger.debug("credentials: {}", credentials);

    try {
        final Authenticator authenticator = getAuthenticator(credential);
        CommonHelper.assertNotNull("authenticator", authenticator);
        authenticator.validate(credentials);
    } catch (final CredentialsException e) {
        logger.error("Failed to validate credentials", e);
        throw new FailedLoginException("Failed to validate credentials: " + e.getMessage());
    }

    final UserProfile profile = profileCreator.create(credentials);
    logger.debug("profile: {}", profile);

    return createResult(new ClientCredential(credentials), profile);
}
 
Example 25
Project: cas-5.1.0   File: RadiusTokenAuthenticationHandler.java   View source code 6 votes vote down vote up
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    try {
        final RadiusTokenCredential radiusCredential = (RadiusTokenCredential) credential;
        final String password = radiusCredential.getToken();

        final RequestContext context = RequestContextHolder.getRequestContext();
        final String username = WebUtils.getAuthentication(context).getPrincipal().getId();

        final Pair<Boolean, Optional<Map<String, Object>>> result =
                RadiusUtils.authenticate(username, password, this.servers,
                        this.failoverOnAuthenticationFailure, this.failoverOnException);
        if (result.getKey()) {
            return createHandlerResult(credential,
                    this.principalFactory.createPrincipal(username, result.getValue().get()),
                    new ArrayList<>());
        }
        throw new FailedLoginException("Radius authentication failed for user " + username);
    } catch (final Exception e) {
        throw new FailedLoginException("Radius authentication failed " + e.getMessage());
    }
}
 
Example 26
Project: cas-5.1.0   File: AzureAuthenticatorAuthenticationHandler.java   View source code 6 votes vote down vote up
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    try {
        final AzureAuthenticatorTokenCredential c = (AzureAuthenticatorTokenCredential) credential;
        final RequestContext context = RequestContextHolder.getRequestContext();
        final Principal principal = WebUtils.getAuthentication(context).getPrincipal();

        LOGGER.debug("Received principal id [{}]", principal.getId());
        final PFAuthParams params = authenticationRequestBuilder.build(principal, c);
        final PFAuthResult r = azureAuthenticatorInstance.authenticate(params);

        if (r.getAuthenticated()) {
            return createHandlerResult(c, principalFactory.createPrincipal(principal.getId()), null);
        }
        LOGGER.error("Authentication failed. Call status: [{}]-[{}]. Error: [{}]", r.getCallStatus(),
                r.getCallStatusString(), r.getMessageError());

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    throw new FailedLoginException("Failed to authenticate user");
}
 
Example 27
Project: cas-5.1.0   File: OpenIdCredentialsAuthenticationHandler.java   View source code 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 DefaultHandlerResult(this, new BasicCredentialMetaData(c), principal);
}
 
Example 28
Project: cas-5.1.0   File: ShiroAuthenticationHandler.java   View source code 6 votes vote down vote up
/**
 * Check subject roles and permissions.
 *
 * @param currentUser the current user
 * @throws FailedLoginException the failed login exception in case roles or permissions are absent
 */
protected void checkSubjectRolesAndPermissions(final Subject currentUser) throws FailedLoginException {
    if (this.requiredRoles != null) {
        for (final String role : this.requiredRoles) {
            if (!currentUser.hasRole(role)) {
                throw new FailedLoginException("Required role " + role + " does not exist");
            }
        }
    }

    if (this.requiredPermissions != null) {
        for (final String perm : this.requiredPermissions) {
            if (!currentUser.isPermitted(perm)) {
                throw new FailedLoginException("Required permission " + perm + " cannot be located");
            }
        }
    }
}
 
Example 29
Project: cas-5.1.0   File: FileAuthenticationHandler.java   View source code 6 votes vote down vote up
@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential transformedCredential, 
                                                             final String originalPassword)
        throws GeneralSecurityException, PreventedException {
    try {
        if (this.fileName == null) {
            throw new FileNotFoundException("Filename does not exist");
        }
        final String username = transformedCredential.getUsername();
        final String passwordOnRecord = getPasswordOnRecord(username);
        if (StringUtils.isBlank(passwordOnRecord)) {
            throw new AccountNotFoundException(username + " not found in backing file.");
        }
        if (matches(originalPassword, passwordOnRecord)) {
            return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username), null);
        }
    } catch (final IOException e) {
        throw new PreventedException("IO error reading backing file", e);
    }
    throw new FailedLoginException();
}
 
Example 30
Project: cas-server-4.2.1   File: X509CredentialsAuthenticationHandler.java   View source code 5 votes vote down vote up
@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 31
Project: cas-5.1.0   File: DuoAuthenticationHandler.java   View source code 5 votes vote down vote up
private HandlerResult authenticateDuoCredential(final Credential credential) throws FailedLoginException {
    try {
        final DuoCredential duoCredential = (DuoCredential) credential;
        if (!duoCredential.isValid()) {
            throw new GeneralSecurityException("Duo credential validation failed. Ensure a username "
                    + " and the signed Duo response is configured and passed. Credential received: " + duoCredential);
        }

        final DuoAuthenticationService duoAuthenticationService = getDuoAuthenticationService();
        final String duoVerifyResponse = duoAuthenticationService.authenticate(duoCredential).getValue();
        LOGGER.debug("Response from Duo verify: [{}]", duoVerifyResponse);
        final String primaryCredentialsUsername = duoCredential.getUsername();

        final boolean isGoodAuthentication = duoVerifyResponse.equals(primaryCredentialsUsername);

        if (isGoodAuthentication) {
            LOGGER.info("Successful Duo authentication for [{}]", primaryCredentialsUsername);

            final Principal principal = this.principalFactory.createPrincipal(duoVerifyResponse);
            return createHandlerResult(credential, principal, new ArrayList<>());
        }
        throw new FailedLoginException("Duo authentication username "
                + primaryCredentialsUsername + " does not match Duo response: " + duoVerifyResponse);

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new FailedLoginException(e.getMessage());
    }
}
 
Example 32
Project: cas-5.1.0   File: X509CredentialsAuthenticationHandler.java   View source code 5 votes vote down vote up
@Override
protected 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 pathLenConstraints 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()));
    }
    LOGGER.warn("Either client certificate could not be determined, or a trusted issuer could not be located");
    throw new FailedLoginException();
}
 
Example 33
Project: springboot-shiro-cas-mybatis   File: SimpleTestUsernamePasswordAuthenticationHandler.java   View source code 5 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),
                this.principalFactory.createPrincipal(username));
    }
    logger.debug("User [{}] failed authentication", username);
    throw new FailedLoginException();
}
 
Example 34
Project: springboot-shiro-cas-mybatis   File: AcceptUsersAuthenticationHandlerTests.java   View source code 5 votes vote down vote up
@Test(expected = FailedLoginException.class)
public void verifyFailsNullPassword() throws Exception{
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    c.setUsername("scott");
    c.setPassword(null);

    this.authenticationHandler.authenticate(c);
}
 
Example 35
Project: cas-server-4.2.1   File: FileAuthenticationHandlerTests.java   View source code 5 votes vote down vote up
@Test(expected = FailedLoginException.class)
public void verifyFailsNullPassword() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

    c.setUsername("scott");
    c.setPassword(null);

    this.authenticationHandler.authenticate(c);
}
 
Example 36
Project: springboot-shiro-cas-mybatis   File: QueryDatabaseAuthenticationHandlerTests.java   View source code 5 votes vote down vote up
@Test(expected = FailedLoginException.class)
public void verifyPasswordInvalid() throws Exception {
    final QueryDatabaseAuthenticationHandler q = new QueryDatabaseAuthenticationHandler();
    q.setDataSource(this.dataSource);
    q.setSql(SQL);
    q.authenticateUsernamePasswordInternal(
            TestUtils.getCredentialsWithDifferentUsernameAndPassword("user1", "psw11"));

}
 
Example 37
Project: springboot-shiro-cas-mybatis   File: QueryDatabaseAuthenticationHandlerTests.java   View source code 5 votes vote down vote up
@Test(expected = FailedLoginException.class)
public void verifyMultipleRecords() throws Exception {
    final QueryDatabaseAuthenticationHandler q = new QueryDatabaseAuthenticationHandler();
    q.setDataSource(this.dataSource);
    q.setSql(SQL);
    q.authenticateUsernamePasswordInternal(
            TestUtils.getCredentialsWithDifferentUsernameAndPassword("user0", "psw0"));

}
 
Example 38
Project: cas-server-4.2.1   File: WsFederationAuthenticationHandler.java   View source code 5 votes vote down vote up
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final WsFederationCredential wsFederationCredentials = (WsFederationCredential) credential;
    if (wsFederationCredentials != null) {
        final Map attributes = wsFederationCredentials.getAttributes();
        final Principal principal = this.principalFactory.createPrincipal(wsFederationCredentials.getId(), attributes);

        return this.createHandlerResult(wsFederationCredentials, principal, new ArrayList<MessageDescriptor>());
    }
    throw new FailedLoginException();
}
 
Example 39
Project: cas-server-4.2.1   File: ShiroAuthenticationHandlerTests.java   View source code 5 votes vote down vote up
@Test(expected=FailedLoginException.class)
public void checkAuthenticationSuccessfulMissingRole() throws Exception {
    final ShiroAuthenticationHandler shiro = new ShiroAuthenticationHandler();
    shiro.setShiroConfiguration(new ClassPathResource("shiro.ini"));
    shiro.setRequiredRoles(Collections.singleton("student"));

    final RememberMeUsernamePasswordCredential creds =
            new RememberMeUsernamePasswordCredential();
    creds.setRememberMe(true);
    creds.setUsername("casuser");
    creds.setPassword("Mellon");
    shiro.authenticate(creds);
}
 
Example 40
Project: springboot-shiro-cas-mybatis   File: OpenIdCredentialsAuthenticationHandlerTests.java   View source code 5 votes vote down vote up
@Test(expected = FailedLoginException.class)
public void verifyTGTWithDifferentId() throws Exception {
    final OpenIdCredential c = new OpenIdCredential("test", "test1");
    final TicketGrantingTicket t = getTicketGrantingTicket();
    this.ticketRegistry.addTicket(t);

    this.openIdCredentialsAuthenticationHandler.authenticate(c);
}