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.apache.activemq.shiro.authc.AuthenticationFilter.java

License:Apache License

@Override
public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception {

    if (isEnabled()) { //disabled means don't enforce authentication (i.e. allow anonymous access):

        Subject subject = getSubject(new ConnectionReference(context, info, getEnvironment()));

        if (!subject.isAuthenticated()) {

            SubjectConnectionReference connection = new SubjectConnectionReference(context, info,
                    getEnvironment(), subject);

            if (this.authenticationPolicy.isAuthenticationRequired(connection)) {
                AuthenticationToken token = this.authenticationTokenFactory.getAuthenticationToken(connection);
                if (token == null) {
                    String msg = "Unable to obtain authentication credentials for newly established connection.  "
                            + "Authentication is required.";
                    throw new AuthenticationException(msg);
                }//from  w w  w .j a va 2 s.c om
                //token is not null - login the current subject:
                subject.login(token);
            }
        }
    }

    super.addConnection(context, info);
}

From source file:org.apache.aurora.scheduler.http.api.security.Kerberos5Realm.java

License:Apache License

@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    byte[] tokenFromInitiator = ((AuthorizeHeaderToken) token).getAuthorizeHeaderValue();
    GSSContext context;/*from  w w  w  .  j  av  a2  s  .c om*/
    try {
        context = gssManager.createContext(serverCredential);
        context.acceptSecContext(tokenFromInitiator, 0, tokenFromInitiator.length);
    } catch (GSSException e) {
        throw new AuthenticationException(e);
    }

    // Technically the GSS-API requires us to continue sending data back and forth in a loop
    // until the context is established, but we can short-circuit here since we know we're using
    // Kerberos V5 directly or Kerberos V5-backed SPNEGO. This is important because it means we
    // don't need to keep state between requests.
    // From http://docs.oracle.com/javase/7/docs/technotes/guides/security/jgss/single-signon.html
    // "In the case of the Kerberos V5 mechanism, there is no more than one round trip of
    // tokens during context establishment."
    if (context.isEstablished()) {
        try {
            KerberosPrincipal kerberosPrincipal = new KerberosPrincipal(context.getSrcName().toString());
            return new SimpleAuthenticationInfo(new SimplePrincipalCollection(ImmutableList.of(
                    // We assume there's a single Kerberos realm in use here. Most Authorizer
                    // implementations care about the "simple" username instead of the full
                    // principal.
                    AT_SPLITTER.splitToList(kerberosPrincipal.getName()).get(0), kerberosPrincipal), getName()),
                    null /* There are no credentials that can be cached. */);
        } catch (GSSException | IndexOutOfBoundsException e) {
            throw new AuthenticationException(e);
        }
    } else {
        throw new AuthenticationException("GSSContext was not established with a single message.");
    }
}

From source file:org.apache.hadoop.gateway.shirorealm.KnoxPamRealm.java

License:Apache License

private void handleAuthFailure(AuthenticationToken token, String errorMessage, Exception e) {
    auditor.audit(Action.AUTHENTICATION, token.getPrincipal().toString(), ResourceType.PRINCIPAL,
            ActionOutcome.FAILURE, errorMessage);
    ShiroLog.failedLoginInfo(token);/*  ww w .  j  a  v  a 2 s. c  o m*/

    if (e != null) {
        ShiroLog.failedLoginAttempt(e.getCause());
        throw new AuthenticationException(e);
    }

    throw new AuthenticationException(errorMessage);
}

From source file:org.apache.usergrid.chop.webapp.service.shiro.ShiroRealm.java

License:Apache License

public static boolean authenticateUser(String username, String password) {
    try {/*from   w w w.java 2  s .c  o  m*/
        if (!SecurityUtils.getSubject().isAuthenticated()) {
            if (username == null) {
                throw new AuthenticationException("Username is null");
            }
            if (password == null) {
                throw new AuthenticationException("Password is null");
            }

            LOG.info(String.format("Authenticating  user %s", username));

            if (username.equalsIgnoreCase("user") && password.equals("pass")) {
                initUserData();
            }
            User user = InjectorFactory.getInstance(UserDao.class).get(username.toLowerCase());
            if (user == null || user.getPassword() == null || !user.getPassword().equalsIgnoreCase(password)) {
                throw new AuthenticationException("Authentication failed");
            }

            SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password));
            authenticatedUser = username;
        }
        return true;

    } catch (Exception e) {
        LOG.error("Error in findUser", e);
    }
    return false;
}

From source file:org.apache.usergrid.chop.webapp.service.shiro.ShiroRealm.java

License:Apache License

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

    try {/*from   www .j a  v a  2s.  co m*/
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        token.setRememberMe(true);

        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());

        if (username == null) {
            throw new AuthenticationException("Authentication failed");
        }

        LOG.info(String.format("Authenticating user %s", username));

        if (username.equals(username) && password.equals("pass")) {
            initUserData();

        }
        User user = InjectorFactory.getInstance(UserDao.class).get(username.toLowerCase());
        if (user == null || user.getPassword() == null || !user.getPassword().equalsIgnoreCase(password)) {
            throw new AuthenticationException("Authentication failed");
        }

        return new SimpleAuthenticationInfo(username, password, this.getName());
    } catch (Exception e) {
        LOG.error("Error while authenticating", e);
        throw new AuthenticationException("Authentication failed", e);
    }

}

From source file:org.apache.usergrid.security.shiro.Realm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    PrincipalCredentialsToken pcToken = (PrincipalCredentialsToken) token;

    if (pcToken.getCredentials() == null) {
        throw new CredentialsException("Missing credentials");
    }/*from   w  w  w .j  a  v a 2 s.  c o  m*/

    boolean authenticated = false;

    PrincipalIdentifier principal = pcToken.getPrincipal();
    PrincipalCredentials credentials = pcToken.getCredentials();

    if (credentials instanceof ClientCredentials) {
        authenticated = true;
    } else if ((principal instanceof AdminUserPrincipal) && (credentials instanceof AdminUserPassword)) {
        authenticated = true;
    } else if ((principal instanceof AdminUserPrincipal) && (credentials instanceof AdminUserAccessToken)) {
        authenticated = true;
    } else if ((principal instanceof ApplicationUserPrincipal)
            && (credentials instanceof ApplicationUserAccessToken)) {
        authenticated = true;
    } else if ((principal instanceof ApplicationPrincipal) && (credentials instanceof ApplicationAccessToken)) {
        authenticated = true;
    } else if ((principal instanceof OrganizationPrincipal)
            && (credentials instanceof OrganizationAccessToken)) {
        authenticated = true;
    }

    if (principal != null) {
        if (!principal.isActivated()) {
            throw new AuthenticationException("Unactivated identity");
        }
        if (principal.isDisabled()) {
            throw new AuthenticationException("Disabled identity");
        }
    }

    if (!authenticated) {
        throw new AuthenticationException("Unable to authenticate");
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Authenticated: {}", principal);
    }

    return new SimpleAuthenticationInfo(pcToken.getPrincipal(), pcToken.getCredentials(), getName());
}

From source file:org.apache.zeppelin.realm.ZeppelinHubRealm.java

License:Apache License

/**
 * Send to ZeppelinHub a login request based on the request body which is a JSON that contains 2
 * fields "login" and "password".//ww w .j a v a 2s .  com
 *
 * @param requestBody JSON string of ZeppelinHub payload.
 * @return Account object with login, name (if set in ZeppelinHub), and mail.
 * @throws AuthenticationException if fail to login.
 */
protected User authenticateUser(String requestBody) {
    PutMethod put = new PutMethod(Joiner.on("/").join(zeppelinhubUrl, USER_LOGIN_API_ENDPOINT));
    String responseBody;
    String userSession;
    try {
        put.setRequestEntity(new StringRequestEntity(requestBody, JSON_CONTENT_TYPE, UTF_8_ENCODING));
        int statusCode = httpClient.executeMethod(put);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Cannot login user, HTTP status code is {} instead on 200 (OK)", statusCode);
            put.releaseConnection();
            throw new AuthenticationException("Couldnt login to ZeppelinHub. " + "Login or password incorrect");
        }
        responseBody = put.getResponseBodyAsString();
        userSession = put.getResponseHeader(USER_SESSION_HEADER).getValue();
        put.releaseConnection();

    } catch (IOException e) {
        LOG.error("Cannot login user", e);
        throw new AuthenticationException(e.getMessage());
    }

    User account;
    try {
        account = User.fromJson(responseBody);
    } catch (JsonParseException e) {
        LOG.error("Cannot fromJson ZeppelinHub response to User instance", e);
        throw new AuthenticationException("Cannot login to ZeppelinHub");
    }

    onLoginSuccess(account.login, userSession);

    return account;
}

From source file:org.codice.ddf.security.oidc.realm.CustomOidcProfileCreator.java

License:Open Source License

@Override
public U create(OidcCredentials credentials, WebContext context) {
    init();//from   w w  w. j a  va  2 s .  co  m

    final U profile = getProfileDefinition().newProfile();

    final AccessToken accessToken = credentials.getAccessToken();
    if (accessToken != null && !accessToken.getValue().isEmpty()) {
        profile.setAccessToken(accessToken);
    }

    final RefreshToken refreshToken = credentials.getRefreshToken();
    if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
        profile.setRefreshToken(refreshToken);
    }

    final JWT idToken = credentials.getIdToken();
    profile.setIdTokenString(idToken.getParsedString());

    try {
        JWTClaimsSet claimsSet = idToken.getJWTClaimsSet();
        assertNotNull("claimsSet", claimsSet);
        profile.setId(ProfileHelper.sanitizeIdentifier(profile, claimsSet.getSubject()));

        for (final Map.Entry<String, Object> entry : claimsSet.getClaims().entrySet()) {
            if (!JwtClaims.SUBJECT.equals(entry.getKey()) && profile.getAttribute(entry.getKey()) == null) {
                getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, entry.getKey(),
                        entry.getValue());
            }
        }

        profile.setTokenExpirationAdvance(configuration.getTokenExpirationAdvance());

        return profile;

    } catch (final java.text.ParseException e) {
        throw new AuthenticationException(e);
    }
}

From source file:org.codice.ddf.security.oidc.realm.OidcRealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
        throws AuthenticationException {
    // token is guaranteed to be of type OidcAuthenticationToken by the supports() method
    OidcAuthenticationToken oidcAuthenticationToken = (OidcAuthenticationToken) authenticationToken;
    OidcCredentials credentials = (OidcCredentials) oidcAuthenticationToken.getCredentials();
    OidcConfiguration oidcConfiguration = oidcHandlerConfiguration.getOidcConfiguration();
    OIDCProviderMetadata oidcProviderMetadata = oidcConfiguration.findProviderMetadata();
    WebContext webContext = (WebContext) oidcAuthenticationToken.getContext();
    OidcClient oidcClient = oidcHandlerConfiguration.getOidcClient(webContext.getFullRequestURL());

    OidcCredentialsResolver oidcCredentialsResolver = new OidcCredentialsResolver(oidcConfiguration, oidcClient,
            oidcProviderMetadata);/*from   w w w . j a  v  a2 s  .c o  m*/

    oidcCredentialsResolver.resolveIdToken(credentials, webContext);

    // problem getting id token, invalidate credentials
    if (credentials.getIdToken() == null) {
        webContext.getSessionStore().destroySession(webContext);

        String msg = String.format("Could not fetch id token with Oidc credentials (%s). "
                + "This may be due to the credentials expiring. "
                + "Invalidating session in order to acquire valid credentials.", credentials);

        LOGGER.warn(msg);
        throw new AuthenticationException(msg);
    }

    OidcProfileCreator oidcProfileCreator = new CustomOidcProfileCreator(oidcConfiguration);
    OidcProfile profile = oidcProfileCreator.create(credentials, webContext);

    SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo();
    SimplePrincipalCollection principalCollection = createPrincipalCollectionFromCredentials(profile);
    simpleAuthenticationInfo.setPrincipals(principalCollection);
    simpleAuthenticationInfo.setCredentials(credentials);

    return simpleAuthenticationInfo;
}

From source file:org.codice.ddf.security.oidc.realm.OidcTokenValidator.java

License:Open Source License

/**
 * Validates id tokens.// w w w .jav a2s  . c  o  m
 *
 * <ul>
 *   <li>If the ID token is not signed, an exception is thrown
 *   <li>If the ID token is signed, the required signing algorithm list from the metadata is used
 *       along with the header to validate it
 *
 * @param idToken - id token to validate
 * @param webContext - the web context used to get the session information
 */
public IDTokenClaimsSet validateIdTokens(JWT idToken, WebContext webContext) {
    if (!(idToken instanceof SignedJWT)) {
        LOGGER.error("Error validating id token. ID token was not signed.");
        throw new AuthenticationException("Error validating id token. ID token was not signed.");
    }

    try {
        // get nonce
        Nonce nonce = null;
        if (configuration.isUseNonce()) {
            Object nonceString = webContext.getSessionStore().get(webContext,
                    OidcConfiguration.NONCE_SESSION_ATTRIBUTE);
            if (nonceString != null) {
                nonce = new Nonce((String) nonceString);
            }
        }

        TokenValidator tokenValidator = new TokenValidator(configuration);
        return tokenValidator.validate(idToken, nonce);
    } catch (Exception e) {
        LOGGER.error("Error validating id token.", e);
        throw new AuthenticationException("Error validating id token.", e);
    }
}