org.springframework.security.oauth2.provider.ClientDetails Java Examples

The following examples show how to use org.springframework.security.oauth2.provider.ClientDetails. 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: AccessConfirmationController.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception {
    AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
    ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
    model.put("auth_request", clientAuth);
    model.put("client", client);
    Map<String, String> scopes = new LinkedHashMap<String, String>();
    for (String scope : clientAuth.getScope()) {
        scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false");
    }
    for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) {
        if (clientAuth.getScope().contains(approval.getScope())) {
            scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(),
                    approval.getStatus() == Approval.ApprovalStatus.APPROVED ? "true" : "false");
        }
    }
    model.put("scopes", scopes);
    return new ModelAndView("access_confirmation", model); // 订阅 appproval 页面
}
 
Example #3
Source File: IndexController.java    From open-cloud with MIT License 6 votes vote down vote up
/**
 * 确认授权页
 * @param request
 * @param session
 * @param model
 * @return
 */
@RequestMapping("/oauth/confirm_access")
public String confirm_access(HttpServletRequest request, HttpSession session, Map model) {
    Map<String, String> scopes = (Map<String, String>) (model.containsKey("scopes") ? model.get("scopes") : request.getAttribute("scopes"));
    List<String> scopeList = new ArrayList<String>();
    for (String scope : scopes.keySet()) {
        scopeList.add(scope);
    }
    model.put("scopeList", scopeList);
    Object auth = session.getAttribute("authorizationRequest");
    if (auth != null) {
        try {
            AuthorizationRequest authorizationRequest = (AuthorizationRequest) auth;
            ClientDetails clientDetails = baseAppRemoteService.getAppClientInfo(authorizationRequest.getClientId()).getData();
            model.put("app", clientDetails.getAdditionalInformation());
        } catch (Exception e) {

        }
    }
    return "confirm_access";
}
 
Example #4
Source File: RedisClientDetailsService.java    From cloud-service with MIT License 6 votes vote down vote up
/**
 * 将oauth_client_details全表刷入redis
 */
public void loadAllClientToCache() {
    if (stringRedisTemplate.hasKey(CACHE_CLIENT_KEY) == Boolean.TRUE) {
        return;
    }
    log.info("将oauth_client_details全表刷入redis");

    List<ClientDetails> list = super.listClientDetails();
    if (CollectionUtils.isEmpty(list)) {
        log.error("oauth_client_details表数据为空,请检查");
        return;
    }

    list.parallelStream().forEach(client -> {
        stringRedisTemplate.boundHashOps(CACHE_CLIENT_KEY).put(client.getClientId(), JSONObject.toJSONString(client));
    });
}
 
Example #5
Source File: OauthClientDetails.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
public ClientDetails toClientDetails() {
    BaseClientDetails clientDetails =
            new BaseClientDetails(
                    getClientId(),
                    getResourceIdsAsString(),
                    getScopeAsString(),
                    getAuthorizedGrantTypesAsString(),
                    getAuthoritiesAsString(),
                    getWebServerRedirectUri());
    clientDetails.setClientSecret(clientSecret);
    clientDetails.setAdditionalInformation(additionalInformation);
    clientDetails.setAccessTokenValiditySeconds(accessTokenValidity);
    clientDetails.setRefreshTokenValiditySeconds(refreshTokenValidity);

    return clientDetails;
}
 
Example #6
Source File: AccessConfirmationController.java    From OpenESPI-DataCustodian-java with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception {
	AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
	ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
	model.put("auth_request", clientAuth);
	model.put("client", client);
	Map<String, String> scopes = new LinkedHashMap<String, String>();
	for (String scope : clientAuth.getScope()) {
		scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false");  //Spring Security OAuth2 2.0.0.M2 change
	}
	for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) {
		if (clientAuth.getScope().contains(approval.getScope())) {
			scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(),
					approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false");
		}
	}
	model.put("scopes", scopes);
	return new ModelAndView("access_confirmation", model);
}
 
Example #7
Source File: ApplicationEndpoint.java    From watchdog-spring-boot-starter with MIT License 6 votes vote down vote up
@PutMapping(value = {"${watchdog.application.prefix:}/applications/{clientId}"})
public ClientDetails update(@PathVariable String clientId, @RequestBody ApplicationParam param){
    Optional<Application> application = applicationService.findByClientId(clientId);
    if(!application.isPresent()){
        throw new NoSuchClientException("Not Found The Client.");
    }
    application.ifPresent(app -> {
        param.populateDefault();
        if(!StringUtils.isEmpty(param.getName())){
            app.setName(param.getName());
        }
        if(param.getRedirectUri() != null){
            app.setRegisteredRedirectUri(param.getRedirectUri());
        }

        if(param.getScope() != null){
            app.setScope(param.getScope());
        }
    });
    applicationService.updateClientDetails(application.get());
    return application.get();
}
 
Example #8
Source File: OAuthClientDetailsServiceTest.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void saveAndLoadGatewayClient() {
    Gateway gateway = new Gateway();
    gateway.setId("gateway-id");
    gateway.setGuid("gateway-guid");
    gateway.setTenant(tenant);

    OauthClientDetails clientDetails = new OauthClientDetails();
    clientDetails.setGatewayProperties(gateway);

    ServiceResponse<OauthClientDetails> serviceResponse = oauthClientDetailsService.saveClient(tenant, null, clientDetails);
    assertThat(serviceResponse, isResponseOk());

    ClientDetails clientDetailsDB = oauthClientDetailsService.loadClientByClientId(gateway.getRoutUriTemplate());
    assertThat(clientDetailsDB, notNullValue());

}
 
Example #9
Source File: CustomRedisTokenStore.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 获取token的总有效时长
 * @param clientId 应用id
 */
private int getAccessTokenValiditySeconds(String clientId) {
    RedisConnection conn = getConnection();
    byte[] bytes;
    try {
        bytes = conn.get(serializeKey(SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId));
    } finally {
        conn.close();
    }
    if (bytes != null) {
        ClientDetails clientDetails = deserializeClientDetails(bytes);
        if (clientDetails.getAccessTokenValiditySeconds() != null) {
            return clientDetails.getAccessTokenValiditySeconds();
        }
    }

    //返回默认值
    return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS;
}
 
Example #10
Source File: OsiamUserApprovalHandler.java    From osiam with MIT License 6 votes vote down vote up
private boolean hasRememberedApprovalForClient(AuthorizationRequest authorizationRequest, ClientDetails client) {
    @SuppressWarnings("unchecked")
    Map<String, Long> approvals = (Map<String, Long>) httpSession.getAttribute(APPROVALS_SESSION_KEY);

    if (approvals == null) {
        return false;
    }

    final Long approvalTime = approvals.get(authorizationRequest.getClientId());

    if (approvalTime == null) {
        return false;
    }

    final long validityInSeconds = (Long) client.getAdditionalInformation().get("validityInSeconds");

    if (System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(validityInSeconds) > approvalTime) {
        approvals.remove(authorizationRequest.getClientId());
        return false;
    }

    return true;
}
 
Example #11
Source File: OAuth2AutoConfigurationTests.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultConfiguration() {
	this.context = new AnnotationConfigServletWebServerApplicationContext();
	this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class);
	this.context.refresh();
	this.context.getBean(AUTHORIZATION_SERVER_CONFIG);
	this.context.getBean(RESOURCE_SERVER_CONFIG);
	this.context.getBean(OAuth2MethodSecurityConfiguration.class);
	ClientDetails config = this.context.getBean(BaseClientDetails.class);
	AuthorizationEndpoint endpoint = this.context.getBean(AuthorizationEndpoint.class);
	UserApprovalHandler handler = (UserApprovalHandler) ReflectionTestUtils.getField(endpoint,
			"userApprovalHandler");
	ClientDetailsService clientDetailsService = this.context.getBean(ClientDetailsService.class);
	ClientDetails clientDetails = clientDetailsService.loadClientByClientId(config.getClientId());
	assertThat(AopUtils.isJdkDynamicProxy(clientDetailsService)).isTrue();
	assertThat(AopUtils.getTargetClass(clientDetailsService).getName())
			.isEqualTo(InMemoryClientDetailsService.class.getName());
	assertThat(handler).isInstanceOf(ApprovalStoreUserApprovalHandler.class);
	assertThat(clientDetails).isEqualTo(config);
	verifyAuthentication(config);
	assertThat(this.context.getBeanNamesForType(OAuth2RestOperations.class)).isEmpty();
}
 
Example #12
Source File: SocialLoginServiceImpl.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessToken getOauth2AccessToken(SystemUser user) throws FebsException {
    final HttpServletRequest httpServletRequest = FebsUtil.getHttpServletRequest();
    httpServletRequest.setAttribute(ParamsConstant.LOGIN_TYPE, SocialConstant.SOCIAL_LOGIN);
    String socialLoginClientId = properties.getSocialLoginClientId();
    ClientDetails clientDetails = null;
    try {
        clientDetails = redisClientDetailsService.loadClientByClientId(socialLoginClientId);
    } catch (Exception e) {
        throw new FebsException("获取第三方登录可用的Client失败");
    }
    if (clientDetails == null) {
        throw new FebsException("未找到第三方登录可用的Client");
    }
    Map<String, String> requestParameters = new HashMap<>(5);
    requestParameters.put(ParamsConstant.GRANT_TYPE, GrantTypeConstant.PASSWORD);
    requestParameters.put(USERNAME, user.getUsername());
    requestParameters.put(PASSWORD, SocialConstant.SOCIAL_LOGIN_PASSWORD);

    String grantTypes = String.join(StringConstant.COMMA, clientDetails.getAuthorizedGrantTypes());
    TokenRequest tokenRequest = new TokenRequest(requestParameters, clientDetails.getClientId(), clientDetails.getScope(), grantTypes);
    return granter.grant(GrantTypeConstant.PASSWORD, tokenRequest);
}
 
Example #13
Source File: OAuth2AutoConfigurationTests.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testEnvironmentalOverrides() {
	this.context = new AnnotationConfigServletWebServerApplicationContext();
	TestPropertyValues.of("security.oauth2.client.clientId:myclientid",
			"security.oauth2.client.clientSecret:mysecret", "security.oauth2.client.autoApproveScopes:read,write",
			"security.oauth2.client.accessTokenValiditySeconds:40",
			"security.oauth2.client.refreshTokenValiditySeconds:80").applyTo(this.context);
	this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class);
	this.context.refresh();
	ClientDetails config = this.context.getBean(ClientDetails.class);
	assertThat(config.getClientId()).isEqualTo("myclientid");
	assertThat(config.getClientSecret()).isEqualTo("mysecret");
	assertThat(config.isAutoApprove("read")).isTrue();
	assertThat(config.isAutoApprove("write")).isTrue();
	assertThat(config.isAutoApprove("foo")).isFalse();
	assertThat(config.getAccessTokenValiditySeconds()).isEqualTo(40);
	assertThat(config.getRefreshTokenValiditySeconds()).isEqualTo(80);
	verifyAuthentication(config);
}
 
Example #14
Source File: AAAGuestServiceImpl.java    From spring4-rest-oauth2 with GNU General Public License v2.0 6 votes vote down vote up
@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 #15
Source File: OAuthHelper.java    From resource-server-testing with MIT License 6 votes vote down vote up
public OAuth2Authentication oAuth2Authentication(final String clientId, final String username) {
	// Look up authorities, resourceIds and scopes based on clientId
	ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
	Collection<GrantedAuthority> authorities = client.getAuthorities();
	Set<String> resourceIds = client.getResourceIds();
	Set<String> scopes = client.getScope();

	// Default values for other parameters
	Map<String, String> requestParameters = Collections.emptyMap();
	boolean approved = true;
	String redirectUrl = null;
	Set<String> responseTypes = Collections.emptySet();
	Map<String, Serializable> extensionProperties = Collections.emptyMap();

	// Create request
	OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities, approved, scopes, resourceIds, redirectUrl, responseTypes, extensionProperties);

	// Create OAuth2AccessToken
	UserDetails user = userDetailsService.loadUserByUsername(username);
	UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, authorities);
	OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);
	return auth;
}
 
Example #16
Source File: OAuth2AutoConfigurationTests.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsr250SecurityAnnotationOverride() {
	this.context = new AnnotationConfigServletWebServerApplicationContext();
	this.context.register(Jsr250EnabledConfiguration.class, MinimalSecureWebApplication.class);
	this.context.refresh();
	this.context.getBean(OAuth2MethodSecurityConfiguration.class);
	ClientDetails config = this.context.getBean(ClientDetails.class);
	DelegatingMethodSecurityMetadataSource source = this.context
			.getBean(DelegatingMethodSecurityMetadataSource.class);
	List<MethodSecurityMetadataSource> sources = source.getMethodSecurityMetadataSources();
	assertThat(sources.size()).isEqualTo(1);
	assertThat(sources.get(0).getClass().getName()).isEqualTo(Jsr250MethodSecurityMetadataSource.class.getName());
	verifyAuthentication(config, HttpStatus.OK);
}
 
Example #17
Source File: FieldUtil.java    From watchdog-spring-boot-starter with MIT License 5 votes vote down vote up
public static String getAutoApproveScopes(ClientDetails clientDetails) {
    if (clientDetails.isAutoApprove("true")) {
        return "true"; // all scopes autoapproved
    }
    Set<String> scopes = new HashSet<String>();
    for (String scope : clientDetails.getScope()) {
        if (clientDetails.isAutoApprove(scope)) {
            scopes.add(scope);
        }
    }
    return StringUtils.collectionToCommaDelimitedString(scopes);
}
 
Example #18
Source File: UacPermissionServiceImpl.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasPermission(Authentication authentication, HttpServletRequest request) {
	String currentLoginName = SecurityUtils.getCurrentLoginName();
	Set<String> currentAuthorityUrl = SecurityUtils.getCurrentAuthorityUrl();
	String requestURI = request.getRequestURI();
	log.info("验证权限loginName={}, requestURI={}, hasAuthorityUrl={}", currentLoginName, requestURI, Joiner.on(GlobalConstant.Symbol.COMMA).join(currentAuthorityUrl));
	// 超级管理员 全部都可以访问
	if (StringUtils.equals(currentLoginName, GlobalConstant.Sys.SUPER_MANAGER_LOGIN_NAME)) {
		return true;
	}

	// DEMO项目Feign客户端具有所有权限, 如果需要则在角色权限中控制
	if (currentLoginName.contains(OAUTH2_CLIENT_PREFIX)) {
		ClientDetails clientDetails = clientDetailsService.loadClientByClientId(currentLoginName);
		return clientDetails != null;
	}

	for (final String authority : currentAuthorityUrl) {
		// DEMO项目放过查询权限
		if (requestURI.contains("query") || requestURI.contains("get") || requestURI.contains("check") || requestURI.contains("select")) {
			return true;
		}
		if (antPathMatcher.match(authority, requestURI)) {
			return true;
		}
	}
	return false;
}
 
Example #19
Source File: OAuth2AutoConfigurationTests.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
private HttpHeaders getHeaders(ClientDetails config) {
	HttpHeaders headers = new HttpHeaders();
	String token = new String(
			Base64.getEncoder().encode((config.getClientId() + ":" + config.getClientSecret()).getBytes()));
	headers.set("Authorization", "Basic " + token);
	return headers;
}
 
Example #20
Source File: BootClientDetailsService.java    From oauth-boot with 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 #21
Source File: OAuth2Configuration.java    From microservices-oauth with Apache License 2.0 5 votes vote down vote up
@Override
public TokenRequest createTokenRequest(Map<String, String> requestParameters,
		ClientDetails authenticatedClient) {
	if (requestParameters.get("grant_type").equals("refresh_token")) {
		OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(
				tokenStore.readRefreshToken(requestParameters.get("refresh_token")));
		SecurityContextHolder.getContext()
				.setAuthentication(new UsernamePasswordAuthenticationToken(authentication.getName(), null,
						userDetailsService.loadUserByUsername(authentication.getName()).getAuthorities()));
	}
	return super.createTokenRequest(requestParameters, authenticatedClient);
}
 
Example #22
Source File: CustomClientDetailsService.java    From oauth-server with Apache License 2.0 5 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String name) {
    ClientE clientE = this.selectByName(name);
    if (clientE == null) {
        throw new NoSuchClientException("No client found : " + name);
    }
    CustomClientDetails clientDetails = new CustomClientDetails();
    clientDetails.setAuthorizedGrantTypes(StringUtils
            .commaDelimitedListToSet(clientE.getAuthorizedGrantTypes()));
    clientDetails.setClientId(clientE.getName());
    clientDetails.setClientSecret(clientE.getSecret());
    clientDetails.setResourceIds(StringUtils.commaDelimitedListToSet(clientE.getResourceIds()));
    clientDetails.setScope(StringUtils.commaDelimitedListToSet(clientE.getScope()));
    clientDetails.setRegisteredRedirectUri(StringUtils
            .commaDelimitedListToSet(clientE.getWebServerRedirectUri()));
    clientDetails.setAuthorities(Collections.emptyList());
    int accessTokenValidity = clientE.getAccessTokenValidity() != null ? clientE.getAccessTokenValidity().intValue() : 3600;
    clientDetails.setAccessTokenValiditySeconds(accessTokenValidity);
    int refreshTokenValidity = clientE.getRefreshTokenValidity() != null ? clientE.getRefreshTokenValidity().intValue() : 3600;
    clientDetails.setRefreshTokenValiditySeconds(refreshTokenValidity);
    clientDetails.setOrganizationId(1L);
    String json = clientE.getAdditionalInformation();
    if (json != null) {
        try {
            Map<String, Object> additionalInformation = mapper.readValue(json, Map.class);
            clientDetails.setAdditionalInformation(additionalInformation);
        } catch (Exception e) {
            LOGGER.warn("parser addition info error: {}", e);
        }
    }
    clientDetails.setAutoApproveScopes(StringUtils.commaDelimitedListToSet(clientE.getAutoApprove()));
    return clientDetails;
}
 
Example #23
Source File: EspiUserApprovalHandler.java    From OpenESPI-DataCustodian-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #24
Source File: MongoClientDetailsServiceTest.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Test(expected = NoSuchClientException.class)
public void shouldNotUpdateClientDetailsWhenClientIdIsNotValid() throws NoSuchClientException {
    //Given
    final ClientDetails clientDetails = ClientDetailsBuilder.clientDetailsBuilder().build();

    //And
    given(mongoClientDetailsRepository.update(any(MongoClientDetails.class))).willReturn(false);

    //When
    mongoClientDetailsService.updateClientDetails(clientDetails);
}
 
Example #25
Source File: OAuthConsumerManagerTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #26
Source File: FieldUtil.java    From watchdog-spring-boot-starter with MIT License 5 votes vote down vote up
public static <T extends ClientDetails> Object[] getFields(T clientDetails, PasswordEncoder passwordEncoder) {
        Object[] fieldsForUpdate = getFieldsForUpdate(clientDetails);
        Object[] fields = new Object[fieldsForUpdate.length + 1];
        System.arraycopy(fieldsForUpdate, 0, fields, 1, fieldsForUpdate.length);
        fields[0] = clientDetails.getClientSecret() != null ? passwordEncoder.encode(clientDetails.getClientSecret())
                : null;
//        if(clientDetails instanceof Application){
//            fields[fields.length - 1] = fields[fields.length - 2];
//            fields[fields.length - 2] = ((Application) clientDetails).getName();
//        }
        return fields;
    }
 
Example #27
Source File: DefaultApplicationRepositoryImpl.java    From watchdog-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
public Application update(ClientDetails application) {
    int count = jdbcTemplate.update(updateApplicationSql, getFieldsForUpdate(application));
    if (count != 1) {
        throw new NoSuchClientException("No client found with id = " + application.getClientId());
    }
    return findByClientId(application.getClientId()).get();
}
 
Example #28
Source File: MongoClientDetailsServiceIntegrationTest.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Test
public void shouldGetListOfClientDetailsByIdSuccessfully() {
    //Given
    final MongoClientDetails clientDetails = MongoClientDetailsBuilder.mongoClientDetailsBuilder().build();

    //And
    mongoClientDetailsService.addClientDetails(clientDetails);

    //When
    final List<ClientDetails> expectedClientDetails = mongoClientDetailsService.listClientDetails();

    //Then
    assertThat(expectedClientDetails).contains(clientDetails);
}
 
Example #29
Source File: OAuthConsumerManagerTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #30
Source File: SophiaClientDetailsService.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
@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;
}