org.springframework.security.authentication.BadCredentialsException Java Examples

The following examples show how to use org.springframework.security.authentication.BadCredentialsException. 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: PhonePasswordTokenGranter.java    From spring-cloud-shop with MIT License 8 votes vote down vote up
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

    Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
    String username = parameters.get("phone");
    String password = parameters.get("password");
    // Protect from downstream leaks of password
    parameters.remove("password");

    Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
    ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
    try {
        userAuth = authenticationManager.authenticate(userAuth);
    } catch (AccountStatusException | BadCredentialsException ase) {
        //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
        throw new InvalidGrantException(ase.getMessage());
    } // If the username/password are wrong the spec says we should send 400/invalid grant

    if (userAuth == null || !userAuth.isAuthenticated()) {
        throw new InvalidGrantException("Could not authenticate user: " + username);
    }

    return new OAuth2Authentication(getRequestFactory().createOAuth2Request(client, tokenRequest), userAuth);
}
 
Example #2
Source File: MockAuthenticationManager.java    From tutorials with MIT License 8 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException
{

    UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getName());

    if(userDetails == null || !passwordEncoder.matches(authentication.getCredentials().toString(), userDetails.getPassword()))
    {
        throw new BadCredentialsException("Invalid username/password");
    }

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
        authentication.getPrincipal().toString(),
        authentication.getCredentials().toString(),
        ROLES);

    return token;
}
 
Example #3
Source File: SmsStaffServiceImpl.java    From HIS with Apache License 2.0 8 votes vote down vote up
@Override
public String login(String username, String password) {
    String token = null;
    //密码需要客户端加密后传递
    try {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);//返回的是一个userDetails的实现类AdminUserDetails
        if(!passwordEncoder.matches(password,userDetails.getPassword())){  //password是从前端过来未经过编译的,而userDetails.getPassword()是从数据库中出来经过编译的
            throw new BadCredentialsException("密码不正确");
        }
        //创建一个新的token
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);  //在securityContext中添加该验证信息
        token = jwtTokenUtil.generateToken(userDetails);
        //updateLoginTimeByUsername(username);
        //insertLoginLog(username);
    } catch (AuthenticationException e) {
        LOGGER.warn("登录异常:{}", e.getMessage());
    }
    return token;
}
 
Example #4
Source File: CalendarUserAuthenticationProvider.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@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 #5
Source File: WxAuthenticationProvider.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
@Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
      WxAuthenticationToken wxAuthenticationToken = (WxAuthenticationToken) authentication;
      // 微信的code
      String principal = wxAuthenticationToken.getPrincipal().toString();
      UserDetails userDetails = customUserDetailsService.loadUserByWxCodeAndTenantCode(principal, TenantContextHolder.getTenantCode(), wxAuthenticationToken.getWxUser());
      if (userDetails == null) {
          log.debug("Authentication failed: no credentials provided");
	SpringContextHolder.publishEvent(new CustomAuthenticationFailureEvent(authentication, userDetails));
	throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.noopBindAccount", "Noop Bind Account"));
      }
      WxAuthenticationToken authenticationToken = new WxAuthenticationToken(userDetails, userDetails.getAuthorities());
      authenticationToken.setDetails(wxAuthenticationToken.getDetails());
SpringContextHolder.publishEvent(new CustomAuthenticationSuccessEvent(authentication, userDetails));
return authenticationToken;
  }
 
Example #6
Source File: CustomLdapAuthenticationProvider.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
    
    boolean authenticated = identityService.checkPassword(authenticationToken.getName(), authenticationToken.getCredentials().toString());
    if (!authenticated) {
        throw new BadCredentialsException(messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    
    FlowableAppUser userDetails = (FlowableAppUser) userDetailsService.loadUserByUsername(authenticationToken.getName());
    
    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
            userDetails, authenticationToken.getCredentials(), 
            authoritiesMapper.mapAuthorities(userDetails.getAuthorities()));
    result.setDetails(authentication.getDetails());
    
    return result;
}
 
Example #7
Source File: UmsAdminServiceImpl.java    From mall-tiny with Apache License 2.0 6 votes vote down vote up
@Override
public String login(String username, String password) {
    String token = null;
    try {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        token = jwtTokenUtil.generateToken(userDetails);
    } catch (AuthenticationException e) {
        LOGGER.warn("登录异常:{}", e.getMessage());
    }
    return token;
}
 
Example #8
Source File: MobileAuthenticationProvider.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) {
    MobileAuthenticationToken authenticationToken = (MobileAuthenticationToken) authentication;
    String mobile = (String) authenticationToken.getPrincipal();
    String password = (String) authenticationToken.getCredentials();
    UserDetails user = userDetailsService.loadUserByMobile(mobile);
    if (user == null) {
        throw new InternalAuthenticationServiceException("手机号或密码错误");
    }
    if (!passwordEncoder.matches(password, user.getPassword())) {
        throw new BadCredentialsException("手机号或密码错误");
    }
    MobileAuthenticationToken authenticationResult = new MobileAuthenticationToken(user, password, user.getAuthorities());
    authenticationResult.setDetails(authenticationToken.getDetails());
    return authenticationResult;
}
 
Example #9
Source File: SocialSignOnEndpoint.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
public boolean socialSignOn(SocialsAssociate socialSignOnUserToken){
	
	socialSignOnUserToken=this.socialsAssociateService.get(socialSignOnUserToken);
	
	_logger.debug("callback SocialSignOn User Token : "+socialSignOnUserToken);
	if(null !=socialSignOnUserToken){

		_logger.debug("Social Sign On from "+socialSignOnUserToken.getProvider()+" mapping to user "+socialSignOnUserToken.getUsername());
		
		if(WebContext.setAuthentication(socialSignOnUserToken.getUsername(), ConstantsLoginType.SOCIALSIGNON,this.socialSignOnProvider.getProviderName(),"xe00000004","success")){
			//socialSignOnUserToken.setAccessToken(JsonUtils.object2Json(this.accessToken));
			socialSignOnUserToken.setSocialUserInfo(accountJsonString);
			//socialSignOnUserToken.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject()));
			
			this.socialsAssociateService.update(socialSignOnUserToken);
		}
		
	}else{
		WebContext.getRequest().getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new BadCredentialsException(WebContext.getI18nValue("login.error.social")));
	}
	return true;
}
 
Example #10
Source File: CalendarUserAuthenticationProvider.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@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 #11
Source File: JwtAuthenticationProvider.java    From fish-admin with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // 获取认证的用户名 & 密码
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    User user = userRepository.findByUserName(name);
    if (user == null) throw new UsernameNotFoundException("username not found!");
    if (!user.isEnable()) throw new AuthenticationException("user has been disabled!") {};
    // 认证逻辑
    if (user.validatePassword(password)) {

        // 这里设置权限和角色
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        // authorities.add( new GrantedAuthorityImpl("ROLE_ADMIN") );
        // authorities.add( new GrantedAuthorityImpl("AUTH_WRITE") );
        // 生成令牌
        Authentication auth = new UsernamePasswordAuthenticationToken(name, password, authorities);
        return auth;
    }else {
        throw new BadCredentialsException("密码错误~");
    }
}
 
Example #12
Source File: CustomAuthenticationProvider.java    From opscenter with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws BadCredentialsException {
    // 获取认证的用户名 & 密码
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    
    // 认证逻辑
    if (name.equals("admin") && password.equals("123456")) {
        // 这里设置权限和角色
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add( new GrantedAuthorityImpl("ROLE_ADMIN") );
        authorities.add( new GrantedAuthorityImpl("AUTH_WRITE") );
        
        authorities.add( new GrantedAuthorityImpl("AUTH_QUERY") );
        authorities.add( new GrantedAuthorityImpl("AUTH_GET") );
        authorities.add( new GrantedAuthorityImpl("AUTH_INSERT") );
        authorities.add( new GrantedAuthorityImpl("AUTH_UPDATE") );

        // 生成令牌
        Authentication auth = new UsernamePasswordAuthenticationToken(name, password, authorities);
        return auth;
    }else {
        throw new BadCredentialsException("密码错误~");
    }
}
 
Example #13
Source File: CustomAuthenticationProvider.java    From mall with Apache License 2.0 6 votes vote down vote up
@Log
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    // 用户输入的用户名
    String name = authentication.getName();

    // 用户输入的密码
    String password = authentication.getCredentials().toString();

    // 根据用户名查询用户信息
    UserDetails userDetails = getUserDetails(name);

    if (Objects.isNull(userDetails)) {
        throw new UsernameNotFoundException("用户不存在");
    }

    if (!bCryptPasswordEncoder.matches(password, userDetails.getPassword())) {
        throw new BadCredentialsException("密码错误");
    }
    return new UsernamePasswordAuthenticationToken(name, password, userDetails.getAuthorities());
}
 
Example #14
Source File: LogsearchSimpleAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationEmptyUser() {
  expect(mockAuthPropsConfig.isAuthSimpleEnabled()).andReturn(true);
  
  replay(mockAuthPropsConfig);
  
  Authentication authentication = new TestingAuthenticationToken("", "credentials");
  
  try {
    provider.authenticate(authentication);
    assertTrue("Should have thrown BadCredentialsException", false);
  } catch(BadCredentialsException e) {
    assertEquals("Username can't be null or empty.", e.getMessage());
  }
  
  verify(mockAuthPropsConfig);
}
 
Example #15
Source File: SmsSuccessHandler.java    From spring-security-oauth2-demo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 对请求头进行解密以及解析
 *
 * @param header 请求头
 * @return 客户端信息
 */
private String[] extractAndDecodeHeader(String header) {
    byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);
    byte[] decoded;
    try {
        decoded = Base64.getDecoder().decode(base64Token);
    } catch (IllegalArgumentException e) {
        throw new BadCredentialsException(
                "Failed to decode basic authentication token");
    }
    String token = new String(decoded, StandardCharsets.UTF_8);
    int delimiter = token.indexOf(":");

    if (delimiter == -1) {
        throw new BadCredentialsException("Invalid basic authentication token");
    }
    return new String[]{token.substring(0, delimiter), token.substring(delimiter + 1)};
}
 
Example #16
Source File: AuthExceptionHandler.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Entry method that takes care about the exception passed to it
 *
 * @param request  Http request
 * @param response Http response
 * @param ex       Exception to be handled
 * @throws ServletException Fallback exception if exception cannot be handled
 */
@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, RuntimeException ex) throws ServletException {
    if (ex instanceof InsufficientAuthenticationException) {
        handleAuthenticationRequired(request, response, ex);
    } else if (ex instanceof BadCredentialsException) {
        handleBadCredentials(request, response, ex);
    } else if (ex instanceof AuthenticationCredentialsNotFoundException) {
        handleAuthenticationCredentialsNotFound(request, response, ex);
    } else if (ex instanceof AuthMethodNotSupportedException) {
        handleAuthMethodNotSupported(request, response, ex);
    } else if (ex instanceof TokenNotValidException) {
        handleTokenNotValid(request, response, ex);
    } else if (ex instanceof TokenNotProvidedException) {
        handleTokenNotProvided(request, response, ex);
    } else if (ex instanceof TokenExpireException) {
        handleTokenExpire(request, response, ex);
    } else if (ex instanceof InvalidCertificateException) {
        handleInvalidCertificate(response, ex);
    } else if (ex instanceof AuthenticationException) {
        handleAuthenticationException(request, response, ex);
    } else {
        throw new ServletException(ex);
    }
}
 
Example #17
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 6 votes vote down vote up
@Test
public void shouldFailToAuthenticateUsingJWKIfMissingKeyIdClaim() throws Exception {
    Jwk jwk = mock(Jwk.class);
    JwkProvider jwkProvider = mock(JwkProvider.class);

    KeyPair keyPair = RSAKeyPair();
    when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
    when(jwk.getPublicKey()).thenReturn(keyPair.getPublic());
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
    String token = JWT.create()
            .withAudience("test-audience")
            .withIssuer("test-issuer")
            .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));

    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    exception.expect(BadCredentialsException.class);
    exception.expectMessage("No kid found in jwt");
    provider.authenticate(authentication);
}
 
Example #18
Source File: AuthenticationCheck.java    From ranger with Apache License 2.0 6 votes vote down vote up
private Authentication getADBindAuthentication(String ldapUrl, String bindDn, String bindPassword,
                                               String userName, String userPassword) {
    Authentication result = null;
    try {
        LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapUrl);
        ldapContextSource.setUserDn(bindDn);
        ldapContextSource.setPassword(bindPassword);
        ldapContextSource.setReferral("follow");
        ldapContextSource.setCacheEnvironmentProperties(true);
        ldapContextSource.setAnonymousReadOnly(false);
        ldapContextSource.setPooled(true);
        ldapContextSource.afterPropertiesSet();

        String searchFilter="(sAMAccountName={0})";
        FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(adDomain, searchFilter,ldapContextSource);
        userSearch.setSearchSubtree(true);

        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        bindAuthenticator.setUserSearch(userSearch);
        bindAuthenticator.afterPropertiesSet();

        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator);

        if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);

            result = ldapAuthenticationProvider.authenticate(finalAuthentication);
        }

    } catch (BadCredentialsException bce) {
        logFile.println("ERROR: LDAP Authentication Failed. Please verify values for ranger.admin.auth.sampleuser and " +
                "ranger.admin.auth.samplepassword\n");
    } catch (Exception e) {
        logFile.println("ERROR: LDAP Authentication Failed: " + e);
    }
    return result;
}
 
Example #19
Source File: CalendarUserAuthenticationProvider.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@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 #20
Source File: CompositeAuthenticationProvider.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null) {
        throw new BadCredentialsException("Bad credential:none authentication provided.");
    }

    if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
        throw new IllegalArgumentException("such authentication type doesnt supported");
    }

    UsernamePasswordAuthenticationToken authToken = (UsernamePasswordAuthenticationToken) authentication;

    String username = authToken.getName();
    if (username == null || username.trim().length() < 1) {
        log.debug("blank user name");
        throw new BadCredentialsException("Bad credential:blank username.");
    }

    return doAuthentication(username, authToken);
}
 
Example #21
Source File: CompositeAuthenticationProvider.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
protected void additionalAuthenticationChecks(SysUser user, UsernamePasswordAuthenticationToken authToken) {
    String authSource = user.getAuthSource();
    if(StringUtils.isBlank(authSource)){
        authSource = AuthContext.LOCAL_AUTH_SOURCE;
    }
    
    if(AuthContext.LOCAL_AUTH_SOURCE.equalsIgnoreCase(authSource)){
        checkAuthentication(user,authToken);
        return;
    }
    
    if(AuthContext.UM_AUTH_SOURCE.equalsIgnoreCase(authSource)){
        umAuthenticationChecker.checkAuthentication(user, authToken);
        return;
    }
    
    throw new BadCredentialsException("Unknown credential type.");
}
 
Example #22
Source File: CustomAuthenticationProvider.java    From hauth-java with 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
Source File: SmsCodeAuthenticationProvider.java    From Taroco with Apache License 2.0 6 votes vote down vote up
@Override
protected void additionalAuthenticationChecks(final UserDetails userDetails, final Authentication authentication) throws AuthenticationException {
    if (authentication.getCredentials() == null) {
        log.error("Authentication failed: no credentials provided");
        throw new BadCredentialsException(this.messages.getMessage("MobileAuthenticationProvider.badCredentials", "Bad credentials"));
    } else {
        final String presentedPassword = authentication.getCredentials().toString();
        final Object principal = authentication.getPrincipal();
        final String key = CacheConstants.DEFAULT_CODE_KEY + principal;
        final String code = redisRepository.get(key);
        // 校验验证码
        if (StrUtil.isEmpty(code) || !code.equals(presentedPassword)) {
            log.error("Authentication failed: verifyCode does not match stored value");
            throw new BadCredentialsException(this.messages.getMessage("MobileAuthenticationProvider.badCredentials", "Bad verifyCode"));
        }
        // 校验成功删除验证码(验证码只能使用一次)
        redisRepository.del(key);
    }
}
 
Example #24
Source File: SubSystemManagementService.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
private JwtToken tryAuthenticateSubSystem(SubSystemTokenDto subSystem) {
	String systemCode = subSystem.getSystemCode();
	SysSubSystemInfo subSystemInfo = subSystemInfoDataService.retrieveSysSubSystemInfoWithSystemCode(systemCode);
	if (subSystemInfo == null) {
		throw new BadCredentialsException(String.format("Sub system %s does not exist.", systemCode));
	}

	if (subSystemInfo.getBlocked() == true) {
		throw new BadCredentialsException(String.format("Sub system %s is blocked.", systemCode));
	}

	if (subSystemInfo.getActive() == false) {
		throw new BadCredentialsException(String.format("Sub system %s is inactive.", systemCode));
	}

	return doAuthenticateSubSystem(subSystem, subSystemInfo);
}
 
Example #25
Source File: SecurityWebExceptionResolver.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handlerMethod, Exception ex) {
	Throwable cause = org.springframework.security.core.AuthenticationException.class.isInstance(ex)?ex:ex.getCause();
	if(org.springframework.security.core.AuthenticationException.class.isInstance(cause)){
		throw (org.springframework.security.core.AuthenticationException)cause;
	}
	
	if(ex instanceof AuthenticationException){
		if(authenticationFailureHandler!=null){
			try {
				authenticationFailureHandler.onAuthenticationFailure(request, response, new BadCredentialsException(ex.getMessage(), ex));
				//处理后返回空的mv,如果返回null,dispatcher会认为异常没有被处理,抛出ex,见processHandlerException
				return new ModelAndView();
			} catch (Exception e) {
				throw new BaseException("handle authentication failure error: " + e.getMessage(), e);
			}
		}else{
			throw new org.springframework.security.authentication.BadCredentialsException(ex.getMessage());
		}
	}
	return super.doResolveException(request, response, handlerMethod, ex);
}
 
Example #26
Source File: AjaxLoginSuccessHandler.java    From fw-cloud-framework with MIT License 6 votes vote down vote up
private String[] extractAndDecodeHeader(String header) throws IOException {

		byte[] base64Token = header.substring(6)
				.getBytes("UTF-8");
		byte[] decoded;
		try {
			decoded = Base64.decode(base64Token);
		} catch (IllegalArgumentException e) {
			throw new BadCredentialsException("Failed to decode basic authentication token");
		}

		String token = new String(decoded, CommonConstant.UTF8);

		int delim = token.indexOf(":");

		if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); }
		return new String[] { token.substring(0, delim), token.substring(delim + 1) };
	}
 
Example #27
Source File: LogsearchFileAuthenticationProviderTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationWrongPassword() {
  List<GrantedAuthority> grantedAuths = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
  User user = new User("principal", passwordEncoder.encode("notCredentials"), grantedAuths);
  
  expect(mockAuthPropsConfig.isAuthFileEnabled()).andReturn(true);
  expect(mockUserDetailsService.loadUserByUsername("principal")).andReturn(user);
  
  replay(mockAuthPropsConfig, mockUserDetailsService);
  
  Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
  try {
    provider.authenticate(authentication);
    fail("Should have thrown BadCredentialsException");
  } catch (BadCredentialsException e) {
    assertEquals("Wrong password.", e.getMessage());
  }
  
  verify(mockAuthPropsConfig, mockUserDetailsService);
}
 
Example #28
Source File: RepositoryAuthenticationProvider.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
	try {
		UserEntity user = userService.findBySource(RepositoryIdentityProvider.PROVIDER_TYPE,  username, true);
		if (RepositoryIdentityProvider.PROVIDER_TYPE.equals(user.getSource())) {
			if (user.getPassword() == null) {
				throw new BadCredentialsException(messages.getMessage(
						"AbstractUserDetailsAuthenticationProvider.badCredentials",
						"Bad credentials"));
			}
			return mapUserEntityToUserDetails(user);
		} else {
			throw new UserNotFoundException(username);
		}
	} catch (UserNotFoundException notFound) {
		throw new UsernameNotFoundException(String.format("User '%s' not found", username), notFound);
	} catch (Exception repositoryProblem) {
		LOGGER.error("Failed to retrieveUser : {}", username, repositoryProblem);
		throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
	}
}
 
Example #29
Source File: UserDetailsAuthenticationProviderImpl.java    From spring-backend-boilerplate with Apache License 2.0 6 votes vote down vote up
/**
 * Implementation of an abstract method defined in the base class. The
 * additionalAuthenticationChecks() method is called by authenticate()
 * method of the base class after the invocation of retrieveUser() method.
 */
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
											  UsernamePasswordAuthenticationToken authentication)
		throws AuthenticationException {
	if (authentication.getCredentials() == null) {
		logger.warn("Authentication failed: no credentials provided");
		throw new BadCredentialsException(messages.getMessage(
				"AbstractUserDetailsAuthenticationProvider.badCredentials",
				"Bad credentials"), null);
	}

	String presentedPassword = authentication.getCredentials().toString();

	if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
		logger.warn("Authentication failed: password does not match stored value");
		throw new BadCredentialsException(messages.getMessage("UserDetailsAuthenticationProviderImpl.badCredentials",
															  "Bad credentials"), null);
	}
}
 
Example #30
Source File: RestAuthenticationEntryPoint.java    From jakduk-api with MIT License 6 votes vote down vote up
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {

    ServiceError serviceError = ServiceError.NEED_TO_LOGIN;

    if (authException.getClass().isAssignableFrom(BadCredentialsException.class))
        serviceError = ServiceError.BAD_CREDENTIALS;

    response.setContentType(ContentType.APPLICATION_JSON.toString());
    response.setStatus(serviceError.getHttpStatus());

    RestErrorResponse restErrorResponse = new RestErrorResponse(serviceError);
    String errorJson = ObjectMapperUtils.writeValueAsString(restErrorResponse);

    PrintWriter out = response.getWriter();
    out.print(errorJson);
    out.flush();
    out.close();
}