Java Code Examples for org.springframework.security.oauth2.provider.client.BaseClientDetails#setClientSecret()

The following examples show how to use org.springframework.security.oauth2.provider.client.BaseClientDetails#setClientSecret() . 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: OAuth2AutoConfigurationTests.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorizationServerOverride() {
	this.context = new AnnotationConfigServletWebServerApplicationContext();
	TestPropertyValues.of("security.oauth2.resourceId:resource-id").applyTo(this.context);
	this.context.register(AuthorizationAndResourceServerConfiguration.class, CustomAuthorizationServer.class,
			MinimalSecureWebApplication.class);
	this.context.refresh();
	BaseClientDetails config = new BaseClientDetails();
	config.setClientId("client");
	config.setClientSecret("secret");
	config.setResourceIds(Arrays.asList("resource-id"));
	config.setAuthorizedGrantTypes(Arrays.asList("password"));
	config.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("USER"));
	config.setScope(Arrays.asList("read"));
	assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1);
	assertThat(countBeans(CustomAuthorizationServer.class)).isEqualTo(1);
	assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1);
	verifyAuthentication(config);
}
 
Example 2
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 3
Source File: UaaClientOperationTest.java    From uaa-java-client with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {

	operations = getConnection().clientOperations();

	try {
		operations.delete("test");
	} catch (Exception ignore) {}

	testClientDetails = new BaseClientDetails();
	testClientDetails.setClientId("test");
	testClientDetails.setClientSecret("testsecret");
	testClientDetails.setAccessTokenValiditySeconds(3600);
	testClientDetails.setAuthorizedGrantTypes(Arrays.asList(UaaTokenGrantType.authorization_code.toString(),
			UaaTokenGrantType.client_credentials.toString()));
	testClientDetails.setRefreshTokenValiditySeconds(86400);
	testClientDetails.setAuthorities(AuthorityUtils.createAuthorityList("uaa.resource", "clients.secret"));

	testClient = operations.create(testClientDetails);
}
 
Example 4
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 5
Source File: ClientController.java    From cloud-service with MIT License 5 votes vote down vote up
@PreAuthorize("hasAuthority('client:save')")
@LogAnnotation(module = "保存client")
@PostMapping
public void save(@RequestBody BaseClientDetails clientDetails) {
    ClientDetails client = getAndCheckClient(clientDetails.getClientId(), false);
    if (client != null) {
        throw new IllegalArgumentException(clientDetails.getClientId() + "已存在");
    }
    // 密码加密
    clientDetails.setClientSecret(passwordEncoder.encode(clientDetails.getClientSecret()));

    clientDetailsService.addClientDetails(clientDetails);
    log.info("保存client信息:{}", clientDetails);
}
 
Example 6
Source File: BaseAppServiceImpl.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 添加应用
 *
 * @param app
 * @return 应用信息
 */
@CachePut(value = "apps", key = "#app.appId")
@Override
public BaseApp addAppInfo(BaseApp app) {
    String appId = String.valueOf(System.currentTimeMillis());
    String apiKey = RandomValueUtils.randomAlphanumeric(24);
    String secretKey = RandomValueUtils.randomAlphanumeric(32);
    app.setAppId(appId);
    app.setApiKey(apiKey);
    app.setSecretKey(secretKey);
    app.setCreateTime(new Date());
    app.setUpdateTime(app.getCreateTime());
    if (app.getIsPersist() == null) {
        app.setIsPersist(0);
    }
    baseAppMapper.insert(app);
    Map info = BeanConvertUtils.objectToMap(app);
    // 功能授权
    BaseClientDetails client = new BaseClientDetails();
    client.setClientId(app.getApiKey());
    client.setClientSecret(app.getSecretKey());
    client.setAdditionalInformation(info);
    client.setAuthorizedGrantTypes(Arrays.asList("authorization_code", "client_credentials", "implicit", "refresh_token"));
    client.setAccessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS);
    client.setRefreshTokenValiditySeconds(REFRESH_TOKEN_VALIDITY_SECONDS);
    jdbcClientDetailsService.addClientDetails(client);
    return app;
}
 
Example 7
Source File: SysClientDetailService.java    From springcloud-oauth2 with MIT License 5 votes vote down vote up
/**
 * 根据客户端id查询
 * @param clientId
 * @return org.springframework.security.oauth2.provider.client.BaseClientDetails
 */
public BaseClientDetails selectById(String clientId) {
    BaseClientDetails clientDetails = new BaseClientDetails();
    clientDetails.setAuthorities(new ArrayList<>());
    clientDetails.setClientId("yaohw");
    // 这个客户端秘钥和密码一样存BCryptPasswordEncoder加密后的接口,具体看定义的加密器
    clientDetails.setClientSecret("$2a$10$CwIutywnbs9bifHaY3Ezu.gYkWi4Zano8gVPq08hXjal6.uj.Yzuy");
    // 设置accessToken和refreshToken的时效,如果不设置则使tokenServices的配置的
    clientDetails.setAccessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(2));
    clientDetails.setRefreshTokenValiditySeconds((int)TimeUnit.DAYS.toSeconds(30));
    // 资源id列表,需要注意的是这里配置的需要与ResourceServerConfig中配置的相匹配
    List<String> resourceIds = new ArrayList<>();
    resourceIds.add("auth-server");
    resourceIds.add("resource-server");
    clientDetails.setResourceIds(resourceIds);
    List<String> scopes = new ArrayList<>(1);
    scopes.add("sever");
    clientDetails.setScope(scopes);
    List<String> grantTypes = new ArrayList<>(5);
    grantTypes.add("password");
    grantTypes.add("refresh_token");
    grantTypes.add("authorization_code");
    grantTypes.add("implicit");
    grantTypes.add("mobile");
    clientDetails.setAuthorizedGrantTypes(grantTypes);
    Set<String> sets = new HashSet<>(1);
    sets.add("http://www.baidu.com");
    clientDetails.setRegisteredRedirectUri(sets);
    List<String> autoApproveScopes = new ArrayList<>(1);
    autoApproveScopes.add("sever");
    // 自动批准作用于,授权码模式时使用,登录验证后直接返回code,不再需要下一步点击授权
    clientDetails.setAutoApproveScopes(autoApproveScopes);
    return clientDetails;
}
 
Example 8
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;
}
 
Example 9
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;
}
 
Example 10
Source File: OAuth2AuthorizationServerConfiguration.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "security.oauth2.client")
public BaseClientDetails oauth2ClientDetails() {
	BaseClientDetails details = new BaseClientDetails();
	if (this.client.getClientId() == null) {
		this.client.setClientId(UUID.randomUUID().toString());
	}
	details.setClientId(this.client.getClientId());
	details.setClientSecret(this.client.getClientSecret());
	details.setAuthorizedGrantTypes(Arrays.asList("authorization_code", "password", "client_credentials",
			"implicit", "refresh_token"));
	details.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
	details.setRegisteredRedirectUri(Collections.<String>emptySet());
	return details;
}
 
Example 11
Source File: OAuth2AuthorizationServerConfig.java    From NFVO with Apache License 2.0 5 votes vote down vote up
private BaseClientDetails buildOpenBatonOSClient() {
  BaseClientDetails openbatonOSClient =
      new BaseClientDetails(
          "openbatonOSClient", RESOURCE_ID, "read,write", "refresh_token,password", "ADMIN");
  openbatonOSClient.setClientSecret("secret");
  openbatonOSClient.setAccessTokenValiditySeconds(userTokenValidityDuration);
  return openbatonOSClient;
}
 
Example 12
Source File: IClientServiceImpl.java    From open-capacity-platform with Apache License 2.0 3 votes vote down vote up
private void updateClient(Client client, List<Long> permissionIds) {
//		Client r = clientDao.getClient(client.getClientId());
//		if (r != null && r.getId() != client.getId()) {
//			throw new IllegalArgumentException(client.getClientId() + "已存在");
//		}

        clientDao.update(client);


        clientDao.deleteClientPermission(client.getId());
        if (!CollectionUtils.isEmpty(permissionIds)) {
            clientDao.saveClientPermission(client.getId(), permissionIds);
        }

        String clientId = clientDao.getById(client.getId()).getClientId();

        BaseClientDetails clientDetails = null;

        // 先从redis获取
        try {
            String value = (String) redisTemplate.boundHashOps(CACHE_CLIENT_KEY).get(clientId);
            clientDetails = JSONObject.parseObject(value, BaseClientDetails.class);
            clientDetails.setClientSecret(client.getClientSecret());
            redisTemplate.boundHashOps(CACHE_CLIENT_KEY).put(clientId, JSONObject.toJSONString(clientDetails));


        } catch (Exception e) {

        }


        log.debug("修改应用{}", client.getClientId());
    }