List of usage examples for org.apache.shiro.authc AuthenticationException AuthenticationException
public AuthenticationException(Throwable cause)
From source file:org.codice.ddf.security.oidc.realm.OidcTokenValidator.java
License:Open Source License
/** * Validates id tokens received from the userinfo endpoint. * * <ul>/*from w w w .jav a 2s. c o m*/ * <li>If the ID token is not signed, validation is ignored * <li>If the ID token is signed * <ul> * <li>If the userinfo signing algorithms are listed in the metadata, we use that * information along with the header attributes to validate the token * <li>If the userinfo signing algorithms are NOT listed in the metadata, we just use the * header attributes to validate the token * </ul> * * @param idToken - id token to validate */ public void validateUserInfoIdToken(JWT idToken) { try { if (!(idToken instanceof SignedJWT)) { LOGGER.info("ID token received from the userinfo endpoint was not signed."); return; } JWKSource jwkSource = new RemoteJWKSet(metadata.getJWKSetURI().toURL(), resourceRetriever); SignedJWT signedJWT = ((SignedJWT) idToken); JWSAlgorithm jwsAlgorithm = signedJWT.getHeader().getAlgorithm(); if (userInfoSigAlgList.isEmpty()) { LOGGER.warn("A JWS algorithm was not listed in the OpenID Connect provider metadata. " + "Using JWS algorithm specified in the header."); } else { if (!userInfoSigAlgList.contains(jwsAlgorithm)) { LOGGER.error("The signature algorithm of the id token do not match the expected ones."); throw new AuthenticationException( "The signature algorithm of the id token do not match the expected ones."); } } JWSKeySelector jwsKeySelector = new JWSVerificationKeySelector(jwsAlgorithm, jwkSource); JWSVerifierFactory jwsVerifierFactory = new DefaultJWSVerifierFactory(); List<? extends Key> keyCandidates = jwsKeySelector.selectJWSKeys(signedJWT.getHeader(), null); if (keyCandidates == null || keyCandidates.isEmpty()) { throw new AuthenticationException("Error Validating userinfo ID token. No matching key(s) found"); } ListIterator<? extends Key> it = keyCandidates.listIterator(); while (it.hasNext()) { JWSVerifier verifier = jwsVerifierFactory.createJWSVerifier(signedJWT.getHeader(), it.next()); if (verifier == null) { continue; } final boolean validSignature = signedJWT.verify(verifier); if (validSignature) { return; } if (!it.hasNext()) { throw new AuthenticationException("Error Validating userinfo ID token. Invalid signature"); } } throw new AuthenticationException("Error Validating userinfo ID token. No matching verifier(s) found"); } catch (Exception e) { LOGGER.error("Error validating id token.", e); throw new AuthenticationException("Error validating id token.", e); } }
From source file:org.codice.ddf.security.oidc.realm.OidcTokenValidator.java
License:Open Source License
/** * Validates an access token's signature * * @param accessToken - the token to validate * @param idToken - the corresponding ID token or null if one is not available. If an ID token is * provided, the signature algorithm in the ID token is used. Otherwise the Algorithm provided * in the header of the access token is used. */// ww w .j a v a2 s . c om private void validateAccessTokenSignature(AccessToken accessToken, JWT idToken) { try { ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor(); JWKSource keySource = new RemoteJWKSet(metadata.getJWKSetURI().toURL(), resourceRetriever); // Get signature algorithm, if ID token is given get algorithm from ID Token otherwise // get algorithm from access token header Algorithm expectedAlgorithm; if (idToken == null || idToken.getHeader().getAlgorithm() == Algorithm.NONE) { String accessTokenString = accessToken.getValue(); Base64URL header = new Base64URL(accessTokenString.substring(0, accessTokenString.indexOf('.'))); JSONObject jsonObject = JSONObjectUtils.parse(header.decodeToString()); expectedAlgorithm = Header.parseAlgorithm(jsonObject); } else { expectedAlgorithm = idToken.getHeader().getAlgorithm(); } if (expectedAlgorithm == Algorithm.NONE) { LOGGER.error("Error validating access token. Access token was not signed."); throw new AuthenticationException("Error validating access token. Access token was not signed."); } JWSAlgorithm expectedJWSAlgorithm = new JWSAlgorithm(expectedAlgorithm.getName(), expectedAlgorithm.getRequirement()); JWSKeySelector keySelector = new JWSVerificationKeySelector(expectedJWSAlgorithm, keySource); jwtProcessor.setJWSKeySelector(keySelector); jwtProcessor.process(accessToken.getValue(), null); } catch (Exception e) { LOGGER.error("Error validating access token.", e); throw new AuthenticationException("Error validating access token.", e); } }
From source file:org.codice.ddf.security.oidc.realm.OidcTokenValidator.java
License:Open Source License
/** * Validates the at_hash parameter in the ID token against the access token. If implicit flow is * used with a id_token token response type is used. The at_hash value is required. * * @param accessToken - the token to validate * @param idToken - the corresponding ID token *//*w ww. j ava2 s .c o m*/ private void validateAccessTokenAtHash(AccessToken accessToken, JWT idToken) { try { Object atHash = idToken.getJWTClaimsSet().getClaim("at_hash"); if (atHash == null && !IMPLICIT_FLOWS.contains(new ResponseType(configuration.getResponseType()))) { return; } if (atHash == null) { String errorMessage = "at_hash value not found in response. If the ID Token is issued from the Authorization Endpoint with " + "anaccess_tokenvalue, which is the case for theresponse_typevalue id_tokentoken, this is REQUIRED"; LOGGER.error(errorMessage); throw new AuthenticationException(errorMessage); } JWSAlgorithm jwsAlgorithm = new JWSAlgorithm(idToken.getHeader().getAlgorithm().getName()); AccessTokenHash accessTokenHash = new AccessTokenHash((String) atHash); AccessTokenValidator.validate(accessToken, jwsAlgorithm, accessTokenHash); } catch (Exception e) { LOGGER.error("Error validating access token.", e); throw new AuthenticationException("Error validating access token.", e); } }
From source file:org.commonjava.auth.shiro.couch.CouchRealm.java
License:Apache License
@Override protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) { final Object principal = principals.getPrimaryPrincipal(); User user;// ww w . jav a 2s .co m try { user = dataManager.getUser(principal.toString()); } catch (final UserDataException e) { logger.error("Failed to retrieve user: %s. Reason: %s", e, principal, e.getMessage()); throw new AuthenticationException("Cannot retrieve user. System configuration is invalid."); } if (user == null) { throw new AuthenticationException("Authentication failed: " + principal); } final Set<String> roleNames = new HashSet<String>(); final Set<Permission> perms = new HashSet<Permission>(); if (user.getRoles() != null) { Set<Role> roles; try { roles = dataManager.getRoles(user); } catch (final UserDataException e) { logger.error("Failed to retrieve roles for user: %s. Reason: %s", e, principal, e.getMessage()); throw new AuthenticationException("Cannot retrieve user roles. System configuration is invalid."); } for (final Role role : roles) { roleNames.add(role.getName()); Set<org.commonjava.couch.rbac.Permission> permissions; try { permissions = dataManager.getPermissions(role); } catch (final UserDataException e) { logger.error("Failed to retrieve permissions for role: %s. Reason: %s", e, role.getName(), e.getMessage()); throw new AuthenticationException( "Cannot retrieve role permissions. System configuration is invalid."); } if (permissions != null) { for (final org.commonjava.couch.rbac.Permission perm : permissions) { perms.add(new ShiroPermission(perm)); } } } } return new SimpleAccount(principals, user.getPasswordDigest(), roleNames, perms); }
From source file:org.commonjava.auth.shiro.couch.CouchRealm.java
License:Apache License
@Override protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) throws AuthenticationException { if (!(token instanceof UsernamePasswordToken)) { throw new AuthenticationException("Cannot use authentication token of type: " + token.getClass().getName() + " with this service."); }/*from ww w . j av a2 s . c o m*/ final UsernamePasswordToken tok = (UsernamePasswordToken) token; User user; try { user = dataManager.getUser(tok.getUsername()); } catch (final UserDataException e) { logger.error("Failed to retrieve user: %s. Reason: %s", e, tok.getUsername(), e.getMessage()); throw new AuthenticationException("Cannot retrieve user. System configuration is invalid."); } return ShiroUserUtils.getAuthenticationInfo(user); }
From source file:org.commonjava.badgr.shiro.BadgrRealm.java
License:Apache License
@Override protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) { final Object principal = principals.getPrimaryPrincipal(); User user;//from w w w.j a v a 2s. c o m try { user = dataManager.getUser(principal.toString()); } catch (final BadgrDataException e) { logger.error("Failed to retrieve user: %s. Reason: %s", e, principal, e.getMessage()); throw new AuthenticationException("Cannot retrieve user. System configuration is invalid."); } if (user == null) { throw new AuthenticationException("Authentication failed: " + principal); } final Set<String> roleNames = new HashSet<String>(); final Set<Permission> perms = new HashSet<Permission>(); if (user.getRoles() != null) { Set<Role> roles; try { roles = dataManager.getRoles(user); } catch (final BadgrDataException e) { logger.error("Failed to retrieve roles for user: %s. Reason: %s", e, principal, e.getMessage()); throw new AuthenticationException("Cannot retrieve user roles. System configuration is invalid."); } for (final Role role : roles) { roleNames.add(role.getName()); Set<org.commonjava.badgr.model.Permission> permissions; try { permissions = dataManager.getPermissions(role); } catch (final BadgrDataException e) { logger.error("Failed to retrieve permissions for role: %s. Reason: %s", e, role.getName(), e.getMessage()); throw new AuthenticationException( "Cannot retrieve role permissions. System configuration is invalid."); } if (permissions != null) { for (final org.commonjava.badgr.model.Permission perm : permissions) { perms.add(new ShiroPermission(perm)); } } } } return new SimpleAccount(principals, user.getPasswordDigest(), roleNames, perms); }
From source file:org.commonjava.badgr.shiro.BadgrRealm.java
License:Apache License
@Override protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) throws AuthenticationException { if (!(token instanceof UsernamePasswordToken)) { throw new AuthenticationException("Cannot use authentication token of type: " + token.getClass().getName() + " with this service."); }/* ww w .j a va 2 s . c om*/ final UsernamePasswordToken tok = (UsernamePasswordToken) token; User user; try { user = dataManager.getUser(tok.getUsername()); } catch (final BadgrDataException e) { logger.error("Failed to retrieve user: %s. Reason: %s", e, tok.getUsername(), e.getMessage()); throw new AuthenticationException("Cannot retrieve user. System configuration is invalid."); } return ShiroUserUtils.getAuthenticationInfo(user); }
From source file:org.eclipse.kapua.app.api.auth.KapuaBasicHttpAuthenticationFilter.java
License:Open Source License
@Override protected UsernamePasswordToken createToken(ServletRequest request, ServletResponse response) { AuthenticationToken authcToken = super.createToken(request, response); if (!(authcToken instanceof UsernamePasswordToken)) { throw new AuthenticationException("!(authcToken instanceof UsernamePasswordToken"); }//w w w . j a va 2 s .c o m UsernamePasswordToken userPassToken = (UsernamePasswordToken) authcToken; // TODO Add implement for login with username@account notation return userPassToken; }
From source file:org.eclipse.kapua.service.authentication.shiro.KapuaAuthenticator.java
License:Open Source License
@Override protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) { AuthenticationStrategy strategy = getAuthenticationStrategy(); AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token); if (loggger.isTraceEnabled()) { loggger.trace("Iterating through {} realms for PAM authentication", realms.size()); }// ww w .j a va 2s .co m List<Throwable> exceptionList = new ArrayList<>(); boolean loginSucceeded = false; boolean supportedRealmFound = false; for (Realm realm : realms) { aggregate = strategy.beforeAttempt(realm, token, aggregate); if (realm.supports(token)) { supportedRealmFound = true; loggger.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm); AuthenticationInfo info = null; Throwable t = null; try { info = realm.getAuthenticationInfo(token); loginSucceeded = true; } catch (Throwable throwable) { t = throwable; if (loggger.isDebugEnabled()) { String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:"; loggger.debug(msg, t); } } aggregate = strategy.afterAttempt(realm, token, info, aggregate, t); exceptionList.add(t); } else { loggger.debug("Realm [{}] does not support token {}. Skipping realm.", realm, token); } } //modified behavior from the ModularRealmAuthenticator to provide a more significantly exception message to the user if the login fails if (supportedRealmFound && !loginSucceeded) { //if there is no realm able to authenticate the AuthenticationToken (but at least one realm for this AuthenticationToken was found) lets check the exceptions thrown by the logins if (exceptionList.size() <= 0) { //login failed and we have no exception to show so throw a ShiroException? //TODO move the error message to the message bundle throw new ShiroException("Internal Error!"); } if (exceptionList.get(0) instanceof AuthenticationException) { throw (AuthenticationException) exceptionList.get(0); } else { throw new AuthenticationException(exceptionList.get(0)); } } else { //otherwise if at least one login succeeded lets proceed with the standard ModularRealmAuthenticator aggregate = strategy.afterAllAttempts(token, aggregate); } return aggregate; }
From source file:org.exoplatform.mongo.security.Realm.java
License:Open Source License
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken userPasswordToken = (UsernamePasswordToken) token; String user = userPasswordToken.getUsername(); String password = new String(userPasswordToken.getPassword()); if (!cryptDe.validate(user, password)) { throw new AuthenticationException("Service cannot allow access with invalid credentials"); }/*from www . j a v a 2s.c o m*/ return new SimpleAuthenticationInfo(user, password, getName()); }