Java Code Examples for org.springframework.security.core.AuthenticationException

The following examples show how to use org.springframework.security.core.AuthenticationException. These examples are extracted from open source projects. 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
@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
@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 Project: Spring-Boot-Blog   Source File: MyAuthenticationProvider.java    License: MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    User user = null;
    try {
        user = userSrv.findByUserLogin(username);
    } catch (UserException e) {
        log.error("系统错误:"+e.getMessage());
        throw new BadCredentialsException("Username not found.");
    }
    if(user == null){
        throw new BadCredentialsException("Username not found.");
    }
    log.error("有人尝试登陆,用户名为:"+username+",密码为:"+password);
    //加密过程在这里体现
    if (!PassWordUtil.getMD5(password+user.getUserSalt()).equals(user.getUserPass()) ) {
        throw new BadCredentialsException("Wrong password.");
    }

    List<SimpleGrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("admin"));

    return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
 
Example 4
@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 5
@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 6
Source Project: lemon   Source File: DefaultAuthenticationProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
@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 8
@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 9
Source Project: Spring-5.0-Cookbook   Source File: CustomFailureHandler.java    License: MIT License 6 votes vote down vote up
@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 10
/**
 * 这个方法很重要,用于认证用户提供的信息是否正确,
 * 并且返回一个 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 11
Source Project: ChengFeng1.5   Source File: UserInfoAuthenticationFilter.java    License: MIT License 6 votes vote down vote up
@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 12
@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 13
@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 14
Source Project: batch-scheduler   Source File: JWTLoginFilter.java    License: MIT License 6 votes vote down vote up
@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 15
@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 16
@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 17
@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
@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 19
/**
 * 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 20
Source Project: ambari-logsearch   Source File: AbstractJWTFilter.java    License: Apache License 2.0 6 votes vote down vote up
@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 21
@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 22
Source Project: hauth-java   Source File: CustomAuthenticationProvider.java    License: MIT License 6 votes vote down vote up
@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 23
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 24
@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 25
@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 26
@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 27
@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 28
Source Project: dubbo-postman   Source File: SessionExpireEntryPoint.java    License: MIT License 6 votes vote down vote up
/**
 * 在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 29
@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 30
Source Project: taskana   Source File: WildflyWebSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public AuthenticationManager preAuthManager() {
  return new AuthenticationManager() {

    @Override
    public Authentication authenticate(Authentication authentication)
        throws AuthenticationException {
      return preauthAuthProvider().authenticate(authentication);
    }
  };
}