List of usage examples for org.springframework.security.core AuthenticationException getMessage
public String getMessage()
From source file:org.cloudfoundry.identity.uaa.authentication.ClientParametersAuthenticationFilter.java
private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo, String clientId) {// w w w. j ava2 s. co m String clientSecret = loginInfo.get(CLIENT_SECRET); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId, clientSecret); authentication.setDetails(new UaaAuthenticationDetails(req, clientId)); try { Authentication auth = clientAuthenticationManager.authenticate(authentication); if (auth == null || !auth.isAuthenticated()) { throw new BadCredentialsException("Client Authentication failed."); } loginInfo.remove(CLIENT_SECRET); AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, getScope(req)); authorizationRequest.setRequestParameters(getSingleValueMap(req)); authorizationRequest.setApproved(true); //must set this to true in order for //Authentication.isAuthenticated to return true OAuth2Authentication result = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); result.setAuthenticated(true); return result; } catch (AuthenticationException e) { throw new BadCredentialsException(e.getMessage(), e); } catch (Exception e) { logger.debug("Unable to authenticate client: " + clientId, e); throw new BadCredentialsException(e.getMessage(), e); } }
From source file:org.cloudfoundry.identity.uaa.authentication.manager.ChainedAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication == null) { return authentication; }//from w w w. j a v a 2 s . c o m UsernamePasswordAuthenticationToken output = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { output = (UsernamePasswordAuthenticationToken) authentication; } else { output = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), authentication.getAuthorities()); output.setDetails(authentication.getDetails()); } boolean authenticated = false; Authentication auth = null; AuthenticationException lastException = null; boolean lastResult = false; boolean shallContinue = true; if (delegates == null || delegates.length == 0) { throw new ProviderNotFoundException("No available authentication providers."); } for (int i = 0; shallContinue && i < delegates.length; i++) { boolean shallAuthenticate = (i == 0) || (lastResult && IF_PREVIOUS_TRUE.equals(delegates[i].getRequired())) || ((!lastResult) && IF_PREVIOUS_FALSE.equals(delegates[i].getRequired())); if (shallAuthenticate) { if (logger.isDebugEnabled()) { logger.debug("Attempting chained authentication of " + output + " with manager:" + delegates[i].getAuthenticationManager() + " required:" + delegates[i].getRequired()); } Authentication thisAuth = null; try { thisAuth = delegates[i].getAuthenticationManager().authenticate(auth != null ? auth : output); } catch (AuthenticationException x) { if (logger.isDebugEnabled()) { logger.debug("Chained authentication exception:" + x.getMessage() + " at:" + (x.getStackTrace().length > 0 ? x.getStackTrace()[0] : "(no stack trace)")); } lastException = x; if (delegates[i].getStopIf() != null) { for (Class<? extends AuthenticationException> exceptionClass : delegates[i].getStopIf()) { if (exceptionClass.isAssignableFrom(x.getClass())) { shallContinue = false; break; } } } } lastResult = thisAuth != null && thisAuth.isAuthenticated(); if (lastResult) { authenticated = true; auth = thisAuth; } else { authenticated = false; auth = null; } } else { shallContinue = false; } if (logger.isDebugEnabled()) { logger.debug("Chained Authentication status of " + output + " with manager:" + delegates[i] + "; Authenticated:" + authenticated); } } if (authenticated) { return auth; } else if (lastException != null) { //we had at least one authentication exception, throw it throw lastException; } else { //not authenticated, but return the last of the result return auth; } }
From source file:org.cloudfoundry.identity.uaa.oauth.CheckTokenEndpoint.java
@RequestMapping(value = "/check_token") @ResponseBody/*from w w w . j ava2s . c o m*/ public Claims checkToken(@RequestParam("token") String value, @RequestParam(name = "scopes", required = false, defaultValue = "") List<String> scopes) { OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value); if (token == null) { throw new InvalidTokenException("Token was not recognised"); } if (token.isExpired()) { throw new InvalidTokenException("Token has expired"); } try { resourceServerTokenServices.loadAuthentication(value); } catch (AuthenticationException x) { throw new InvalidTokenException((x.getMessage())); } Claims response = getClaimsForToken(token.getValue()); List<String> claimScopes = response.getScope().stream().map(String::toLowerCase) .collect(Collectors.toList()); List<String> missingScopes = new ArrayList<>(); for (String expectedScope : scopes) { if (!claimScopes.contains(expectedScope.toLowerCase())) { missingScopes.add(expectedScope); } } if (!missingScopes.isEmpty()) { throw new InvalidScopeException( "Some requested scopes are missing: " + String.join(",", missingScopes)); } return response; }
From source file:org.craftercms.social.util.support.security.CrafterProfileFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String token = getParamFromRequest(httpRequest, tokenRequestParamKey); String tenantName = getParamFromRequest(httpRequest, tenantRequestParamKey); try {/*from w ww .j a va2s .c o m*/ // get encrypted token cookie with the user profile information String encryptedToken = getCipherTokenCookie(httpRequest); // get the cipher SimpleDesCipher cipher = new SimpleDesCipher(cipherkey); // try to use the encryptedToken first if (encryptedToken != null && !encryptedToken.isEmpty()) { // decrypt the cookie and read values from it String[] profileValues = getProfileValues(encryptedToken, cipher); String profileToken = profileValues[TOKEN]; /* Validate the token. If the simple token & cookie token don't match, * the user may have changed, so use the basic ticket in this case */ if (profileToken.equals(token) && profile.validateUserToken(profileToken)) { authenticateWithCipherToken(chain, httpRequest, httpResponse, tenantName, cipher, profileValues, profileToken); } else { // try authenticate with the simple token, is token in cipher is no longer valid authenticateWithSimpleToken(chain, httpRequest, httpResponse, token, tenantName, cipher); } /* if no encrypted token, look for regular token & start with that * this will always happen before the encrypted token */ } else { authenticateWithSimpleToken(chain, httpRequest, httpResponse, token, tenantName, cipher); } } catch (org.craftercms.social.exceptions.AuthenticationException authExc) { failRequest(httpRequest, httpResponse, new BadCredentialsException(authExc.getMessage())); } }
From source file:org.dspace.app.rest.security.StatelessLoginFilter.java
@Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { AuthenticationService authenticationService = restAuthenticationService.getAuthenticationService(); Iterator<AuthenticationMethod> authenticationMethodIterator = authenticationService .authenticationMethodIterator(); Context context = ContextUtil.obtainContext(request); StringBuilder wwwAuthenticate = new StringBuilder(); while (authenticationMethodIterator.hasNext()) { AuthenticationMethod authenticationMethod = authenticationMethodIterator.next(); if (wwwAuthenticate.length() > 0) { wwwAuthenticate.append(", "); }//from w ww . j a va 2 s . co m wwwAuthenticate.append(authenticationMethod.getName()).append(" realm=\"DSpace REST API\""); String loginPageURL = authenticationMethod.loginPageURL(context, request, response); if (StringUtils.isNotBlank(loginPageURL)) { // We cannot reply with a 303 code because may browsers handle 3xx response codes transparently. This // means that the JavaScript client code is not aware of the 303 status and fails to react accordingly. wwwAuthenticate.append(", location=\"").append(loginPageURL).append("\""); } } response.setHeader("WWW-Authenticate", wwwAuthenticate.toString()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, failed.getMessage()); }
From source file:org.hx.rainbow.common.security.login.RainbowFailureHandler.java
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if (this.defaultFailureUrl == null) { this.logger.debug("No failure URL set, sending 401 Unauthorized error"); response.sendError(401, "Authentication Failed: " + exception.getMessage()); } else {/*from w w w. ja v a 2 s . com*/ saveException(request, exception); if (this.forwardToDestination) { this.logger.debug("Forwarding to " + this.defaultFailureUrl); request.getRequestDispatcher(this.defaultFailureUrl + exception.getMessage()).forward(request, response); } else { this.logger.debug("Redirecting to " + this.defaultFailureUrl); this.redirectStrategy.sendRedirect(request, response, this.defaultFailureUrl + exception.getMessage()); } } }
From source file:org.hyperic.hq.web.login.LoginController.java
@RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login(HttpServletRequest request, HttpServletResponse response, HttpSession session) { final boolean debug = log.isDebugEnabled(); ModelAndView result = new ModelAndView(); // ...first check for an authentication object, if one exists we are already logged in... Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated()) { try {/*from w ww. j a v a 2s .c om*/ if (debug) log.debug("User has already been authenticated. Redirecting to dashboard."); response.sendRedirect("/Dashboard.do"); return result; } catch (IOException e) { log.warn("Could not perform the redirect for an authenticated user, displaying login page instead"); } } // ...we're dealing with an unauthenticated user, we're going to show the login form... AuthzSubject guestUser = authzSubjectManager.getSubjectById(AuthzConstants.guestId); // ...before we return, check for an error message... boolean loginError = request.getParameter("authfailed") != null; if (loginError) { if (session != null) { AuthenticationException ex = (AuthenticationException) session .getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY); if (ex != null) { result.addObject("errorMessage", RequestUtils.message(request, ex.getMessage())); } } } result.addObject("guestUsername", (guestUser != null) ? guestUser.getName() : "guest"); result.addObject("guestEnabled", (guestUser != null && guestUser.getActive())); // ...set a response header so we can identify the login page explicitly... response.setHeader("hq-requires-auth", "1"); return result; }
From source file:org.jwebsocket.plugins.system.SystemPlugIn.java
/** * Logon a user given the username and password by using the Spring Security module * * @param aConnector// w ww . j a va2 s . c o m * @param aToken The token with the username and password */ void logon(WebSocketConnector aConnector, Token aToken) { TokenServer lServer = getServer(); if (aConnector.getSession().isAuthenticated()) { lServer.sendToken(aConnector, lServer.createErrorToken(aToken, -1, "is authenticated")); return; } String lUsername = aToken.getString("username"); String lPassword = aToken.getString("password"); if (mLog.isDebugEnabled()) { mLog.debug("Starting authentication ..."); } Authentication lAuthRequest = new UsernamePasswordAuthenticationToken(lUsername, lPassword); Authentication lAuthResult; try { lAuthResult = getAuthProvMgr().authenticate(lAuthRequest); } catch (AuthenticationException ex) { String lMsg = ex.getClass().getSimpleName() + ": " + ex.getMessage(); Token lResponse = getServer().createErrorToken(aToken, -1, lMsg); lResponse.setString("username", lUsername); sendToken(aConnector, aConnector, lResponse); if (mLog.isDebugEnabled()) { mLog.debug(lMsg); } return; // stop the execution flow } if (mLog.isDebugEnabled()) { mLog.debug("Authentication successful. Updating the user session (id: " + (null != aConnector.getSession() ? aConnector.getSession().getSessionId() : "[null]") + ", storage: " + (null != aConnector.getSession() ? aConnector.getSession().getStorage() : "[null]") + ")..."); } // getting the session Map<String, Object> lSession = aConnector.getSession().getStorage(); // setting the is_authenticated flag lSession.put(IS_AUTHENTICATED, lAuthResult.isAuthenticated()); // setting the connector username aConnector.setUsername(lUsername); // setting the uuid String lUUID; Object lDetails = lAuthResult.getDetails(); if (null != lDetails && lDetails instanceof IUserUniqueIdentifierContainer) { lUUID = ((IUserUniqueIdentifierContainer) lDetails).getUUID(); } else { lUUID = lUsername; } lSession.put(UUID, lUUID); // setting the authorities String lAuthorities = ""; for (GrantedAuthority lGA : lAuthResult.getAuthorities()) { lAuthorities = lAuthorities.concat(lGA.getAuthority() + " "); } // storing the user authorities as a string to avoid serialization problems lSession.put(AUTHORITIES, lAuthorities); // creating the response Token lResponse = createResponse(aToken); lResponse.setString("uuid", lUUID); lResponse.setString("username", lUsername); lResponse.setList("authorities", Tools.parseStringArrayToList(lAuthorities.split(" "))); // sending the response to requester sendToken(aConnector, lResponse); // sending response to clients that share the requester session getServer().broadcastToSharedSession(aConnector.getId(), aConnector.getSession().getSessionId(), lResponse, false); if (mLog.isDebugEnabled()) { mLog.debug("Logon process finished successfully!"); } // if successfully logged in... if (lUsername != null) { // broadcast "login event" to other clients broadcastLoginEvent(aConnector); } }
From source file:org.nimbustools.ctxbroker.rest.FailAuthenticationEntryPoint.java
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { ErrorMessage error = new ErrorMessage("Unauthorized: " + authException.getMessage()); if (logger.isDebugEnabled()) { logger.debug("Sending authentication failure response: " + error.toString(), authException); }/*from w w w . ja va 2 s .c o m*/ this.responseUtil.sendServletError(response, error, HttpServletResponse.SC_UNAUTHORIZED); }
From source file:org.patientview.radar.service.impl.UserManagerImpl.java
public boolean authenticateProfessionalUser(String username, String password) throws AuthenticationException { ProfessionalUser professionalUser = userDao.getProfessionalUserByUsername(username); if (professionalUser != null) { try {//from w w w .jav a 2 s . c om Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); return authentication.isAuthenticated(); } catch (AuthenticationException e) { LOGGER.warn("Authentication failed for user {} and password {}", username, e.getMessage()); throw e; } } return false; }