List of usage examples for org.springframework.security.authentication BadCredentialsException BadCredentialsException
public BadCredentialsException(String msg)
BadCredentialsException
with the specified message. From source file:org.mitre.oauth2.token.JWTAssertionTokenGranter.java
@Override protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException { // read and load up the existing token String incomingTokenValue = tokenRequest.getRequestParameters().get("assertion"); OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue); if (incomingToken.getScope().contains(SystemScopeService.ID_TOKEN_SCOPE)) { if (!client.getClientId().equals(tokenRequest.getClientId())) { throw new InvalidClientException("Not the right client for this token"); }// w w w .j av a 2 s .c om // it's an ID token, process it accordingly try { // TODO: make this use a more specific idtoken class JWT idToken = JWTParser.parse(incomingTokenValue); OAuth2AccessTokenEntity accessToken = tokenServices.getAccessTokenForIdToken(incomingToken); if (accessToken != null) { //OAuth2AccessTokenEntity newIdToken = tokenServices.get OAuth2AccessTokenEntity newIdTokenEntity = new OAuth2AccessTokenEntity(); // copy over all existing claims JWTClaimsSet.Builder claims = new JWTClaimsSet.Builder(idToken.getJWTClaimsSet()); if (client instanceof ClientDetailsEntity) { ClientDetailsEntity clientEntity = (ClientDetailsEntity) client; // update expiration and issued-at claims if (clientEntity.getIdTokenValiditySeconds() != null) { Date expiration = new Date(System.currentTimeMillis() + (clientEntity.getIdTokenValiditySeconds() * 1000L)); claims.expirationTime(expiration); newIdTokenEntity.setExpiration(expiration); } } else { //This should never happen logger.fatal("SEVERE: Client is not an instance of OAuth2AccessTokenEntity."); throw new BadCredentialsException( "SEVERE: Client is not an instance of ClientDetailsEntity; JwtAssertionTokenGranter cannot process this request."); } claims.issueTime(new Date()); claims.jwtID(UUID.randomUUID().toString()); // set a random NONCE in the middle of it SignedJWT newIdToken = new SignedJWT((JWSHeader) idToken.getHeader(), claims.build()); jwtService.signJwt(newIdToken); newIdTokenEntity.setJwt(newIdToken); newIdTokenEntity.setAuthenticationHolder(incomingToken.getAuthenticationHolder()); newIdTokenEntity.setScope(incomingToken.getScope()); newIdTokenEntity.setClient(incomingToken.getClient()); newIdTokenEntity = tokenServices.saveAccessToken(newIdTokenEntity); // attach the ID token to the access token entity accessToken.setIdToken(newIdTokenEntity); accessToken = tokenServices.saveAccessToken(accessToken); // delete the old ID token tokenServices.revokeAccessToken(incomingToken); return newIdTokenEntity; } } catch (ParseException e) { logger.warn("Couldn't parse id token", e); } } // if we got down here, we didn't actually create any tokens, so return null return null; /* * Otherwise, process it like an access token assertion ... which we don't support yet so this is all commented out * / if (jwtService.validateSignature(incomingTokenValue)) { Jwt jwt = Jwt.parse(incomingTokenValue); if (oldToken.getScope().contains("id-token")) { // TODO: things } // TODO: should any of these throw an exception instead of returning null? JwtClaims claims = jwt.getClaims(); if (!config.getIssuer().equals(claims.getIssuer())) { // issuer isn't us return null; } if (!authorizationRequest.getClientId().equals(claims.getAudience())) { // audience isn't the client return null; } Date now = new Date(); if (!now.after(claims.getExpiration())) { // token is expired return null; } // FIXME // This doesn't work. We need to look up the old token, figure out its scopes and bind it appropriately. // In the case of an ID token, we need to look up its parent access token and change the reference, and revoke the old one, and // that's tricky. // we might need new calls on the token services layer to handle this, and we might // need to handle id tokens separately. return new OAuth2Authentication(authorizationRequest, null); } else { return null; // throw error?? } */ }
From source file:sk.lazyman.gizmo.security.GizmoAuthProvider.java
private Authentication authenticateUsingLdap(Authentication authentication) throws AuthenticationException { String principal = (String) authentication.getPrincipal(); DirContextOperations ctx = ldapBindAuthenticator.authenticate(authentication); User user = userRepository.findUserByName(principal); if (user == null) { user = createUser(ctx, principal); }/* w ww.jav a 2s.c o m*/ if (!user.isEnabled()) { throw new BadCredentialsException("GizmoAuthenticationProvider.userDisabled"); } GizmoPrincipal gizmoPrincipal = new GizmoPrincipal(user); LOGGER.debug("User '{}' authenticated ({}), authorities: {}", new Object[] { authentication.getPrincipal(), authentication.getClass().getSimpleName(), gizmoPrincipal.getAuthorities() }); return new UsernamePasswordAuthenticationToken(gizmoPrincipal, null, gizmoPrincipal.getAuthorities()); }
From source file:org.awesomeagile.testing.google.FakeGoogleController.java
private void validateAuthorization(String authorizationHeader) { if (StringUtils.startsWithIgnoreCase(authorizationHeader, BEARER)) { if (knownTokens.contains(StringUtils.removeStartIgnoreCase(authorizationHeader, BEARER).trim())) { return; }// w w w. j ava2 s.c om } throw new BadCredentialsException("Invalid authorization header: " + authorizationHeader); }
From source file:it.scoppelletti.programmerpower.web.security.CasClient.java
/** * Richiede un ticket di autenticazione. * //from w w w. ja va2 s. c om * @param userName Nome dell’utente. * @param pwd Password. * @return Ticket di autenticazione. */ public String newTicketGrantingTicket(String userName, SecureString pwd) throws ProtocolException { String text; Matcher matcher; Client client; Request req; Response resp; Form form; Status status; WebResources res = new WebResources(); SecurityResources secRes = new SecurityResources(); if (Strings.isNullOrEmpty(userName)) { throw new ArgumentNullException("userName"); } if (Values.isNullOrEmpty(pwd)) { throw new ArgumentNullException("pwd"); } if (Strings.isNullOrEmpty(myServerUrl)) { throw new PropertyNotSetException(toString(), "serverUrl"); } if (myServiceProps == null) { throw new PropertyNotSetException(toString(), "serviceProperties"); } form = new Form(); form.add("username", userName); form.add("password", pwd.toString()); req = new Request(Method.POST, myServerUrl); req.setEntity(form.getWebRepresentation(CharacterSet.UTF_8)); client = new Client(Protocol.HTTPS); resp = client.handle(req); status = resp.getStatus(); if (status.equals(Status.CLIENT_ERROR_BAD_REQUEST)) { throw new BadCredentialsException(secRes.getFailedLoginException()); } if (status.equals(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE)) { throw new ProtocolException(res.getUnsupportedMediaTypeException()); } if (!status.equals(Status.SUCCESS_CREATED)) { throw new ProtocolException( res.getUnexpectedStatusCodeException(status.getCode(), status.getDescription())); } text = resp.getEntityAsText(); if (Strings.isNullOrEmpty(text)) { throw new ProtocolException(res.getEmptyResponseException()); } matcher = myTGTFormat.matcher(text); if (!matcher.matches()) { throw new ProtocolException(res.getInvalidResponseException(text)); } return matcher.group(1); }
From source file:com.evolveum.midpoint.model.impl.security.AuthenticationEvaluatorImpl.java
@Override public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx) throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {/*from w w w.j ava 2 s . c o m*/ checkEnteredCredentials(connEnv, authnCtx); MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true); UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); if (checkCredentials(principal, authnCtx, connEnv)) { recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, authnCtx.getEnteredCredential(), principal.getAuthorities()); return token; } else { recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch"); throw new BadCredentialsException("web.security.provider.invalid"); } }
From source file:com.alliander.osgp.shared.security.CustomAuthenticationManager.java
private void checkUsernameAndPasswordForEmptiness(final String username, final String password) { // Check user name and password. if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { LOGGER.debug(NULL_BLANK_USERNAME_CREDENTIALS); throw new BadCredentialsException(NULL_BLANK_USERNAME_CREDENTIALS); }/* w ww .j a v a 2 s. co m*/ }
From source file:com.haulmont.restapi.ldap.LdapAuthController.java
protected OAuth2AccessTokenResult authenticate(String username, String password, Locale locale, String ipAddress, Map<String, String> parameters) { if (!ldapTemplate.authenticate(LdapUtils.emptyLdapName(), buildPersonFilter(username), password)) { log.info("REST API authentication failed: {} {}", username, ipAddress); throw new BadCredentialsException("Bad credentials"); }/*from w ww . ja v a2 s. c o m*/ return oAuthTokenIssuer.issueToken(username, locale, Collections.emptyMap()); }
From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.controllers.BasicAuthenticationRESTController.java
private String[] obtainUserAndPasswordFromBasicAuthenticationHeader(HttpServletRequest httpServletRequest) throws Exception { // Authorization header String authHeader = httpServletRequest.getHeader("Authorization"); if (authHeader == null) { throw new BadCredentialsException("Authorization header not found"); }/*from w w w . ja va 2 s. c o m*/ // Decode the authorization string BASE64Decoder decoder = new BASE64Decoder(); String token; try { byte[] decoded = decoder.decodeBuffer(authHeader.substring(6)); token = new String(decoded); } catch (IllegalArgumentException e) { throw new BadCredentialsException("Failed to decode basic authentication token"); } int separator = token.indexOf(":"); if (separator == -1) { throw new BadCredentialsException("Invalid basic authentication token"); } return new String[] { token.substring(0, separator), token.substring(separator + 1) }; }
From source file:com.alliander.osgp.shared.security.CustomAuthenticationManager.java
private void checkLoginResponse(final LoginResponse loginResponse) { // Check if the response equals null. if (loginResponse == null) { LOGGER.debug(LOGIN_RESPONSE_IS_NULL); throw new BadCredentialsException(LOGIN_RESPONSE_IS_NULL); }//from w w w .j a v a 2 s . c o m // Check if the response is OK. if (!loginResponse.getFeedbackMessage().equals(OK)) { LOGGER.debug(LOGIN_RESPONSE_IS_NOT_OK); throw new BadCredentialsException(LOGIN_RESPONSE_IS_NOT_OK); } }
From source file:com.evolveum.midpoint.web.security.MidPointAuthenticationProvider.java
private Authentication authenticateUserPassword(MidPointPrincipal principal, String password) throws BadCredentialsException { if (StringUtils.isBlank(password)) { throw new BadCredentialsException("web.security.provider.access.denied"); }/*from w w w . j a va2 s . com*/ if (principal == null || principal.getUser() == null || principal.getUser().getCredentials() == null) { throw new BadCredentialsException("web.security.provider.invalid"); } if (!principal.isEnabled()) { throw new BadCredentialsException("web.security.provider.disabled"); } UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); PasswordType passwordType = credentials.getPassword(); int failedLogins = passwordType.getFailedLogins() != null ? passwordType.getFailedLogins() : 0; if (maxFailedLogins > 0 && failedLogins >= maxFailedLogins) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(MiscUtil.asDate(passwordType.getLastFailedLogin().getTimestamp()).getTime()); calendar.add(Calendar.MINUTE, loginTimeout); long lockedTill = calendar.getTimeInMillis(); if (lockedTill > System.currentTimeMillis()) { throw new BadCredentialsException("web.security.provider.locked"); } } ProtectedStringType protectedString = passwordType.getValue(); if (protectedString == null) { throw new BadCredentialsException("web.security.provider.password.bad"); } if (StringUtils.isEmpty(password)) { throw new BadCredentialsException("web.security.provider.password.encoding"); } Collection<Authorization> authorizations = principal.getAuthorities(); if (authorizations == null || authorizations.isEmpty()) { throw new BadCredentialsException("web.security.provider.access.denied"); } for (Authorization auth : authorizations) { if (auth.getAction() == null || auth.getAction().isEmpty()) { throw new BadCredentialsException("web.security.provider.access.denied"); } } try { String decoded; if (protectedString.getEncryptedDataType() != null) { decoded = protector.decryptString(protectedString); } else { LOGGER.warn("Authenticating user based on clear value. Please check objects, " + "this should not happen. Protected string should be encrypted."); decoded = protectedString.getClearValue(); } if (password.equals(decoded)) { // Good password if (failedLogins > 0) { passwordType.setFailedLogins(0); } XMLGregorianCalendar systemTime = MiscUtil .asXMLGregorianCalendar(new Date(System.currentTimeMillis())); LoginEventType event = new LoginEventType(); event.setTimestamp(systemTime); event.setFrom(getRemoteHost()); passwordType.setPreviousSuccessfulLogin(passwordType.getLastSuccessfulLogin()); passwordType.setLastSuccessfulLogin(event); userProfileService.updateUser(principal); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, password, principal.getAuthorities()); return token; } else { // Bad password passwordType.setFailedLogins(++failedLogins); XMLGregorianCalendar systemTime = MiscUtil .asXMLGregorianCalendar(new Date(System.currentTimeMillis())); LoginEventType event = new LoginEventType(); event.setTimestamp(systemTime); event.setFrom(getRemoteHost()); passwordType.setLastFailedLogin(event); userProfileService.updateUser(principal); throw new BadCredentialsException("web.security.provider.invalid"); } } catch (EncryptionException ex) { throw new AuthenticationServiceException("web.security.provider.unavailable", ex); } }