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.openid.connect.assertion.JWTBearerClientAssertionTokenEndpointFilter.java
/** * Pull the assertion out of the request and send it up to the auth manager for processing. *//*from w ww . j av a 2s. co m*/ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { // check for appropriate parameters String assertionType = request.getParameter("client_assertion_type"); String assertion = request.getParameter("client_assertion"); try { JWT jwt = JWTParser.parse(assertion); String clientId = jwt.getJWTClaimsSet().getSubject(); Authentication authRequest = new JWTBearerAssertionAuthenticationToken(clientId, jwt); return this.getAuthenticationManager().authenticate(authRequest); } catch (ParseException e) { throw new BadCredentialsException("Invalid JWT credential: " + assertion); } }
From source file:org.openengsb.opencit.ui.web.AbstractCitPageTest.java
private void mockAuthentication() { AuthenticationManager authManager = mock(AuthenticationManager.class); final Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new GrantedAuthorityImpl("ROLE_USER")); when(authManager.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() { @Override/*from www. j ava2 s. c o m*/ public Authentication answer(InvocationOnMock invocation) { Authentication auth = (Authentication) invocation.getArguments()[0]; if (auth.getCredentials().equals("password")) { return new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), authorities); } throw new BadCredentialsException("wrong password"); } }); appContext.putBean("authenticationManager", authManager); }
From source file:com.devicehive.websockets.handlers.CommonHandlers.java
@PreAuthorize("permitAll") public WebSocketResponse processRefresh(JsonObject request, WebSocketSession session) { String refreshToken = null;/* ww w.j a v a2 s. co m*/ if (request.get("refreshToken") != null) { refreshToken = request.get("refreshToken").getAsString(); } JwtPayload payload; try { payload = tokenService.getPayload(refreshToken); } catch (Exception e) { logger.error(e.getMessage(), e); throw new BadCredentialsException(e.getMessage()); } UserVO user = userService.findById(payload.getUserId()); if (user == null) { String msg = "JwtToken: User not found"; logger.warn(msg); throw new BadCredentialsException(msg); } if (!user.getStatus().equals(UserStatus.ACTIVE)) { String msg = "JwtToken: User is not active"; logger.warn(msg); throw new BadCredentialsException(msg); } if (!payload.getTokenType().equals(TokenType.REFRESH)) { String msg = "JwtToken: refresh token is not valid"; logger.warn(msg); throw new BadCredentialsException(msg); } if (payload.getExpiration().before(timestampService.getDate())) { String msg = "JwtToken: refresh token has expired"; logger.warn(msg); throw new BadCredentialsException(msg); } WebSocketResponse response = new WebSocketResponse(); response.addValue("accessToken", tokenService.generateJwtAccessToken(payload)); return response; }
From source file:com.erudika.para.security.FacebookAuthFilter.java
/** * Handles an authentication request.//from w w w . ja va 2s. c o m * @param request HTTP request * @param response HTTP response * @return an authentication object that contains the principal object if successful. * @throws IOException ex */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { final String requestURI = request.getRequestURI(); UserAuthentication userAuth = null; if (requestURI.endsWith(FACEBOOK_ACTION)) { String authCode = request.getParameter("code"); if (!StringUtils.isBlank(authCode)) { String url = Utils.formatMessage(TOKEN_URL, authCode, request.getRequestURL().toString(), Config.FB_APP_ID, Config.FB_SECRET); HttpGet tokenPost = new HttpGet(url); CloseableHttpResponse resp1 = httpclient.execute(tokenPost); if (resp1 != null && resp1.getEntity() != null) { String token = EntityUtils.toString(resp1.getEntity(), Config.DEFAULT_ENCODING); if (token != null && token.startsWith("access_token")) { String accessToken = token.substring(token.indexOf("=") + 1, token.indexOf("&")); userAuth = getOrCreateUser(null, accessToken); } EntityUtils.consumeQuietly(resp1.getEntity()); } } } User user = SecurityUtils.getAuthenticatedUser(userAuth); if (userAuth == null || user == null || user.getIdentifier() == null) { throw new BadCredentialsException("Bad credentials."); } else if (!user.getActive()) { throw new LockedException("Account is locked."); } return userAuth; }
From source file:com.erudika.para.security.LinkedInAuthFilter.java
/** * Handles an authentication request./* ww w . j a v a 2s .c o m*/ * @param request HTTP request * @param response HTTP response * @return an authentication object that contains the principal object if successful. * @throws IOException ex */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException { final String requestURI = request.getRequestURI(); UserAuthentication userAuth = null; if (requestURI.endsWith(LINKEDIN_ACTION)) { String authCode = request.getParameter("code"); if (!StringUtils.isBlank(authCode)) { String url = Utils.formatMessage(TOKEN_URL, authCode, request.getRequestURL().toString(), Config.LINKEDIN_APP_ID, Config.LINKEDIN_SECRET); HttpPost tokenPost = new HttpPost(url); CloseableHttpResponse resp1 = httpclient.execute(tokenPost); if (resp1 != null && resp1.getEntity() != null) { Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent()); if (token != null && token.containsKey("access_token")) { userAuth = getOrCreateUser(null, (String) token.get("access_token")); } EntityUtils.consumeQuietly(resp1.getEntity()); } } } User user = SecurityUtils.getAuthenticatedUser(userAuth); if (userAuth == null || user == null || user.getIdentifier() == null) { throw new BadCredentialsException("Bad credentials."); } else if (!user.getActive()) { throw new LockedException("Account is locked."); } return userAuth; }
From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = (String) authentication.getCredentials(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(); parameters.set("username", username); parameters.set("password", password); @SuppressWarnings("rawtypes") ResponseEntity<Map> response = restTemplate.exchange(loginUrl, HttpMethod.POST, new HttpEntity<MultiValueMap<String, Object>>(parameters, headers), Map.class); if (response.getStatusCode() == HttpStatus.OK) { String userFromUaa = (String) response.getBody().get("username"); if (userFromUaa.equals(userFromUaa)) { logger.info("Successful authentication request for " + authentication.getName()); return new UsernamePasswordAuthenticationToken(username, null, UaaAuthority.USER_AUTHORITIES); }// w ww. j ava 2 s .c om } else if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) { logger.info("Failed authentication request"); throw new BadCredentialsException("Authentication failed"); } else if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) { logger.info("Internal error from UAA. Please Check the UAA logs."); } else { logger.error("Unexpected status code " + response.getStatusCode() + " from the UAA." + " Is a compatible version running?"); } throw new RuntimeException("Could not authenticate with remote server"); }
From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.simple.services.presentation.SimpleAuthenticationServiceImpl.java
/** * Authenticates an user. Requires basic authentication header. * @param httpServletRequest/*from w ww . j ava2s. co m*/ * @param httpServletResponse * @return * @throws Exception */ @RequestMapping(value = "${appverse.frontfacade.rest.simpleAuthenticationEndpoint.path:/sec/simplelogin}", method = RequestMethod.POST) public ResponseEntity<AuthorizationData> login(@RequestBody CredentialsVO credentials, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { try { if (credentials == null || credentials.getUsername() == null) { throw new BadCredentialsException("Invalid parameters"); } // Authenticate principal and return authorization data AuthorizationData authData = userAndPasswordAuthenticationManager .authenticatePrincipal(credentials.getUsername(), credentials.getPassword()); if (securityEnableCsrf) { // Obtain XSRFToken and add it as a response header // The token comes in the request (CsrFilter adds it) and we need to set it in the response so the clients // have it to use it in the next requests CsrfToken csrfToken = (CsrfToken) httpServletRequest.getAttribute(CSRF_TOKEN_SESSION_ATTRIBUTE); httpServletResponse.addHeader(csrfToken.getHeaderName(), csrfToken.getToken()); } // AuthorizationDataVO return new ResponseEntity<AuthorizationData>(authData, HttpStatus.OK); } catch (AuthenticationException e) { return new ResponseEntity<AuthorizationData>(HttpStatus.UNAUTHORIZED); } }
From source file:org.verinice.rest.security.VeriniceAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); // Determine username String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName(); boolean cacheWasUsed = true; UserDetails user = this.getUserCache().getUserFromCache(username); if (user == null) { cacheWasUsed = false;// w ww . j a va 2s. c o m try { user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); } catch (UsernameNotFoundException notFound) { logger.debug("User '" + username + "' not found"); if (hideUserNotFoundExceptions) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } else { throw notFound; } } catch (InternalAuthenticationServiceException e) { throw new BadCredentialsException(e.getMessage(), e); } Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract"); } try { getPreAuthenticationChecks().check(user); additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); } catch (AuthenticationException exception) { if (cacheWasUsed) { // There was a problem, so try again after checking // we're using latest data (i.e. not from the cache) cacheWasUsed = false; user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); getPreAuthenticationChecks().check(user); additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); } else { throw exception; } } getPostAuthenticationChecks().check(user); if (!cacheWasUsed) { this.getUserCache().putUserInCache(user); } Object principalToReturn = user; if (isForcePrincipalAsString()) { principalToReturn = user.getUsername(); } return createSuccessAuthentication(principalToReturn, authentication, user); }
From source file:com.haulmont.restapi.auth.ExternalOAuthTokenGranter.java
@Override public OAuth2AccessTokenResult issueToken(OAuth2AccessTokenRequest tokenRequest) { RestApiConfig config = configuration.getConfig(RestApiConfig.class); String login = tokenRequest.getLogin(); Locale locale = tokenRequest.getLocale(); Map<String, String> parameters = new HashMap<>(); parameters.put("username", login); parameters.put("client_id", config.getRestClientId()); parameters.put("scope", "rest-api"); parameters.put("grant", GRANT_TYPE); UserSession session;/*from ww w . ja v a 2s . c om*/ try { TrustedClientCredentials credentials = new TrustedClientCredentials(login, config.getTrustedClientPassword(), locale); credentials.setClientType(ClientType.REST_API); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .currentRequestAttributes(); if (attributes != null) { HttpServletRequest request = attributes.getRequest(); credentials.setIpAddress(request.getRemoteAddr()); credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT))); } else { credentials.setClientInfo(makeClientInfo("")); } credentials.setParams(tokenRequest.getLoginParams()); session = authenticationService.login(credentials).getSession(); } catch (RestApiAccessDeniedException ex) { log.info("User is not allowed to use the REST API {}", login); throw new BadCredentialsException("User is not allowed to use the REST API"); } catch (LoginException e) { log.info("Unable to issue token for REST API: {}", login); throw new BadCredentialsException("Bad credentials"); } parameters.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString()); for (Map.Entry<String, String> tokenParam : tokenRequest.getTokenDetails().entrySet()) { parameters.put(EXTENDED_DETAILS_ATTRIBUTE_PREFIX + tokenParam.getKey(), tokenParam.getValue()); } // issue token using obtained Session, it is required for DB operations inside of persistent token store OAuth2AccessToken accessToken = withSecurityContext(new SecurityContext(session), () -> { ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(config.getRestClientId()); TokenRequest tr = getRequestFactory().createTokenRequest(parameters, authenticatedClient); return grant(GRANT_TYPE, tr); }); return new OAuth2AccessTokenResult(session, accessToken); }
From source file:org.dspace.rest.authentication.DSpaceAuthenticationProvider.java
private Authentication createAuthenticationToken(final String password, final Context context, final List<SimpleGrantedAuthority> grantedAuthorities) { EPerson ePerson = context.getCurrentUser(); if (ePerson != null && StringUtils.isNotBlank(ePerson.getEmail())) { return new UsernamePasswordAuthenticationToken(ePerson.getEmail(), password, grantedAuthorities); } else {//from w ww. j a va 2s . c om log.info(LogManager.getHeader(context, "failed_login", "No eperson with an non-blank e-mail address found")); throw new BadCredentialsException("Login failed"); } }