下面列出了怎么用org.springframework.security.oauth2.provider.ClientRegistrationException的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
}
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();
}
}
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();
}
}
@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);
}
}
@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;
}
@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;
}
@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;
}
/**
* 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;
}
@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;
}
@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;
}
@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;
}
@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();
}
@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;
}
@Override
public UserDetails loadUserByUsername( String username ) throws UsernameNotFoundException
{
try
{
return super.loadUserByUsername( username );
}
catch ( ClientRegistrationException ex )
{
throw new UsernameNotFoundException( ex.getMessage(), ex );
}
}
@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());
}
}
@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());
}
}
@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());
}
}
/**
* 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;
}
@Override
public ClientDetails loadClientByClientId(String id) throws ClientRegistrationException {
return clientDetailsRepo.findByClientId(id).orElse(null);
}
@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);
}
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
ClientDetails clientDetail = loadClientDetails(authentication);
return clientDetail;
}
@Override public ClientDetails loadClientByClientId(String clientId)
throws ClientRegistrationException {
return clientRepository.findByClientIdAlias(clientId).orElseThrow(
() -> new ClientRegistrationException(
String.format("Client %s does not exist!", clientId)));
}
@Override
public ClientDetails loadClientByClientId(String clientId)
throws ClientRegistrationException {
return clients_.loadClientByClientId(clientId);
}
/**
* 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);
}
abstract protected ClientDetails loadClientDetails(UsernamePasswordAuthenticationToken authentication) throws ClientRegistrationException;