Example usage for org.apache.shiro.authc AuthenticationException AuthenticationException

List of usage examples for org.apache.shiro.authc AuthenticationException AuthenticationException

Introduction

In this page you can find the example usage for org.apache.shiro.authc AuthenticationException AuthenticationException.

Prototype

public AuthenticationException(Throwable cause) 

Source Link

Document

Constructs a new AuthenticationException.

Usage

From source file:org.ohdsi.webapi.shiro.JdbcAuthRealm.java

License:Apache License

private String getPasswordForUser(String username) {
    String result = null;//from  w ww  . ja  v a 2s.c o m

    try (Connection conn = dataSource.getConnection();
            PreparedStatement ps = createPreparedStatement(conn, username);
            ResultSet rs = ps.executeQuery()) {
        for (boolean foundResult = false; rs.next(); foundResult = true) {
            if (foundResult) {
                throw new AuthenticationException(
                        "More than one user row found for user [" + username + "]. Usernames must be unique.");
            }
            result = rs.getString(1);
        }
    } catch (SQLException e) {
        String message = "There was a SQL error while authenticating user [" + username + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }
        result = null;
    }
    return result;
}

From source file:org.opendaylight.aaa.shiro.filters.AuthenticationListenerTest.java

License:Open Source License

@Test
public void testOnFailure() throws Exception {
    // variables for an unsucessful authentication attempt
    final AuthenticationListener authenticationListener = new AuthenticationListener();
    final UsernamePasswordToken authenticationToken = new UsernamePasswordToken();
    authenticationToken.setUsername("unsuccessfulUser1");
    authenticationToken.setHost("unsuccessfulHost1");
    final AuthenticationException authenticationException = new AuthenticationException("test auth exception");
    // produces unsuccessful authentication attempt output
    authenticationListener.onFailure(authenticationToken, authenticationException);

    // grab the latest log output and ensure it is in line with what is expected
    final List<LoggingEvent> loggingEvents = TestAppender.getCurrentInstance().getEvents();
    final int whichLoggingEvent = loggingEvents.size() - 1;
    final LoggingEvent latestLoggingEvent = loggingEvents.get(whichLoggingEvent);
    final String latestLogMessage = latestLoggingEvent.getMessage();
    assertEquals("Unsuccessful authentication attempt by unsuccessfulUser1 from unsuccessfulHost1",
            latestLogMessage);/*from ww w  . j a v  a  2  s . c o m*/
}

From source file:org.opendaylight.aaa.shiro.filters.MoonOAuthFilter.java

License:Open Source License

private void oauthAccessTokenResponse(HttpServletResponse resp, Claim claim, String clientId, String token)
        throws OAuthSystemException, IOException {
    if (claim == null) {
        throw new AuthenticationException(UNAUTHORIZED);
    }//from  ww w  .j av  a  2 s. c  om

    // Cache this token...
    Authentication auth = new AuthenticationBuilder(new ClaimBuilder(claim).setClientId(clientId).build())
            .setExpiration(tokenExpiration()).build();
    ServiceLocator.getInstance().getTokenStore().put(token, auth);

    OAuthResponse r = OAuthASResponse.tokenResponse(SC_CREATED).setAccessToken(token)
            .setTokenType(TokenType.BEARER.toString()).setExpiresIn(Long.toString(auth.expiration()))
            .buildJSONMessage();
    write(resp, r);
}

From source file:org.opendaylight.aaa.shiro.realm.KeystoneAuthRealm.java

License:Open Source License

/**
 * As {@link #doGetAuthenticationInfo(AuthenticationToken)}
 * but using the provided {@link SimpleHttpClient} to reach
 * the Keystone server./*from  ww  w .  j  ava2 s  .  c  o m*/
 *
 * @param authenticationToken see
 *  {@link AuthorizingRealm#doGetAuthenticationInfo(AuthenticationToken)}
 * @param client the {@link SimpleHttpClient} to use.
 * @return see
 *  {@link AuthorizingRealm#doGetAuthenticationInfo(AuthenticationToken)}
 */
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken authenticationToken,
        final SimpleHttpClient client) {

    final URI theServerUri = getServerUri();
    final String theDefaultDomain = getDefaultDomain();

    if (!(authenticationToken instanceof UsernamePasswordToken)) {
        LOG.error("Only basic authentication is supported");
        throw new AuthenticationException(FATAL_ERROR_BASIC_AUTH_ONLY);
    }

    if (Objects.isNull(theServerUri)) {
        LOG.error("Invalid URL to Keystone server");
        throw new AuthenticationException(FATAL_ERROR_INVALID_URL);
    }

    final UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
    final String qualifiedUser = usernamePasswordToken.getUsername();
    final String password = new String(usernamePasswordToken.getPassword());
    final String[] qualifiedUserArray = qualifiedUser.split(USERNAME_DOMAIN_SEPARATOR, 2);
    final String username = qualifiedUserArray.length > 0 ? qualifiedUserArray[0] : qualifiedUser;
    final String domain = qualifiedUserArray.length > 1 ? qualifiedUserArray[1] : theDefaultDomain;

    final KeystoneAuth keystoneAuth = new KeystoneAuth(username, password, domain);
    final SimpleHttpRequest<KeystoneToken> httpRequest = client.requestBuilder(KeystoneToken.class)
            .uri(theServerUri).path(AUTH_PATH).method(HttpMethod.POST)
            .mediaType(MediaType.APPLICATION_JSON_TYPE).entity(keystoneAuth).queryParam(NO_CATALOG_OPTION, "")
            .build();

    KeystoneToken theToken;
    try {
        theToken = httpRequest.execute();
    } catch (WebApplicationException e) {
        LOG.debug("Unable to authenticate - Keystone result code: {}", e.getResponse().getStatus(), e);
        return null;
    }

    final Set<String> theRoles = theToken.getToken().getRoles().stream().map(KeystoneToken.Token.Role::getName)
            .collect(Collectors.toSet());

    final String userId = username + USERNAME_DOMAIN_SEPARATOR + domain;
    final ODLPrincipal odlPrincipal = createODLPrincipal(username, domain, userId, theRoles);
    return new SimpleAuthenticationInfo(odlPrincipal, password.toCharArray(), getName());
}

From source file:org.opendaylight.aaa.shiro.realm.KeystoneAuthRealm.java

License:Open Source License

private SSLContext getSecureSSLContext(final ICertificateManager certificateManager) {
    final SSLContext sslContext = Optional.ofNullable(certificateManager)
            .map(ICertificateManager::getServerContext).orElse(null);
    if (Objects.isNull(sslContext)) {
        LOG.error("Could not get a valid SSL context from certificate manager");
        throw new AuthenticationException(UNABLE_TO_AUTHENTICATE);
    }//from w  ww  . j ava  2  s  .com
    return sslContext;
}

From source file:org.opendaylight.aaa.shiro.realm.TokenAuthRealm.java

License:Open Source License

private Authentication validate(final String token) {
    Authentication auth = ServiceLocator.getInstance().getTokenStore().get(token);
    if (auth == null) {
        throw new AuthenticationException("Could not validate the token " + token);
    } else {/* w w w.ja  v  a 2s . co  m*/
        ServiceLocator.getInstance().getAuthenticationService().set(auth);
    }
    return auth;
}

From source file:org.openengsb.core.security.OpenEngSBShiroAuthenticator.java

License:Apache License

@Override
protected AuthenticationInfo doAuthenticate(AuthenticationToken token) throws AuthenticationException {
    try {/*from  w w w.  j  a  va  2 s  .c  o  m*/
        Authentication authenticate = authenticator.authenticate(token.getPrincipal().toString(),
                (Credentials) token.getCredentials());
        return new SimpleAuthenticationInfo(authenticate.getUsername(), authenticate.getCredentials(),
                "openengsb");
    } catch (org.openengsb.domain.authentication.AuthenticationException e) {
        throw new AuthenticationException(e);
    }
}

From source file:org.openengsb.core.services.OpenEngSBShiroAuthenticator.java

License:Apache License

@Override
protected AuthenticationInfo doAuthenticate(AuthenticationToken token) throws AuthenticationException {
    if (token instanceof RootAuthenticationToken) {
        return new SimpleAuthenticationInfo(token.getPrincipal(), null, "openengsb");
    }/*from   w w  w. j  av  a 2  s . com*/
    try {
        Authentication authenticate = authenticator.authenticate(token.getPrincipal().toString(),
                (Credentials) token.getCredentials());
        return new SimpleAuthenticationInfo(authenticate.getUsername(), authenticate.getCredentials(),
                "openengsb");
    } catch (org.openengsb.domain.authentication.AuthenticationException e) {
        throw new AuthenticationException(e);
    }
}

From source file:org.ow2.proactive.iam.core.realms.PamRealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    UnixUser user;/*from w  ww.  jav  a  2s  .  c om*/
    try {
        user = getPam().authenticate(upToken.getUsername(), new String(upToken.getPassword()));
    } catch (PAMException e) {
        // Until libpam4j provides more details, we can only throw the top-level exception
        throw new AuthenticationException(e);
    }
    return new SimpleAuthenticationInfo(new UnixUserPrincipal(user), upToken.getPassword(), getName());
}

From source file:org.ow2.proactive.workflowcatalog.security.RestSchedulerRealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
        throws AuthenticationException {

    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

    String user = authenticationToken.getPrincipal().toString();
    String pass = getPass(usernamePasswordToken.getPassword());
    String cred = getCred(usernamePasswordToken.getCredentials());

    if (user == null || user.isEmpty())
        throw new AuthenticationException("No user provided");

    MyPrincipal principal = null;//  w w  w  . j av  a  2  s. c  o m
    try {
        if (pass != null) {
            principal = mySecurityManagerService.findMyPrincipalByUsernamePassword(user, pass);
        } else if (cred != null) {
            principal = mySecurityManagerService.findMyPrincipalByUsernameCredentials(user, cred);
        } else {
            throw new LoginException("Neither pass nor credentials were provided for: " + user);
        }
    } catch (LoginException e) {
        throw new AuthenticationException("Login failed for user: " + user, e);
    } catch (SchedulerRestException e) {
        throw new AuthenticationException("REST error during login of user: " + user, e);
    }

    return new SimpleAccount(principal.getUsername(), principal.getCredentials(), getName(),
            principal.getRoles(), new HashSet());

}