org.springframework.security.core.AuthenticationException Java Examples
The following examples show how to use
org.springframework.security.core.AuthenticationException.
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: ResourceServerConfiguration.java From spring-security with Apache License 2.0 | 8 votes |
@Bean public AuthenticationEntryPoint authenticationEntryPoint(){ return (HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) ->{ Map<String, Object> map = new HashMap<>(); map.put("code", 401); map.put("msg", "非法访问资源,访问此资源需要完全身份验证"); map.put("path", request.getServletPath()); map.put("timestamp", System.currentTimeMillis()); response.setContentType("application/json"); response.setCharacterEncoding(CharsetUtil.UTF_8); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getOutputStream(), map); } catch (Exception e) { throw new ServletException(); } }; }
Example #2
Source File: JwtAuthenticationFailHandler.java From Spring-Boot-Book with Apache License 2.0 | 8 votes |
@Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException, IOException { httpServletRequest.setCharacterEncoding("UTF-8"); // 获得用户名密码 String username = httpServletRequest.getParameter("uname"); String password = httpServletRequest.getParameter("pwd"); MemberLoginLog loginRecord = new MemberLoginLog(); loginRecord.setLoginip(IpUtils.getIpAddr(httpServletRequest)); loginRecord.setLogintime(System.currentTimeMillis()); loginRecord.setUsername(username); loginRecord.setStates(0); loginRecord.setWay(2); memberLoginLogRepository.save(loginRecord); httpServletResponse.setContentType("application/json;charset=utf-8"); PrintWriter out = httpServletResponse.getWriter(); out.write("{\"status\":\"error\",\"message\":\"用户名或密码错误\"}"); out.flush(); out.close(); }
Example #3
Source File: AjaxLoginProcessingFilter.java From springboot-security-jwt with MIT License | 8 votes |
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!HttpMethod.POST.name().equals(request.getMethod()) || !WebUtil.isAjax(request)) { if(logger.isDebugEnabled()) { logger.debug("Authentication method not supported. Request method: " + request.getMethod()); } throw new AuthMethodNotSupportedException("Authentication method not supported"); } LoginRequest loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class); if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) { throw new AuthenticationServiceException("Username or Password not provided"); } UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()); return this.getAuthenticationManager().authenticate(token); }
Example #4
Source File: AAAUserAuthenticationProvider.java From spring4-rest-oauth2 with GNU General Public License v2.0 | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String user=authentication.getPrincipal().toString(); String pwd=authentication.getCredentials().toString(); //PUT Auth Bean here boolean result=user.equals("myuser") && pwd.equals("mypassword"); //= aaaProxy.isValidUser(authentication.getPrincipal() //.toString(), authentication.getCredentials().toString()); if (result) { List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); AAAUserAuthenticationToken auth = new AAAUserAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities); return auth; } else { throw new BadCredentialsException("Bad User Credentials."); } }
Example #5
Source File: CustomAuthenticationProvider.java From pivotal-bank-demo with Apache License 2.0 | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); AuthenticationRequest request = new AuthenticationRequest(); request.setUsername(name); request.setPassword(password); try { Map<String, Object> params = service.login(request); if (params != null) { List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority("USER")); Authentication auth = new UsernamePasswordAuthenticationToken( name, password, grantedAuths); return auth; } else { throw new BadCredentialsException("Username not found"); } } catch (HttpServerErrorException e) { throw new BadCredentialsException("Login failed!"); } }
Example #6
Source File: AbstractSecureContentFilter.java From api-layer with Eclipse Public License 2.0 | 6 votes |
/** * Extracts the token from the request and use the authentication manager to perform authentication. * Then set the currently authenticated principal and call the next filter in the chain. * * @param request the http request * @param response the http response * @param filterChain the filter chain * @throws ServletException a general exception * @throws IOException a IO exception */ @Override protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { Optional<AbstractAuthenticationToken> authenticationToken = extractContent(request); if (authenticationToken.isPresent()) { try { Authentication authentication = authenticationManager.authenticate(authenticationToken.get()); SecurityContextHolder.getContext().setAuthentication(authentication); filterChain.doFilter(request, response); } catch (AuthenticationException authenticationException) { failureHandler.onAuthenticationFailure(request, response, authenticationException); } catch (RuntimeException e) { resourceAccessExceptionHandler.handleException(request, response, e); } } else { filterChain.doFilter(request, response); } }
Example #7
Source File: DefaultAuthenticationProvider.java From lemon with Apache License 2.0 | 6 votes |
@SuppressWarnings("deprecation") protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { String username = userDetails.getUsername(); String presentedPassword = authentication.getCredentials().toString(); String tenantId = tenantHolder.getTenantId(); String result = authnClient.authenticate(username, presentedPassword, tenantId); boolean isValid = AccountStatus.SUCCESS.equals(result); if (!isValid) { logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails); } }
Example #8
Source File: AbstractJWTFilter.java From ambari-logsearch with Apache License 2.0 | 6 votes |
@Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { super.unsuccessfulAuthentication(request, response, failed); String ajaxRequestHeader = request.getHeader("X-Requested-With"); String loginUrl = constructLoginURL(request); if (loginUrl.endsWith("?doAs=anonymous")) { // HACK! - use proper solution, investigate which filter changes ? to & loginUrl = StringUtils.removeEnd(loginUrl, "?doAs=anonymous"); } if (!isWebUserAgent(request.getHeader("User-Agent")) || "XMLHttpRequest".equals(ajaxRequestHeader)) { Map<String, String> mapObj = new HashMap<>(); mapObj.put("knoxssoredirectURL", URLEncoder.encode(loginUrl, "UTF-8")); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, new Gson().toJson(mapObj)); } else { response.sendRedirect(loginUrl); } }
Example #9
Source File: CustomAuthenticationProvider.java From cf-SpringBootTrader with Apache License 2.0 | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); AuthenticationRequest request = new AuthenticationRequest(); request.setUsername(name); request.setPassword(password); try { Map<String, Object> params = service.login(request); if (params != null) { List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority("USER")); Authentication auth = new UsernamePasswordAuthenticationToken( name, password, grantedAuths); return auth; } else { throw new BadCredentialsException("Username not found"); } } catch (HttpServerErrorException e) { throw new BadCredentialsException("Login failed!"); } }
Example #10
Source File: CalendarUserAuthenticationProvider.java From Spring-Security-Third-Edition with MIT License | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String email = token.getName(); CalendarUser user = email == null ? null : calendarService.findUserByEmail(email); if(user == null) { throw new UsernameNotFoundException("Invalid username/password"); } // Database Password already encrypted: String password = user.getPassword(); boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password); if(!passwordsMatch) { throw new BadCredentialsException("Invalid username/password"); } Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities); logger.info("CalendarUser ({}), successfully authenticated", user.getEmail()); return usernamePasswordAuthenticationToken; }
Example #11
Source File: X509CertificateAuthenticationProvider.java From grpc-spring-boot-starter with MIT License | 6 votes |
@Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { if (!(authentication instanceof X509CertificateAuthentication)) { throw new IllegalArgumentException("Unsupported authentication type: " + authentication.getClass().getName() + ". Only X509CertificateAuthentication is supported!"); } final X509CertificateAuthentication auth = (X509CertificateAuthentication) authentication; final String username = this.usernameExtractor.apply(auth); if (username == null) { log.debug("Could not find username"); throw new UsernameNotFoundException("No username provided"); } final UserDetails user = this.userDetailsService.loadUserByUsername(username); if (user == null) { log.debug("Could not find user '{}'", username); throw new UsernameNotFoundException("Unknown username: " + username); } log.debug("Authenticated as '{}'", username); return new X509CertificateAuthentication(user, auth.getCredentials(), user.getAuthorities()); }
Example #12
Source File: SessionExpireEntryPoint.java From dubbo-postman with MIT License | 6 votes |
/** * 在cas授权失败的时候会进入这个方法 * @param request * @param response * @param authException * @throws IOException * @throws ServletException */ @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { //判断请求类型是否是ajax if(request.getHeader(AJAX_TYPE) != null || request.getParameter(AJAX_TYPE)!=null){ //设置过期标识,让前端js进行处理 response.setHeader(AJAX_HEADER,"time-out"); try { //直接返回错误信息,前端js进行拦截 response.sendError(HttpServletResponse.SC_OK,"session已经过期"); } catch (IOException e) { } }else{ casAuthenticationEntryPoint.commence(request,response,authException); } }
Example #13
Source File: NiFiAuthenticationFilter.java From localization_nifi with Apache License 2.0 | 6 votes |
private void authenticate(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException { String dnChain = null; try { final Authentication authenticationRequest = attemptAuthentication(request); if (authenticationRequest != null) { // log the request attempt - response details will be logged later log.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", authenticationRequest.toString(), request.getMethod(), request.getRequestURL().toString(), request.getRemoteAddr())); // attempt to authorize the user final Authentication authenticated = authenticationManager.authenticate(authenticationRequest); successfulAuthorization(request, response, authenticated); } // continue chain.doFilter(request, response); } catch (final AuthenticationException ae) { // invalid authentication - always error out unsuccessfulAuthorization(request, response, ae); } }
Example #14
Source File: CustomAuthenticationProvider.java From hauth-java with MIT License | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // 获取认证的用户名 & 密码 String name = authentication.getName(); Object pd = authentication.getCredentials(); if (pd == null) { return new UsernamePasswordAuthenticationToken(name, "", new ArrayList<>()); } String password = pd.toString(); UserLoginEntity userLoginEntity = loginService.loginValidator(name, password); // 认证逻辑 if (userLoginEntity.isFlag()) { return getRole(name, password); } else { logger.info("登录失败,原因是:账号 {}: {}", userLoginEntity.getUsername(), userLoginEntity.getMessage()); throw new BadCredentialsException(new GsonBuilder().create().toJson(userLoginEntity)); } }
Example #15
Source File: OpenIDAuthenticationFailureHandler.java From attic-rave with Apache License 2.0 | 6 votes |
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if(exception instanceof UsernameNotFoundException && exception.getAuthentication() instanceof OpenIDAuthenticationToken && ((OpenIDAuthenticationToken)exception.getAuthentication()).getStatus().equals(OpenIDAuthenticationStatus.SUCCESS)) { OpenIDAuthenticationToken token = (OpenIDAuthenticationToken)exception.getAuthentication(); String url = token.getIdentityUrl(); User user = createTemporaryUser(token, url); request.getSession(true).setAttribute(ModelKeys.NEW_USER, user); DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); log.info("Redirecting to new user account creation page"); super.setRedirectStrategy(redirectStrategy); redirectStrategy.sendRedirect(request, response, "/"+ViewNames.CREATE_ACCOUNT_PAGE); return; } else { super.onAuthenticationFailure(request, response, exception); } }
Example #16
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 #17
Source File: CustomUsernamePasswordAuthenticationFilter.java From maintain with MIT License | 6 votes |
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (!request.getMethod().equals("POST")) throw new AuthenticationServiceException((new StringBuilder()) .append("Authentication method not supported: ").append(request.getMethod()).toString()); String username = obtainUsername(request); String password = obtainPassword(request); if (username == null) username = ""; if (password == null) password = ""; username = username.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); setDetails(request, authRequest); return getAuthenticationManager().authenticate(authRequest); }
Example #18
Source File: CalendarUserAuthenticationProvider.java From Spring-Security-Third-Edition with MIT License | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String email = token.getName(); CalendarUser user = email == null ? null : calendarService.findUserByEmail(email); if(user == null) { throw new UsernameNotFoundException("Invalid username/password"); } // Database Password already encrypted: String password = user.getPassword(); boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password); if(!passwordsMatch) { throw new BadCredentialsException("Invalid username/password"); } Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities); return usernamePasswordAuthenticationToken; }
Example #19
Source File: AuthenticationRestController.java From tour-of-heros-api-security-zerhusen with MIT License | 6 votes |
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST) public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException { // Perform the security final Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( authenticationRequest.getUsername(), authenticationRequest.getPassword() ) ); SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-security so we can generate token final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); final String token = jwtTokenUtil.generateToken(userDetails, device); // Return the token return ResponseEntity.ok(new JwtAuthenticationResponse(token)); }
Example #20
Source File: JWTAuthenticationProvider.java From airsonic with GNU General Public License v3.0 | 6 votes |
@Override public Authentication authenticate(Authentication auth) throws AuthenticationException { JWTAuthenticationToken authentication = (JWTAuthenticationToken) auth; if (authentication.getCredentials() == null || !(authentication.getCredentials() instanceof String)) { LOG.error("Credentials not present"); return null; } String rawToken = (String) auth.getCredentials(); DecodedJWT token = JWTSecurityService.verify(jwtKey, rawToken); Claim path = token.getClaim(JWTSecurityService.CLAIM_PATH); authentication.setAuthenticated(true); // TODO:AD This is super unfortunate, but not sure there is a better way when using JSP if (StringUtils.contains(authentication.getRequestedPath(), "/WEB-INF/jsp/")) { LOG.warn("BYPASSING AUTH FOR WEB-INF page"); } else if (!roughlyEqual(path.asString(), authentication.getRequestedPath())) { throw new InsufficientAuthenticationException("Credentials not valid for path " + authentication .getRequestedPath() + ". They are valid for " + path.asString()); } List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("IS_AUTHENTICATED_FULLY")); authorities.add(new SimpleGrantedAuthority("ROLE_TEMP")); return new JWTAuthenticationToken(authorities, rawToken, authentication.getRequestedPath()); }
Example #21
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 #22
Source File: JWTLoginFilter.java From batch-scheduler with MIT License | 6 votes |
@Override public Authentication attemptAuthentication( HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException { String username = req.getParameter("username"); String password = req.getParameter("password"); if (password != null) { password = CryptoAES.getInstance().aesEncrypt(password); } // 返回一个验证令牌 return getAuthenticationManager().authenticate( new UsernamePasswordAuthenticationToken( username, password ) ); }
Example #23
Source File: SmsCodeAuthenticationProvider.java From codeway_service with GNU General Public License v3.0 | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication; String phone = (String) authenticationToken.getPrincipal(); User user = new User(); user.setPhone(phone); UserDetails userInfo = userDetailsService.loadUserByUsername(JsonUtil.toJsonString(user)); if (userInfo == null) { throw new ValidateCodeException("手机号不存在!"); } SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userInfo, userInfo.getAuthorities()); authenticationResult.setDetails(authenticationToken.getDetails()); return authenticationResult; }
Example #24
Source File: DatabaseAuthenticationProvider.java From WebApplication-Project-Skeleton with MIT License | 6 votes |
@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { log.info("retrieveUser, for username={}", username); if (StringUtils.isEmpty(username)) { setHideUserNotFoundExceptions(false);//Setting this will cause UsernameNotFoundExceptions to be thrown instead of BadCredentialsException throw new UsernameNotFoundException("Enter your username."); } User user = userService.findUserByUsername(username); String givenPassword = (String) authentication.getCredentials(); if (user == null || !user.getPassword().equals(givenPassword)) { throw new BadCredentialsException("Incorrect username or password."); } return user; }
Example #25
Source File: SimpleHashUtil.java From Roothub with GNU Affero General Public License v3.0 | 6 votes |
/** * 这个方法很重要,用于认证用户提供的信息是否正确, * 并且返回一个 UserDetails 对象,父类的 authenticate() 方法会用到这个对象 */ @Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { // 调用认证服务接口,加载 UserDetails 对象 UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (userDetails == null) { throw new UsernameNotFoundException(username); } // 判断用户名和密码是否正确,如果正确直接返回 if (userDetails.getUsername().equals(authentication.getPrincipal().toString()) && passwordEncoder.isPasswordValid(userDetails.getPassword(), authentication.getCredentials().toString(), null)) { return userDetails; } throw new BadCredentialsException("username: " + username + ", credentials: " + authentication.getCredentials()); }
Example #26
Source File: UserInfoAuthenticationFilter.java From ChengFeng1.5 with MIT License | 6 votes |
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String username=request.getParameter("nickname"); String password=request.getParameter("password"); if (username == null) username = ""; if (password == null) password = ""; username = username.trim(); //封装到token中提交 UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( username, password); return this.getAuthenticationManager().authenticate(authRequest); }
Example #27
Source File: CustomUserDetailsAuthenticationProvider.java From tutorials with MIT License | 6 votes |
@Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } String presentedPassword = authentication.getCredentials() .toString(); if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } }
Example #28
Source File: RestAuthenticationEntryPoint.java From mall-swarm with Apache License 2.0 | 5 votes |
@Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Cache-Control","no-cache"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage()))); response.getWriter().flush(); }
Example #29
Source File: UserJWTControllerTest.java From flair-registry with Apache License 2.0 | 5 votes |
@Test public void authenticationException() throws Exception { // Authentication exception throws Mockito.doThrow(new AuthenticationException(null){}).when(tokenProvider) .createToken(Mockito.any(Authentication.class), Mockito.anyBoolean()); MvcResult res = mock.perform(post("/api/authenticate") .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL) .content("{\"username\":\"fakeUsername\",\"password\":\"fakePassword\",\"rememberMe\":false}")) .andExpect(status().isUnauthorized()) .andReturn(); assertTrue(res.getResponse().getContentAsString().startsWith("{\"AuthenticationException\"")); }
Example #30
Source File: BeihuDefaultAuthenticationEntryPoint.java From beihu-boot with Apache License 2.0 | 5 votes |
@Override public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException { logger.error("Unauthorized", e); // response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); // response.setStatus(HttpStatus.FORBIDDEN.value()); // // ApiBoot Result // ApiBootResult result = ApiBootResult.builder().errorMessage(HttpStatus.UNAUTHORIZED.getReasonPhrase()).errorCode(String.valueOf(HttpStatus.UNAUTHORIZED.value())).build(); // // return json // response.getWriter().write(new ObjectMapper().writeValueAsString(result)); throw new ServiceException(BasicServiceCode.UNAUTHORIZED); }