Java Code Examples for org.springframework.security.core.AuthenticationException#getMessage()
The following examples show how to use
org.springframework.security.core.AuthenticationException#getMessage() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JwtAuthenticationEntryPoint.java From spring-oauth2-jwt-jdbc with MIT License | 6 votes |
@Override public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { httpServletResponse.setStatus(SC_FORBIDDEN); httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); String message; if(e.getCause() != null) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } byte[] body = new ObjectMapper() .writeValueAsBytes(Collections.singletonMap("error", message)); httpServletResponse.getOutputStream().write(body); }
Example 2
Source File: SpringSecurityHelper.java From teiid-spring-boot with Apache License 2.0 | 6 votes |
@Override public Object authenticate(String securityDomain, String baseUserName, Credentials credentials, String applicationName) throws LoginException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authenticationManager != null) { //if authentication is not null, we'll logically treat as caller identity if (authentication == null) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(baseUserName, credentials == null ? null : new String(credentials.getCredentialsAsCharArray())); try { authentication = authenticationManager.authenticate(token); } catch (AuthenticationException e) { throw new LoginException(e.getMessage()); } } baseUserName = authentication.getName(); } else { return null; } if (logger.isTraceEnabled()) { logger.trace("Logged in user: " + baseUserName); } return authentication; }
Example 3
Source File: CustomFailureHandler.java From Spring-5.0-Cookbook with MIT License | 6 votes |
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { System.out.println("failure"); String targetUrl = ""; if(exception instanceof BadCredentialsException){ targetUrl = "/login.html?error=" + exception.getMessage(); } else { targetUrl = "/login.html?error=" + true; } if (response.isCommitted()) { System.out.println("Internal problem in redirection"); return; } redirectStrategy.sendRedirect(request, response, targetUrl); }
Example 4
Source File: AjaxAuthenticationFailureHandler.java From ankush with GNU Lesser General Public License v3.0 | 6 votes |
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) { String problemDescription = "InvalidCredentials"; if (exception != null) { String msg = exception.getMessage(); if (msg != null) { if (msg.equals("User is disabled")) problemDescription = "AccountDisabled"; } } response.setContentType("application/json"); response.getWriter().print("{\"success\":false, \"reason\":\"" + problemDescription +"\"}"); response.getWriter().flush(); } else { super.onAuthenticationFailure(request, response, exception); } }
Example 5
Source File: CustomFailureHandler.java From Spring-5.0-Cookbook with MIT License | 6 votes |
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { System.out.println("failure"); String targetUrl = ""; if(exception instanceof BadCredentialsException){ targetUrl = "/login.html?error=" + exception.getMessage(); } else { targetUrl = "/login.html?error=" + true; } if (response.isCommitted()) { System.out.println("Internal problem in redirection"); return; } redirectStrategy.sendRedirect(request, response, targetUrl); }
Example 6
Source File: AjaxAuthenticationFailureHandler.java From albedo with GNU Lesser General Public License v3.0 | 6 votes |
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { String useruame = request.getParameter("username"); LoginUtil.isValidateCodeLogin(useruame, true, false); String message = exception instanceof BadCredentialsException && "Bad credentials".equals(exception.getMessage()) ? "密码填写错误!" : exception.getMessage(); LogOperate logOperate = SysLogUtils.getSysLog(); logOperate.setParams(HttpUtil.toParams(request.getParameterMap())); logOperate.setUsername(useruame); try { UserDetail userDetails = (UserDetail) userDetailsService.loadUserByUsername(useruame); if (userDetails != null) { logOperate.setCreatedBy(userDetails.getId()); } } catch (Exception e) { } logOperate.setLogType(LogType.WARN.name()); logOperate.setTitle("用户登录失败"); logOperate.setDescription(message); logOperate.setException(ExceptionUtil.stacktraceToString(exception)); AsyncUtil.recordLogLogin(logOperate); response.setStatus(HttpServletResponse.SC_OK); WebUtil.renderJson(response, Result.buildFail(message)); }
Example 7
Source File: AjaxAuthenticationHandler.java From onetwo with Apache License 2.0 | 6 votes |
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { logger.error("login error", exception); if(RequestUtils.isAjaxRequest(request)){ String msg = exception.getMessage(); /*if(BadCredentialsException.class.isInstance(exception)){ msg = "用户密码不匹配!"; }*/ SimpleResultBuilder<?> builder = DataResults.error("验证失败:"+msg); String errorCode = SecurityErrors.AUTH_FAILED.name(); if (exception instanceof ExceptionCodeMark) { errorCode = ((ExceptionCodeMark)exception).getCode(); } DataResult<?> rs = buildErrorCode(builder, request, exception) .code(errorCode) .build(); String text = mapper.toJson(rs); ResponseUtils.render(response, text, ResponseUtils.JSON_TYPE, true); }else{ this.failureHandler.onAuthenticationFailure(request, response, exception); } }
Example 8
Source File: KerberosProvider.java From localization_nifi with Apache License 2.0 | 6 votes |
@Override public final AuthenticationResponse authenticate(final LoginCredentials credentials) throws InvalidLoginCredentialsException, IdentityAccessException { if (provider == null) { throw new IdentityAccessException("The Kerberos authentication provider is not initialized."); } try { // Perform the authentication final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword()); logger.debug("Created authentication token for principal {} with name {} and is authenticated {}", token.getPrincipal(), token.getName(), token.isAuthenticated()); final Authentication authentication = provider.authenticate(token); logger.debug("Ran provider.authenticate() and returned authentication for " + "principal {} with name {} and is authenticated {}", authentication.getPrincipal(), authentication.getName(), authentication.isAuthenticated()); return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer); } catch (final AuthenticationException e) { throw new InvalidLoginCredentialsException(e.getMessage(), e); } }
Example 9
Source File: FebsAuthenticationFailureHandler.java From FEBS-Security with Apache License 2.0 | 6 votes |
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException { String message; if (exception instanceof UsernameNotFoundException) { message = "用户不存在!"; } else if (exception instanceof BadCredentialsException) { message = "用户名或密码错误!"; } else if (exception instanceof LockedException) { message = "用户已被锁定!"; } else if (exception instanceof DisabledException) { message = "用户不可用!"; } else if (exception instanceof AccountExpiredException) { message = "账户已过期!"; } else if (exception instanceof CredentialsExpiredException) { message = "用户密码已过期!"; } else if (exception instanceof ValidateCodeException || exception instanceof FebsCredentialExcetion) { message = exception.getMessage(); } else { message = "认证失败,请联系网站管理员!"; } response.setContentType(FebsConstant.JSON_UTF8); response.getWriter().write(mapper.writeValueAsString(ResponseBo.error(message))); }
Example 10
Source File: LoginFailHandler.java From WeBASE-Node-Manager with Apache License 2.0 | 5 votes |
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException { log.info("login fail", ex); String errorMsg = ex.getMessage(); RetCode retCode = ConstantCode.PASSWORD_ERROR; // default password fail if (errorMsg.contains("code")) { retCode = JsonTools.toJavaObject(errorMsg, RetCode.class); } BaseResponse baseResponse = new BaseResponse(retCode); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(JsonTools.toJSONString(baseResponse)); }
Example 11
Source File: SecurityContextVarsInitializer.java From bdf3 with Apache License 2.0 | 5 votes |
@Override public void initializeContext(Map<String, Object> vars) throws Exception { vars.put("loginUsername", ContextUtils.getLoginUsername()); vars.put("loginUser", ContextUtils.getLoginUser()); AuthenticationException ex = (AuthenticationException) DoradoContext.getAttachedRequest().getSession() .getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); String errorMsg = ex != null ? ex.getMessage() : "none"; vars.put("authenticationErrorMsg", errorMsg); }
Example 12
Source File: DefaultController.java From oauth2-protocol-patterns with Apache License 2.0 | 5 votes |
@GetMapping(path = "/login", params = "error") public String loginError(@SessionAttribute(WebAttributes.AUTHENTICATION_EXCEPTION) AuthenticationException authEx, Map<String, Object> model) { String errorMessage = authEx != null ? authEx.getMessage() : "[unknown error]"; model.put("errorMessage", errorMessage); return "error"; }
Example 13
Source File: LoginController.java From blog-sample with Apache License 2.0 | 5 votes |
@RequestMapping("/login/error") @ResponseBody public Msg<?> loginError(HttpServletRequest request) { AuthenticationException exception = (AuthenticationException)request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION"); return new Msg<>(false, exception.getMessage(), exception.toString()); }
Example 14
Source File: LoginUserController.java From coderadar with MIT License | 5 votes |
@PostMapping( path = "/user/auth", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity login(@RequestBody @Validated LoginUserCommand command) { try { return new ResponseEntity<>(loginUserUseCase.login(command), HttpStatus.OK); } catch (AuthenticationException e) { return new ResponseEntity<>(new ErrorMessageResponse(e.getMessage()), HttpStatus.FORBIDDEN); } }
Example 15
Source File: SecurityHandlerConfig.java From open-capacity-platform with Apache License 2.0 | 5 votes |
/** * 登陆失败 * * @return */ @Bean public AuthenticationFailureHandler loginFailureHandler() { return new AuthenticationFailureHandler() { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { String msg = null; if (exception instanceof BadCredentialsException) { msg = "密码错误"; } else { msg = exception.getMessage(); } Map<String, String> rsp = new HashMap<>(); response.setStatus(HttpStatus.UNAUTHORIZED.value()); rsp.put("resp_code", HttpStatus.UNAUTHORIZED.value() + ""); rsp.put("rsp_msg", msg); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(objectMapper.writeValueAsString(rsp)); response.getWriter().flush(); response.getWriter().close(); } }; }
Example 16
Source File: SecurityHandlerConfig.java From open-capacity-platform with Apache License 2.0 | 5 votes |
/** * 登陆失败 * * @return */ @Bean public AuthenticationFailureHandler loginFailureHandler() { return new AuthenticationFailureHandler() { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { String msg = null; if (exception instanceof BadCredentialsException) { msg = "密码错误"; } else { msg = exception.getMessage(); } Map<String, String> rsp = new HashMap<>(); response.setStatus(HttpStatus.UNAUTHORIZED.value()); rsp.put("resp_code", HttpStatus.UNAUTHORIZED.value() + ""); rsp.put("rsp_msg", msg); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(objectMapper.writeValueAsString(rsp)); response.getWriter().flush(); response.getWriter().close(); } }; }
Example 17
Source File: LDAuthenticationFailureHandler.java From document-management-software with GNU Lesser General Public License v3.0 | 4 votes |
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { StringBuffer failureUrl = new StringBuffer(request.getContextPath()); failureUrl.append("/"); if (request.getParameter(PARAM_FAILUREURL) != null) failureUrl.append(request.getParameter(PARAM_FAILUREURL)); if (failureUrl.toString().indexOf('?') != -1) failureUrl.append("&"); else failureUrl.append("?"); failureUrl.append("failure="); String failureReason = exception.getMessage(); /* * Mask the not found as a wrong password, in order to avoid * vulnerability "Username Enumeration Weakness"<br> * https://www.zeroscience.mk/en/vulnerabilities/ZSL-2018-5451.php */ if (AccountNotFoundException.CODE.equals(failureReason)) failureReason = WrongPasswordException.CODE; failureUrl.append(failureReason); try { Cookie failureCookie = new Cookie(COOKIE_LDOC_FAILURE, failureReason); failureCookie.setMaxAge(10); response.addCookie(failureCookie); } catch (Throwable t) { } String username = request.getParameter("j_username"); log.warn("Authentication of {} was unsuccesful due to {}", username, failureReason); String normalizedFailureUrl = failureUrl.toString().replace("//", "/"); if (normalizedFailureUrl.startsWith("/")) normalizedFailureUrl = normalizedFailureUrl.substring(1); log.info("Redirecting to {}", normalizedFailureUrl.toString()); response.sendRedirect(failureUrl.toString()); }
Example 18
Source File: AccoutJwtResource.java From albedo with GNU Lesser General Public License v3.0 | 4 votes |
/** * 功能描述: 认证授权 */ @AnonymousAccess @PostMapping(SecurityConstants.AUTHENTICATE_URL) @ApiOperation("认证授权") public ResponseEntity authorize(@Valid @RequestBody LoginVo loginVo) { Date canLoginDate = RedisUtil.getCacheObject(SecurityConstants.DEFAULT_LOGIN_AFTER_24_KEY + loginVo.getUsername()); if (canLoginDate != null) { return ResponseEntityBuilder.buildFail(HttpStatus.UNAUTHORIZED, "您的账号在" + DateUtil.format(canLoginDate) + "后才可登录"); } if (!SpringContextHolder.isDevelopment()) { LoginUtil.checkCode(loginVo); } try { String s = PasswordDecoderFilter.decryptAes(loginVo.getPassword(), applicationProperties.getSecurity().getEncodeKey()); loginVo.setPassword(s.trim()); } catch (Exception e) { } UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVo.getUsername(), loginVo.getPassword()); String keyLoginCount = SecurityConstants.DEFAULT_LOGIN_KEY + loginVo.getUsername(); try { Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); boolean rememberMe = (loginVo.getRememberMe() == null) ? false : loginVo.getRememberMe(); String jwt = tokenProvider.createToken(authentication, rememberMe); log.info("jwt:{}", jwt); RedisUtil.delete(keyLoginCount); return ResponseEntityBuilder.buildOkData(new LinkedHashMap<String, Object>() {{ put("access_token", jwt); put("expires_in", tokenProvider.getExpirationDateSecondsFromToken(jwt)); }}); } catch (AuthenticationException ae) { log.warn("Authentication exception trace: {}", ae); String msg = ae.getMessage(); if (ae instanceof BadCredentialsException) { Integer cacheObject = RedisUtil.getCacheObject(keyLoginCount); if (cacheObject == null) { cacheObject = 1; } msg = "密码错误,请重试"; boolean level1 = cacheObject >= 5 && cacheObject < 9; boolean level2 = cacheObject == 9; boolean level3 = cacheObject > 9; if (level1) { msg = "您还剩" + (10 - cacheObject) + "次密码输入机会,建议点击‘忘记密码’"; } else if (level2) { msg = "您还剩1次密码输入机会,再次错误,您的账号将被暂时锁定24小时,24小时内禁止登录"; } else if (level3) { msg = "您密码错误次数已超过10次,您的账号将被暂时锁定24小时,建议点击‘忘记密码’,凭手机号码重置密码,24小时后再尝试登录"; cacheObject = 0; // RedisUtil.setCacheObject(SecurityConstants.DEFAULT_LOGIN_AFTER_24_KEY +loginVo.getUsername(), DateUtil.addDays(PublicUtil.getCurrentDate(), 1), 1, TimeUnit.DAYS); } RedisUtil.setCacheObject(keyLoginCount, 1 + cacheObject); } return ResponseEntityBuilder.buildFail(HttpStatus.UNAUTHORIZED, msg); } }
Example 19
Source File: KerberosIdentityProvider.java From nifi-registry with Apache License 2.0 | 4 votes |
@Override public AuthenticationResponse authenticate(AuthenticationRequest authenticationRequest) throws InvalidCredentialsException, IdentityAccessException { if (provider == null) { throw new IdentityAccessException("The Kerberos authentication provider is not initialized."); } try { final String rawPrincipal = authenticationRequest.getUsername(); final Object credentials = authenticationRequest.getCredentials(); final String parsedRealm = KerberosPrincipalParser.getRealm(rawPrincipal); // Apply default realm from KerberosIdentityProvider's configuration specified in identity-providers.xml if a principal without a realm was given // Otherwise, the default realm configured from the krb5 configuration specified in the nifi.registry.kerberos.krb5.file property will end up being used boolean realmInRawPrincipal = StringUtils.isNotBlank(parsedRealm); final String identity; if (realmInRawPrincipal) { // there's a realm already in the given principal, use it identity = rawPrincipal; logger.debug("Realm was specified in principal {}, default realm was not added to the identity being authenticated", rawPrincipal); } else if (StringUtils.isNotBlank(defaultRealm)) { // the value for the default realm is not blank, append the realm to the given principal identity = StringUtils.joinWith("@", rawPrincipal, defaultRealm); logger.debug("Realm was not specified in principal {}, default realm {} was added to the identity being authenticated", rawPrincipal, defaultRealm); } else { // otherwise, use the given principal, which will use the default realm as specified in the krb5 configuration identity = rawPrincipal; logger.debug("Realm was not specified in principal {}, default realm is blank and was not added to the identity being authenticated", rawPrincipal); } // perform the authentication final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(identity, credentials); if (logger.isDebugEnabled()) { logger.debug("Created authentication token " + token.toString()); } final Authentication authentication = provider.authenticate(token); if (logger.isDebugEnabled()) { logger.debug("Ran provider.authenticate(token) and returned authentication for " + "principal={} with name={} and isAuthenticated={}", authentication.getPrincipal(), authentication.getName(), authentication.isAuthenticated()); } return new AuthenticationResponse(authentication.getName(), identity, expiration, issuer); } catch (final AuthenticationException e) { throw new InvalidCredentialsException(e.getMessage(), e); } }
Example 20
Source File: RangerAuthFailureHandler.java From ranger with Apache License 2.0 | 4 votes |
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { String ajaxRequestHeader = request.getHeader("X-Requested-With"); if (logger.isDebugEnabled()) { logger.debug("commence() X-Requested-With=" + ajaxRequestHeader); } response.setContentType("application/json;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("X-Frame-Options", "DENY"); String jsonResp = ""; try { String msg = exception.getMessage(); VXResponse vXResponse = new VXResponse(); if (msg != null && !msg.isEmpty()) { if (CLIUtil.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",request).equalsIgnoreCase(msg)) { vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("The username or password you entered is incorrect."); logger.info("Error Message : " + msg); } else if (msg.contains("Could not get JDBC Connection; nested exception is java.sql.SQLException: Connections could not be acquired from the underlying database!")) { vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Unable to connect to DB."); } else if (msg.contains("Communications link failure")) { vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Unable to connect to DB."); } else if (CLIUtil.getMessage("AbstractUserDetailsAuthenticationProvider.disabled",request).equalsIgnoreCase(msg)) { vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("The username or password you entered is disabled."); } } jsonResp = jsonUtil.writeObjectAsString(vXResponse); response.getWriter().write(jsonResp); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } catch (IOException e) { logger.info("Error while writing JSON in HttpServletResponse"); } if (ajaxRequestHeader != null && "XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) { // if (logger.isDebugEnabled()) { // logger.debug("Forwarding AJAX login request failure to " // + ajaxLoginfailurePage); // } // request.getRequestDispatcher(ajaxLoginfailurePage).forward(request, // response); if (logger.isDebugEnabled()) { logger.debug("Sending login failed response : " + jsonResp); } }// else { // super.onAuthenticationFailure(request, response, exception); //} }