Java 类javax.security.auth.login.FailedLoginException 实例源码

项目:cas-5.1.0    文件:DefaultWebflowConfigurer.java   
/**
 * 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);

}
项目:cas-5.1.0    文件:AcceptUsersAuthenticationHandler.java   
@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);
}
项目:springboot-shiro-cas-mybatis    文件:PolicyBasedAuthenticationManagerTests.java   
/**
 * 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;
}
项目:springboot-shiro-cas-mybatis    文件:AbstractPac4jAuthenticationHandler.java   
/**
 * 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);
}
项目:jdk8u-jdk    文件:JConsole.java   
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();
}
项目:cas-server-4.2.1    文件:SearchModeSearchDatabaseAuthenticationHandler.java   
@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);
}
项目:springboot-shiro-cas-mybatis    文件:OpenIdCredentialsAuthenticationHandler.java   
@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);
}
项目:cas-server-4.2.1    文件:ShiroAuthenticationHandler.java   
/**
 * 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");
            }
        }
    }
}
项目:springboot-shiro-cas-mybatis    文件:ShiroAuthenticationHandler.java   
/**
 * 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");
            }
        }
    }
}
项目:cas-server-4.2.1    文件:AbstractPac4jAuthenticationHandler.java   
/**
 * 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);
}
项目:cas4.0.x-server-wechat    文件:KryoTranscoderTests.java   
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();
}
项目:cas-server-4.2.1    文件:FileAuthenticationHandler.java   
@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();
}
项目:cas-server-4.2.1    文件:AcceptUsersAuthenticationHandler.java   
@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);
}
项目:springboot-shiro-cas-mybatis    文件:LegacyAuthenticationHandlerAdapter.java   
@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);
    }
}
项目:cas-server-4.2.1    文件:KryoTranscoderTests.java   
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();
}
项目:springboot-shiro-cas-mybatis    文件:ClientAuthenticationHandler.java   
/**
 * {@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);
}
项目:cas4.0.x-server-wechat    文件:RadiusAuthenticationHandler.java   
@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();
}
项目:cas4.0.x-server-wechat    文件:SimpleTestUsernamePasswordAuthenticationHandler.java   
@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();
}
项目:cas-5.1.0    文件:X509CredentialsAuthenticationHandler.java   
/**
 * 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));
        }
    }
}
项目:OpenJSharp    文件:JConsole.java   
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();
}
项目:springboot-shiro-cas-mybatis    文件:FileAuthenticationHandler.java   
/**
 * {@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();
}
项目:cas4.0.x-server-wechat    文件:X509CredentialsAuthenticationHandler.java   
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));
        }
    }
}
项目:cas4.0.x-server-wechat    文件:FileAuthenticationHandler.java   
/** {@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();
}
项目:cas-server-4.2.1    文件:AbstractWrapperAuthenticationHandler.java   
@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);
}
项目:cas-5.1.0    文件:RadiusTokenAuthenticationHandler.java   
@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());
    }
}
项目:cas-5.1.0    文件:AzureAuthenticatorAuthenticationHandler.java   
@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");
}
项目:cas-5.1.0    文件:OpenIdCredentialsAuthenticationHandler.java   
@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);
}
项目:cas-5.1.0    文件:ShiroAuthenticationHandler.java   
/**
 * 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");
            }
        }
    }
}
项目:cas-5.1.0    文件:FileAuthenticationHandler.java   
@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();
}
项目:cas-server-4.2.1    文件:X509CredentialsAuthenticationHandler.java   
@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();
}
项目:cas-5.1.0    文件:DuoAuthenticationHandler.java   
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());
    }
}
项目:cas-5.1.0    文件:X509CredentialsAuthenticationHandler.java   
@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();
}
项目:springboot-shiro-cas-mybatis    文件:SimpleTestUsernamePasswordAuthenticationHandler.java   
@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();
}
项目:springboot-shiro-cas-mybatis    文件:AcceptUsersAuthenticationHandlerTests.java   
@Test(expected = FailedLoginException.class)
public void verifyFailsNullPassword() throws Exception{
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

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

    this.authenticationHandler.authenticate(c);
}
项目:cas-server-4.2.1    文件:FileAuthenticationHandlerTests.java   
@Test(expected = FailedLoginException.class)
public void verifyFailsNullPassword() throws Exception {
    final UsernamePasswordCredential c = new UsernamePasswordCredential();

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

    this.authenticationHandler.authenticate(c);
}
项目:springboot-shiro-cas-mybatis    文件:QueryDatabaseAuthenticationHandlerTests.java   
@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"));

}
项目:springboot-shiro-cas-mybatis    文件:QueryDatabaseAuthenticationHandlerTests.java   
@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"));

}
项目:cas-server-4.2.1    文件:WsFederationAuthenticationHandler.java   
@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();
}
项目:cas-server-4.2.1    文件:ShiroAuthenticationHandlerTests.java   
@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);
}
项目:springboot-shiro-cas-mybatis    文件:OpenIdCredentialsAuthenticationHandlerTests.java   
@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);
}