Java Code Examples for org.springframework.security.oauth2.provider.ClientRegistrationException

The following examples show how to use org.springframework.security.oauth2.provider.ClientRegistrationException. 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
Source Project: konker-platform   Source File: OAuthClientDetailsService.java    License: Apache License 2.0 6 votes vote down vote up
public ServiceResponse<OauthClientDetails> loadClientById(Tenant tenant, String clientId) throws ClientRegistrationException {
    if (!Optional.ofNullable(clientId).isPresent()) {
        throw new ClientRegistrationException(Validations.INVALID_ID.getCode());
    }
    OauthClientDetails details = oauthClientDetailRepository.findOne(clientId);
    if (details != null) {
        if (!details.getTenant().getId().equals(tenant.getId())) {
            return ServiceResponseBuilder.<OauthClientDetails>error()
                    .withMessage(Messages.CLIENT_CREDENTIALS_INVALID.getCode())
                    .build();
        }
        return ServiceResponseBuilder.<OauthClientDetails>ok()
                .withResult(details)
                .build();
    } else {
        return ServiceResponseBuilder.<OauthClientDetails>error()
                .withMessage(Messages.CLIENT_CREDENTIALS_INVALID.getCode())
                .build();
    }

}
 
Example 2
Source Project: konker-platform   Source File: OAuthClientDetailsService.java    License: Apache License 2.0 6 votes vote down vote up
public ServiceResponse<OauthClientDetails> loadApplicationAndClientSecret(Tenant tenant, Application application, String clientSecret)
        throws ClientRegistrationException {
    if (!Optional.ofNullable(clientSecret).isPresent()) {
        throw new ClientRegistrationException(Validations.INVALID_ID.getCode());
    }
    OauthClientDetails details = oauthClientDetailRepository.findByApplicationAndSecret(application.getName(), clientSecret);
    if (details != null) {
        if (!details.getTenant().getId().equals(tenant.getId())) {
            return ServiceResponseBuilder.<OauthClientDetails>error()
                    .withMessage(Messages.CLIENT_CREDENTIALS_INVALID.getCode())
                    .build();
        }
        return ServiceResponseBuilder.<OauthClientDetails>ok()
                .withResult(details)
                .build();
    } else {
        return ServiceResponseBuilder.<OauthClientDetails>error()
                .withMessage(Messages.CLIENT_CREDENTIALS_INVALID.getCode())
                .build();
    }
}
 
Example 3
Source Project: konker-platform   Source File: OAuthClientDetailsService.java    License: Apache License 2.0 6 votes vote down vote up
public ServiceResponse<OauthClientDetails> loadClientByIdAsRoot(String clientId) throws ClientRegistrationException {
    if (!Optional.ofNullable(clientId).isPresent()) {
        throw new ClientRegistrationException(Validations.INVALID_ID.getCode());
    }
    OauthClientDetails details = oauthClientDetailRepository.findOne(clientId);
    if (details != null) {
        return ServiceResponseBuilder.<OauthClientDetails>ok()
                .withResult(details)
                .build();
    } else {
        User user = userRepository.findByEmail(clientId);
        if (user != null) {
            return ServiceResponseBuilder.<OauthClientDetails>ok()
                    .withResult(OauthClientDetails.builder().build().setUserProperties(user))
                    .build();
        }

        return ServiceResponseBuilder.<OauthClientDetails>error()
                .withMessage(Messages.CLIENT_CREDENTIALS_INVALID.getCode())
                .build();
    }
}
 
Example 4
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
    
    if (clientId.equals(id))
    {
        List<String> authorizedGrantTypes = new ArrayList<String>();
        authorizedGrantTypes.add("password");
        authorizedGrantTypes.add("refresh_token");
        authorizedGrantTypes.add("client_credentials");
 
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(id);
        clientDetails.setClientSecret(secretKey);
        clientDetails.setAuthorizedGrantTypes(authorizedGrantTypes);
         
        return clientDetails;
    }
    else {
        throw new NoSuchClientException("No client recognized with id: "
                + clientId);
    }
    
}
 
Example 5
Source Project: open-cloud   Source File: ClientDetailsServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
    ClientDetails details = baseAppServiceClient.getAppClientInfo(clientId).getData();
    if (details != null && details.getClientId()!=null && details.getAdditionalInformation() != null) {
        String status = details.getAdditionalInformation().getOrDefault("status", "0").toString();
        if(!"1".equals(status)){
            throw new ClientRegistrationException("客户端已被禁用");
        }
    }
    return details;
}
 
Example 6
Source Project: open-cloud   Source File: ClientDetailsServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
    ClientDetails details = baseAppRemoteService.getAppClientInfo(clientId).getData();
    if (details != null && details.getClientId()!=null && details.getAdditionalInformation() != null) {
        String status = details.getAdditionalInformation().getOrDefault("status", "0").toString();
        if(!"1".equals(status)){
            throw new ClientRegistrationException("客户端已被禁用");
        }
    }
    return details;
}
 
Example 7
@Override
public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException,
        InvalidTokenException {
    OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
    if (accessToken == null) {
        throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
    }
    else if (accessToken.isExpired()) {
        tokenStore.removeAccessToken(accessToken);
        throw new InvalidTokenException("Access token expired: " + accessTokenValue);
    }

    OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
    if (result == null) {
        // in case of race condition
        throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
    }
    if (clientDetailsService != null) {
        String clientId = result.getOAuth2Request().getClientId();
        try {
            clientDetailsService.loadClientByClientId(clientId);
        }
        catch (ClientRegistrationException e) {
            throw new InvalidTokenException("Client not valid: " + clientId, e);
        }
    }
    return result;
}
 
Example 8
Source Project: springcloud-oauth2   Source File: ClientDetailsServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * Load a client by the client id. This method must not return null.
 *
 * @param clientId The client id.
 * @return The client details (never null).
 * @throws ClientRegistrationException If the client account is locked, expired, disabled, or invalid for any other reason.
 */
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
    log.info("客户端查询:" + clientId);
    BaseClientDetails baseClientDetails = clientDetailService.selectById(clientId);
    if (baseClientDetails == null) {
        throw new NoSuchClientException("not found clientId:" + clientId);
    }
    return baseClientDetails;
}
 
Example 9
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
    ApiResponse apiResponse = authorityClient.getOauthClientDetailsByClientId(clientId);
    OauthClientDetails model  = JSON.parseObject(JSON.toJSONString( apiResponse.getData(), true),OauthClientDetails.class);
    if (model == null) {
        throw new CommonException(SophiaHttpStatus.CLIENT_ERROR);
    }
    BaseClientDetails clientDetails = new BaseClientDetails();
    //客户端(client)id
    clientDetails.setClientId(model.getClientId());
    //客户端所能访问的资源id集合
    if (StringUtils.isNotEmpty(model.getResourceIds())) {
        clientDetails.setResourceIds(Arrays.asList(model.getResourceIds().split(",")));
    }
    //客户端(client)的访问密匙
    clientDetails.setClientSecret(new BCryptPasswordEncoder().encode(model.getClientSecret()));
    //客户端支持的grant_type授权类型
    clientDetails.setAuthorizedGrantTypes(Arrays.asList(model.getAuthorizedGrantTypes().split(",")));
    //客户端申请的权限范围
    clientDetails.setScope(Arrays.asList(model.getScope().split(",")));
    Integer accessTokenValidity = model.getAccessTokenValidity();
    if (accessTokenValidity != null && accessTokenValidity > 0) {
        //设置token的有效期,不设置默认12小时
        clientDetails.setAccessTokenValiditySeconds(accessTokenValidity);
    }
    Integer refreshTokenValidity = model.getRefreshTokenValidity();
    if (refreshTokenValidity != null && refreshTokenValidity > 0) {
        //设置刷新token的有效期,不设置默认30天
        clientDetails.setRefreshTokenValiditySeconds(refreshTokenValidity);
    }
    clientDetails.isAutoApprove(model.getAutoapprove());
    log.debug("clientId是:" + clientId);
    return clientDetails;
}
 
Example 10
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
    ApiResponse apiResponse = authorityClient.getOauthClientDetailsByClientId(clientId);
    OauthClientDetails model  = JSON.parseObject(JSON.toJSONString( apiResponse.getData(), true),OauthClientDetails.class);
    if (model == null) {
        throw new CommonException(SophiaHttpStatus.CLIENT_ERROR);
    }
    BaseClientDetails clientDetails = new BaseClientDetails();
    //客户端(client)id
    clientDetails.setClientId(model.getClientId());
    //客户端所能访问的资源id集合
    if (StringUtils.isNotEmpty(model.getResourceIds())) {
        clientDetails.setResourceIds(Arrays.asList(model.getResourceIds().split(",")));
    }
    //客户端(client)的访问密匙
    clientDetails.setClientSecret(new BCryptPasswordEncoder().encode(model.getClientSecret()));
    //客户端支持的grant_type授权类型
    clientDetails.setAuthorizedGrantTypes(Arrays.asList(model.getAuthorizedGrantTypes().split(",")));
    //客户端申请的权限范围
    clientDetails.setScope(Arrays.asList(model.getScope().split(",")));
    Integer accessTokenValidity = model.getAccessTokenValidity();
    if (accessTokenValidity != null && accessTokenValidity > 0) {
        //设置token的有效期,不设置默认12小时
        clientDetails.setAccessTokenValiditySeconds(accessTokenValidity);
    }
    Integer refreshTokenValidity = model.getRefreshTokenValidity();
    if (refreshTokenValidity != null && refreshTokenValidity > 0) {
        //设置刷新token的有效期,不设置默认30天
        clientDetails.setRefreshTokenValiditySeconds(refreshTokenValidity);
    }
    clientDetails.isAutoApprove(model.getAutoapprove());
    log.debug("clientId是:" + clientId);
    return clientDetails;
}
 
Example 11
Source Project: oauth-boot   Source File: BootClientDetailsService.java    License: MIT License 5 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {

    Client client = this.clientService.findClientByClientId(clientId);

    if(client==null){
        throw new ClientRegistrationException("客户端不存在");
    }
    BootClientDetails details=new BootClientDetails(client);

    return details;
}
 
Example 12
Source Project: konker-platform   Source File: OAuthClientDetailsService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
    if (!Optional.ofNullable(clientId).isPresent()) {
        throw new ClientRegistrationException(Validations.INVALID_ID.getCode());
    }
    ServiceResponse<OauthClientDetails> response = loadClientByIdAsRoot(clientId);
    if (!Optional.ofNullable(response).isPresent() || !response.isOk()) {
        throw new ClientRegistrationException("Invalid credentials");
    }

    return response.getResult().toClientDetails();

}
 
Example 13
@Override
public ClientDetails loadClientByClientId( String clientId ) throws ClientRegistrationException
{
    ClientDetails clientDetails = clientDetails( oAuth2ClientService.getOAuth2ClientByClientId( clientId ) );

    if ( clientDetails == null )
    {
        throw new ClientRegistrationException( "Invalid client_id" );
    }

    return clientDetails;
}
 
Example 14
@Override
public UserDetails loadUserByUsername( String username ) throws UsernameNotFoundException
{
    try
    {
        return super.loadUserByUsername( username );
    }
    catch ( ClientRegistrationException ex )
    {
        throw new UsernameNotFoundException( ex.getMessage(), ex );
    }
}
 
Example 15
@Test(expected = ClientRegistrationException.class)
public void loadClientNotFound() throws Exception {
    ConsumerRecordVO record = this.createMockConsumer("key_1", "secret", true);
    when(this.consumerDAO.getConsumer(Mockito.anyString())).thenReturn(record);
    try {
        ClientDetails extracted = this.consumerManager.loadClientByClientId("key_1");
    } catch (ClientRegistrationException e) {
        throw e;
    } finally {
        Mockito.verify(consumerDAO, Mockito.times(1)).getConsumer(Mockito.anyString());
    }
}
 
Example 16
@Test(expected = ClientRegistrationException.class)
public void loadClientNotFound_2() throws Exception {
    when(this.consumerDAO.getConsumer(Mockito.anyString())).thenReturn(null);
    try {
        ClientDetails extracted = this.consumerManager.loadClientByClientId("key_1");
    } catch (ClientRegistrationException e) {
        throw e;
    } finally {
        Mockito.verify(consumerDAO, Mockito.times(1)).getConsumer(Mockito.anyString());
    }
}
 
Example 17
@Test(expected = ClientRegistrationException.class)
public void loadClientNotFound_3() throws Exception {
    when(this.consumerDAO.getConsumer(Mockito.anyString())).thenThrow(RuntimeException.class);
    try {
        ClientDetails extracted = this.consumerManager.loadClientByClientId("key_1");
    } catch (ClientRegistrationException e) {
        throw e;
    } finally {
        Mockito.verify(consumerDAO, Mockito.times(1)).getConsumer(Mockito.anyString());
    }
}
 
Example 18
/**
 * Allows automatic approval for a white list of clients in the implicit grant case.
 * 
 * @param authorizationRequest The authorization request.
 * @param userAuthentication the current user authentication
 * 
 * @return An updated request if it has already been approved by the current user.
 */
@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest,
		Authentication userAuthentication) {

	boolean approved = false;
	// If we are allowed to check existing approvals this will short circuit the decision
	if (useApprovalStore) {
		authorizationRequest = super.checkForPreApproval(authorizationRequest, userAuthentication);
		approved = authorizationRequest.isApproved();
	}
	else {
		if (clientDetailsService != null) {
			Collection<String> requestedScopes = authorizationRequest.getScope();
			try {
				ClientDetails client = clientDetailsService
						.loadClientByClientId(authorizationRequest.getClientId());
				for (String scope : requestedScopes) {
					if (client.isAutoApprove(scope) || client.isAutoApprove("all")) {
						approved = true;
						break;
					}
				}
			}
			catch (ClientRegistrationException e) {
			}
		}
	}
	authorizationRequest.setApproved(approved);

	return authorizationRequest;
}
 
Example 19
Source Project: authmore-framework   Source File: ClientDetailService.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String id) throws ClientRegistrationException {
    return clientDetailsRepo.findByClientId(id).orElse(null);
}
 
Example 20
Source Project: NFVO   Source File: CustomClientDetailsService.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
  for (BaseClientDetails baseClientDetails : clientDetailsRepo)
    if (baseClientDetails.getClientId().equals(clientId)) return baseClientDetails;
  throw new ClientRegistrationException("Invalid clientId: " + clientId);
}
 
Example 21
Source Project: onetwo   Source File: AbstractOAuth2ClientDetailsService.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
	UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
	ClientDetails clientDetail = loadClientDetails(authentication);
	return clientDetail;
}
 
Example 22
@Override public ClientDetails loadClientByClientId(String clientId)
    throws ClientRegistrationException {
  return clientRepository.findByClientIdAlias(clientId).orElseThrow(
      () -> new ClientRegistrationException(
          String.format("Client %s does not exist!", clientId)));
}
 
Example 23
@Override
public ClientDetails loadClientByClientId(String clientId)
		throws ClientRegistrationException {
	return clients_.loadClientByClientId(clientId);
}
 
Example 24
/**
 * Load client by client id client details.
 *
 * @param clientId the client id
 *
 * @return the client details
 *
 * @throws ClientRegistrationException the client registration exception
 */
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
	return clientDetailsService.loadClientByClientId(clientId);
}
 
Example 25
abstract protected ClientDetails loadClientDetails(UsernamePasswordAuthenticationToken authentication) throws ClientRegistrationException;