org.springframework.security.authentication.InternalAuthenticationServiceException Java Examples

The following examples show how to use org.springframework.security.authentication.InternalAuthenticationServiceException. 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: MobileTokenAuthenticationProvider.java    From Taroco with Apache License 2.0 6 votes vote down vote up
@Override
protected UserDetails retrieveUser(final String mobile, final Authentication authentication) throws AuthenticationException {
    UserDetails loadedUser;
    try {
        loadedUser = userDetailsService.loadUserByUsername(mobile);
    } catch (UsernameNotFoundException var6) {
        throw var6;
    } catch (Exception var7) {
        throw new InternalAuthenticationServiceException(var7.getMessage(), var7);
    }
    if (loadedUser == null) {
        throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
    } else {
        return loadedUser;
    }
}
 
Example #2
Source File: CustomUserDetailsAuthenticationProvider.java    From tutorials with MIT License 6 votes vote down vote up
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) 
    throws AuthenticationException {
    CustomAuthenticationToken auth = (CustomAuthenticationToken) authentication;
    UserDetails loadedUser;

    try {
        loadedUser = this.userDetailsService.loadUserByUsernameAndDomain(auth.getPrincipal()
            .toString(), auth.getDomain());
    } catch (UsernameNotFoundException notFound) {
        if (authentication.getCredentials() != null) {
            String presentedPassword = authentication.getCredentials()
                .toString();
            passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword);
        }
        throw notFound;
    } catch (Exception repositoryProblem) {
        throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }

    if (loadedUser == null) {
        throw new InternalAuthenticationServiceException("UserDetailsService returned null, "
            + "which is an interface contract violation");
    }
    return loadedUser;
}
 
Example #3
Source File: TwoFactorAuthenticationServiceImpl.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
private UserSecret getSecret() {
  User user = getUser();
  UserSecret secret =
      runAsSystem(
          () ->
              dataService
                  .query(USER_SECRET, UserSecret.class)
                  .eq(UserSecretMetadata.USER_ID, user.getId())
                  .findOne());

  if (secret != null) {
    return secret;
  } else {
    throw new InternalAuthenticationServiceException(
        format(
            "Secret not found, user: [{0}] is not configured for two factor authentication",
            user.getUsername()));
  }
}
 
Example #4
Source File: SmsCodeAuthenticationProvider.java    From Taroco with Apache License 2.0 6 votes vote down vote up
@Override
protected UserDetails retrieveUser(final String mobile, final Authentication authentication) throws AuthenticationException {
    UserDetails loadedUser;
    try {
        loadedUser = userDetailsService.loadUserByUsername(mobile);
    } catch (UsernameNotFoundException var6) {
        throw var6;
    } catch (Exception var7) {
        throw new InternalAuthenticationServiceException(var7.getMessage(), var7);
    }
    if (loadedUser == null) {
        throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
    } else {
        return loadedUser;
    }
}
 
Example #5
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 #6
Source File: MiniAppIntegrationAuthenticator.java    From cola-cloud with MIT License 6 votes vote down vote up
@Override
public SysUserAuthentication authenticate(IntegrationAuthentication integrationAuthentication) {
    WxMaJscode2SessionResult session = null;
    String password = integrationAuthentication.getAuthParameter("password");
    try {
        session = this.wxMaService.getUserService().getSessionInfo(password);
        WechatMiniAppToken wechatToken = new WechatMiniAppToken(session.getOpenid(), session.getUnionid(), session.getSessionKey());
        // 加密算法的初始向量
        wechatToken.setIv(integrationAuthentication.getAuthParameter("iv"));
        // 用户的加密数据
        wechatToken.setEncryptedData(integrationAuthentication.getAuthParameter("encryptedData"));
    } catch (WxErrorException e) {
        throw new InternalAuthenticationServiceException("获取微信小程序用户信息失败",e);
    }
    String openId = session.getOpenid();
    SysUserAuthentication sysUserAuthentication = sysUserClient.findUserBySocial(UcClientConstant.SOCIAL_TYPE_WECHAT_MINIAP, openId);
    if(sysUserAuthentication != null){
        sysUserAuthentication.setPassword(passwordEncoder.encode(password));
    }
    return sysUserAuthentication;
}
 
Example #7
Source File: CustomUserDetailsAuthenticationProvider.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
/**
  * 加载用户信息
  *
  * @param username       username
  * @param authentication authentication
  * @return UserDetails
  * @throws AuthenticationException
  */
 @Override
 protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException, TenantNotFoundException{
     UserDetails loadedUser;
     try {
         // 加载用户信息
         loadedUser = this.userDetailsService.loadUserByIdentifierAndTenantCode(TenantContextHolder.getTenantCode(), authentication.getPrincipal().toString());
     } catch (UsernameNotFoundException notFound) {
         if (authentication.getCredentials() != null) {
             String presentedPassword = authentication.getCredentials().toString();
             passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword);
         }
         throw notFound;
     } catch (Exception tenantNotFound) {
throw new InternalAuthenticationServiceException(tenantNotFound.getMessage(), tenantNotFound);
     }
     if (loadedUser == null) {
         throw new InternalAuthenticationServiceException("get user information failed");
     }
     return loadedUser;
 }
 
Example #8
Source File: AjaxAuthenticationProvider.java    From fw-cloud-framework with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
	AjaxAuthenticationToken ajaxAuthenticationToken = (AjaxAuthenticationToken) authentication;
	AuthUser user = userFeignApi.findUserByMobile((String) ajaxAuthenticationToken.getPrincipal());

	if (null == user)
		throw new UsernameNotFoundException("登录账户[" + ajaxAuthenticationToken.getPrincipal() + "]不存在");

	UserDetailsImpl userDetails = buildUserDeatils(user);

	if (null == userDetails)
		throw new InternalAuthenticationServiceException("登录用户[" + ajaxAuthenticationToken.getPrincipal() + "]不存在!");

	AjaxAuthenticationToken authenticationToken = new AjaxAuthenticationToken(userDetails, userDetails.getAuthorities());
	authenticationToken.setDetails(ajaxAuthenticationToken.getDetails());
	return authenticationToken;
}
 
Example #9
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 #10
Source File: SmsCodeAuthenticationProvider.java    From imooc-security with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
    UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
    if(user==null){
        throw new InternalAuthenticationServiceException("无法获取用户信息");
    }
    SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user,user.getAuthorities());
    //把未认证的信息放到已认证的detail里面
    authenticationResult.setDetails(authenticationToken.getDetails());

    return authenticationResult;
}
 
Example #11
Source File: JwtTokenParserTest.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithUnsupportedAlgotith() {
    expectedException.expect(InternalAuthenticationServiceException.class);
    expectedException.expectMessage("Unsupported verifier algorithm not-supported-algorith");

    JwtTokenParser parser = new JwtTokenParserMock(new TokenFactory(),
                                                   mockUaaCLient(false, "not-supported-algorith", "not-at-all-matters"),
                                                   true);
    parser.parse("not-important-token-string");
}
 
Example #12
Source File: JwtTokenParser.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private TokenKey readTokenKey() {
    Map<String, Object> tokenKeyResponse = uaaClient.readTokenKey();
    Object value = tokenKeyResponse.get("value");
    Object alg = tokenKeyResponse.get("alg");
    if (value == null || alg == null) {
        throw new InternalAuthenticationServiceException("Response from /token_key does not contain a key value or an algorithm");
    }
    return new TokenKey(value.toString(), alg.toString());

}
 
Example #13
Source File: AccessPredicates.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * @deprecated Should never be called
 */
@Override
@Deprecated // Should never be called
public boolean test(final Authentication t) {
    throw new InternalAuthenticationServiceException(
            "Tried to execute the 'permit-all' access predicate. The server's security configuration is broken.");
}
 
Example #14
Source File: AccessPredicates.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * @deprecated Should never be called
 */
@Override
@Deprecated // Should never be called
public boolean test(final Authentication t) {
    throw new InternalAuthenticationServiceException(
            "Tried to execute the 'permit-all' access predicate. The server's security configuration is broken.");
}
 
Example #15
Source File: SmsAuthenticationProvider.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
    UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());

    if (userDetails == null)
        throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");

    SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());

    authenticationResult.setDetails(authenticationToken.getDetails());

    return authenticationResult;
}
 
Example #16
Source File: SmsAuthenticationProvider.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
    UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());

    if (userDetails == null)
        throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");

    SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());

    authenticationResult.setDetails(authenticationToken.getDetails());

    return authenticationResult;
}
 
Example #17
Source File: SmsAuthenticationProvider.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
    UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());

    if (userDetails == null)
        throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");

    SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());

    authenticationResult.setDetails(authenticationToken.getDetails());

    return authenticationResult;
}
 
Example #18
Source File: SmsAuthenticationProvider.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
    UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());

    if (userDetails == null)
        throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");

    SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());

    authenticationResult.setDetails(authenticationToken.getDetails());

    return authenticationResult;
}
 
Example #19
Source File: AuthenticatedUser.java    From jwala with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @return user
 */
public User getUser() {
    if(context.getUserPrincipal() == null) {
        throw new InternalAuthenticationServiceException("User not found");
    }
    return new User(context.getUserPrincipal().getName());
}
 
Example #20
Source File: AuthenticationFilter.java    From learning-code with Apache License 2.0 5 votes vote down vote up
private Authentication tryToAuthenticate(Authentication requestAuth) {
    Authentication responseAuth = getAuthenticationManager().authenticate(requestAuth);
    if (responseAuth == null || !responseAuth.isAuthenticated()) {
        throw new InternalAuthenticationServiceException("Unable to authenticate Domain User for provided credentials");
    }
    log.debug("User successfully authenticated");
    return responseAuth;
}
 
Example #21
Source File: LoginController.java    From Parrit with MIT License 5 votes vote down vote up
@RequestMapping(path = "/api/login", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> login(@RequestBody @Valid LoginDTO loginDTO) throws InternalAuthenticationServiceException {
    String name = loginDTO.getName();
    String password = loginDTO.getPassword();

    Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(name, password, Collections.emptyList()));

    if (authentication.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return new ResponseEntity<>("/" + authentication.getName(), HttpStatus.OK);
    }

    throw new InternalAuthenticationServiceException("Unknown authentication failure.");
}
 
Example #22
Source File: ManagementEndpointAuthenticationFilter.java    From spring-boot-security-example with MIT License 5 votes vote down vote up
private Authentication tryToAuthenticate(Authentication requestAuthentication) {
    Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication);
    if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {
        throw new InternalAuthenticationServiceException("Unable to authenticate Backend Admin for provided credentials");
    }
    logger.debug("Backend Admin successfully authenticated");
    return responseAuthentication;
}
 
Example #23
Source File: AuthenticationFilter.java    From spring-boot-security-example with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = asHttp(request);
    HttpServletResponse httpResponse = asHttp(response);

    Optional<String> username = Optional.fromNullable(httpRequest.getHeader("X-Auth-Username"));
    Optional<String> password = Optional.fromNullable(httpRequest.getHeader("X-Auth-Password"));
    Optional<String> token = Optional.fromNullable(httpRequest.getHeader("X-Auth-Token"));

    String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);

    try {
        if (postToAuthenticate(httpRequest, resourcePath)) {
            logger.debug("Trying to authenticate user {} by X-Auth-Username method", username);
            processUsernamePasswordAuthentication(httpResponse, username, password);
            return;
        }

        if (token.isPresent()) {
            logger.debug("Trying to authenticate user by X-Auth-Token method. Token: {}", token);
            processTokenAuthentication(token);
        }

        logger.debug("AuthenticationFilter is passing request down the filter chain");
        addSessionContextToLogging();
        chain.doFilter(request, response);
    } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) {
        SecurityContextHolder.clearContext();
        logger.error("Internal authentication service exception", internalAuthenticationServiceException);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (AuthenticationException authenticationException) {
        SecurityContextHolder.clearContext();
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
    } finally {
        MDC.remove(TOKEN_SESSION_KEY);
        MDC.remove(USER_SESSION_KEY);
    }
}
 
Example #24
Source File: AuthenticationFilter.java    From spring-boot-security-example with MIT License 5 votes vote down vote up
private Authentication tryToAuthenticate(Authentication requestAuthentication) {
    Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication);
    if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {
        throw new InternalAuthenticationServiceException("Unable to authenticate Domain User for provided credentials");
    }
    logger.debug("User successfully authenticated");
    return responseAuthentication;
}
 
Example #25
Source File: MolgenisLoginController.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String determineErrorMessagesFromInternalAuthenticationExceptions(Object attribute) {
  String errorMessage = "";
  if (attribute instanceof InternalAuthenticationServiceException) {
    Throwable throwable = ((InternalAuthenticationServiceException) attribute).getCause();
    if (throwable.getCause() instanceof UsernameNotFoundException) {
      errorMessage = ERROR_MESSAGE_BAD_CREDENTIALS;
    }
  }
  return errorMessage;
}
 
Example #26
Source File: TwoFactorAuthenticationServiceImpl.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void saveSecretForUser(String secret) {

  if (secret == null) {
    throw new InternalAuthenticationServiceException("No secretKey found");
  } else {
    User user = getUser();
    UserSecret userSecret = userSecretFactory.create();
    userSecret.setUserId(user.getId());
    userSecret.setSecret(secret);
    runAsSystem(() -> dataService.add(USER_SECRET, userSecret));
  }
}
 
Example #27
Source File: TwoFactorAuthenticationServiceImpl.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean isConfiguredForUser() {
  boolean isConfigured = false;
  try {
    UserSecret secret = getSecret();
    if (StringUtils.hasText(secret.getSecret())) {
      isConfigured = true;
    }
  } catch (InternalAuthenticationServiceException err) {
    LOG.warn(err.getMessage());
  }

  return isConfigured;
}
 
Example #28
Source File: HttpAuthenticationFilter.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
private void tryAuthenticate(Authentication requestAuth) {
    Authentication authentication = authenticationManager.authenticate(requestAuth);
    if (authentication == null || !authentication.isAuthenticated()) {
        throw new InternalAuthenticationServiceException("Unable to authenticate user with provided credentials");
    }
    logger.debug("Successfully authenticated");
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example #29
Source File: SmsAuthenticationProvider.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
    UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());

    if (userDetails == null)
        throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");

    SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());

    authenticationResult.setDetails(authenticationToken.getDetails());

    return authenticationResult;
}
 
Example #30
Source File: CustomWebResponseExceptionTranslator.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ResponseEntity translate(Exception e) throws Exception {
       JsonData<Void> jsonData = JsonData.failed(StatusEnum.SYSTEM_ERROR);
       if (e instanceof InternalAuthenticationServiceException) {
           jsonData = JsonData.failed(StatusEnum.SYSTEM_ERROR);
       } else if (e instanceof InvalidGrantException) {
           jsonData = JsonData.failed(StatusEnum.LOGIN_ERROR);
       }
       return new ResponseEntity<>(jsonData, HttpStatus.OK);
   }