org.springframework.security.oauth2.provider.client.BaseClientDetails Java Examples

The following examples show how to use org.springframework.security.oauth2.provider.client.BaseClientDetails. 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: ClientController.java    From spring-oauth-example with MIT License 6 votes vote down vote up
/**
 * Create/update a client from the form.
 * @param clientDetails The model to create/update.
 * @param newClient Indicates if this is a new client. If null it's an existing client.
 * @return redirects to the root.
 */
@PostMapping(value = "/edit")
@PreAuthorize("hasRole('ROLE_OAUTH_ADMIN')")
public String editClient(
        @ModelAttribute BaseClientDetails clientDetails,
        @RequestParam(value = "newClient", required = false) String newClient
        ) {
    if (newClient == null) {
        //does not update the secret!
        // TODO: delete tokens and approvals
        clientDetailsService.updateClientDetails(clientDetails);
    } else {
        clientDetailsService.addClientDetails(clientDetails);
    }

    // If the user has entered a secret in the form update it.
    if (!clientDetails.getClientSecret().isEmpty()) {
        clientDetailsService.updateClientSecret(clientDetails.getClientId(), clientDetails.getClientSecret());
    }
    return "redirect:/";
}
 
Example #2
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 #3
Source File: OAuth2AuthorizationServerConfig.java    From NFVO with Apache License 2.0 6 votes vote down vote up
/**
 * Method for generating an OAuth2 token for services. The token's (and refresh token's) validity
 * duration is longer than for normal users.
 *
 * @param serviceName
 * @return the oauth2 service token
 */
public OAuth2AccessToken getNewServiceToken(String serviceName) {
  Set<GrantedAuthority> authorities = new HashSet<>();
  authorities.add(new SimpleGrantedAuthority("ADMIN"));

  OAuth2Request oAuth2Request = buildOAuth2Request(serviceName, authorities);
  User userPrincipal =
      new User(serviceName, "" + Math.random() * 1000, true, true, true, true, authorities);

  UsernamePasswordAuthenticationToken authenticationToken =
      new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities);
  OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);

  BaseClientDetails externalServiceClientDetails = buildExternalServiceClientDetails(serviceName);
  customClientDetailsService.addclientDetails(externalServiceClientDetails);

  OAuth2AccessToken token = serviceTokenServices.createAccessToken(auth);
  log.trace("New Service token: " + token);
  return token;
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
Source File: BaseAppServiceImpl.java    From open-cloud with MIT License 6 votes vote down vote up
/**
 * 修改应用
 *
 * @param app 应用
 * @return 应用信息
 */
@Caching(evict = {
        @CacheEvict(value = {"apps"}, key = "#app.appId"),
        @CacheEvict(value = {"apps"}, key = "'client:'+#app.appId")
})
@Override
public BaseApp updateInfo(BaseApp app) {
    app.setUpdateTime(new Date());
    baseAppMapper.updateById(app);
    // 修改客户端附加信息
    BaseApp appInfo = getAppInfo(app.getAppId());
    Map info = BeanConvertUtils.objectToMap(appInfo);
    BaseClientDetails client = (BaseClientDetails) jdbcClientDetailsService.loadClientByClientId(appInfo.getApiKey());
    client.setAdditionalInformation(info);
    jdbcClientDetailsService.updateClientDetails(client);
    return app;
}
 
Example #9
Source File: LoginAuthSuccessHandler.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Called when a user has been successfully authenticated.
 * 调用spring security oauth API 生成 oAuth2AccessToken
 *
 * @param request        the request which caused the successful authentication
 * @param response       the response
 * @param authentication the <tt>Authentication</tt> object which was created during
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

    try {

        TokenRequest tokenRequest = new TokenRequest(null, null, null, null);

        // 简化
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(new BaseClientDetails());
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);


        OAuth2AccessToken oAuth2AccessToken = yamiTokenServices.createAccessToken(oAuth2Authentication);
        log.info("获取token 成功:{}", oAuth2AccessToken.getValue());

        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
    } catch (IOException e) {
        throw new BadCredentialsException(
                "Failed to decode basic authentication token");
    }

}
 
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: RedisClientDetailsService.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
    ClientDetails clientDetails = null;

    // 先从redis获取
    String value = (String) redisTemplate.boundHashOps(CACHE_CLIENT_KEY).get(clientId);
    if (StringUtils.isBlank(value)) {
        clientDetails = cacheAndGetClient(clientId);
    } else {
        clientDetails = JSONObject.parseObject(value, BaseClientDetails.class);
    }

    return clientDetails;
}
 
Example #12
Source File: UaaClientOperationTest.java    From uaa-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetClients() throws Exception {

	SearchResults<BaseClientDetails> clients = operations.getClients(FilterRequestBuilder.showAll());

	assertEquals("Total Results wrong", 12, clients.getTotalResults()); // default 11 + test client 1 = 12 clients
	assertEquals("Items Per Page wrong", 12, clients.getItemsPerPage());
	assertEquals("Actual result count wrong", 12, clients.getResources().size());
}
 
Example #13
Source File: UaaClientOperationTest.java    From uaa-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetClient() throws Exception {

	BaseClientDetails client = operations.findById("app");

	assertEquals("ID wrong", "app", client.getClientId());
	assertNull("Secret should not be returned", client.getClientSecret());
}
 
Example #14
Source File: UaaClientOperationTest.java    From uaa-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateDelete() throws Exception {

	BaseClientDetails checkClient = operations.findById(testClient.getClientId());
	assertEquals(testClient.getClientId(), checkClient.getClientId());

	operations.delete(checkClient.getClientId());
}
 
Example #15
Source File: UaaClientOperationTest.java    From uaa-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdate() throws Exception {

	BaseClientDetails client = operations.findById(testClient.getClientId());

	client.setScope(Arrays.asList("foo"));
	BaseClientDetails updated = operations.update(client);

	assertNotEquals(testClient.getScope(), updated.getScope());
	assertEquals(client.getScope().iterator().next(), updated.getScope().iterator().next());
}
 
Example #16
Source File: OAuth2AuthorizationServerConfig.java    From NFVO with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(ClientDetailsServiceConfigurer client) throws Exception {
  customClientDetailsService = new CustomClientDetailsService();
  BaseClientDetails openbatonOSClient = buildOpenBatonOSClient();
  customClientDetailsService.addclientDetails(openbatonOSClient);
  client.withClientDetails(customClientDetailsService);
}
 
Example #17
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 #18
Source File: ClientController.java    From cloud-service with MIT License 5 votes vote down vote up
@PreAuthorize("hasAuthority('client:update')")
@LogAnnotation(module = "修改client")
@PutMapping
public void update(@RequestBody BaseClientDetails clientDetails) {
    getAndCheckClient(clientDetails.getClientId(), true);
    clientDetailsService.updateClientDetails(clientDetails);
    log.info("修改client信息:{}", clientDetails);
}
 
Example #19
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 #20
Source File: ClientDetailsServiceImpl.java    From springcloud-oauth2 with 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 #21
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 #22
Source File: Oauth2AuthorizationServerConfig.java    From spring-security-oauth2-demo with GNU General Public License v3.0 5 votes vote down vote up
private void configClient(ClientDetailsServiceConfigurer clients) throws Exception {
    InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
    for (BaseClientDetails client : clientDetails.getClient()) {
        ClientDetailsServiceBuilder<InMemoryClientDetailsServiceBuilder>.ClientBuilder clientBuilder =
                builder.withClient(client.getClientId());
        clientBuilder
                .secret(client.getClientSecret())
                .resourceIds(client.getResourceIds().toArray(new String[0]))
                .authorizedGrantTypes(client.getAuthorizedGrantTypes().toArray(new String[0]))
                .authorities(
                        AuthorityUtils.authorityListToSet(client.getAuthorities())
                                .toArray(new String[0]))
                .scopes(client.getScope().toArray(new String[0]));
        if (client.getAutoApproveScopes() != null) {
            clientBuilder.autoApprove(
                    client.getAutoApproveScopes().toArray(new String[0]));
        }
        if (client.getAccessTokenValiditySeconds() != null) {
            clientBuilder.accessTokenValiditySeconds(
                    client.getAccessTokenValiditySeconds());
        }
        if (client.getRefreshTokenValiditySeconds() != null) {
            clientBuilder.refreshTokenValiditySeconds(
                    client.getRefreshTokenValiditySeconds());
        }
        if (client.getRegisteredRedirectUri() != null) {
            clientBuilder.redirectUris(
                    client.getRegisteredRedirectUri().toArray(new String[0]));
        }
    }
}
 
Example #23
Source File: RedisClientDetailsService.java    From cloud-service with MIT License 5 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
    ClientDetails clientDetails = null;

    // 先从redis获取
    String value = (String) stringRedisTemplate.boundHashOps(CACHE_CLIENT_KEY).get(clientId);
    if (StringUtils.isBlank(value)) {
        clientDetails = cacheAndGetClient(clientId);
    } else {
        clientDetails = JSONObject.parseObject(value, BaseClientDetails.class);
    }

    return clientDetails;
}
 
Example #24
Source File: ClientController.java    From cloud-service with MIT License 5 votes vote down vote up
/**
 * 判断是否是我们自己系统内部用的client<br>
 * 在扩展字段里放一个isSystem标注一下
 *
 * @param clientDetails
 * @see SystemClientInfo
 */
private boolean isSystemClient(ClientDetails clientDetails) {
    BaseClientDetails baseClientDetails = (BaseClientDetails) clientDetails;
    Map<String, Object> additionalInformation = baseClientDetails.getAdditionalInformation();
    if (additionalInformation == null) {
        additionalInformation = new HashMap<>();
        baseClientDetails.setAdditionalInformation(additionalInformation);
    }

    boolean isSystem = SystemClientInfo.CLIENT_ID.equalsIgnoreCase(baseClientDetails.getClientId());
    baseClientDetails.addAdditionalInformation("isSystem", isSystem);

    return isSystem;
}
 
Example #25
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 #26
Source File: RedisClientDetailsService.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@Override
public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
    ClientDetails clientDetails = null;
    String value = (String) redisService.hget(CACHE_CLIENT_KEY, clientId);
    if (StringUtils.isBlank(value)) {
        clientDetails = cacheAndGetClient(clientId);
    } else {
        clientDetails = JSONObject.parseObject(value, BaseClientDetails.class);
    }

    return clientDetails;
}
 
Example #27
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 #28
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 #29
Source File: AuthorizationServerConfiguration.java    From openapi-petstore with Apache License 2.0 5 votes vote down vote up
public AuthorizationServerConfiguration(BaseClientDetails details,
                                        AuthenticationConfiguration authenticationConfiguration,
                                        ObjectProvider<TokenStore> tokenStore,
                                        ObjectProvider<AccessTokenConverter> tokenConverter,
                                        AuthorizationServerProperties properties) throws Exception {
    super(details, authenticationConfiguration, tokenStore, tokenConverter, properties);
}
 
Example #30
Source File: OAuth2AuthorizationServerConfiguration.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
public AuthorizationSecurityConfigurer(BaseClientDetails details,
		AuthenticationConfiguration authenticationConfiguration, ObjectProvider<TokenStore> tokenStore,
		ObjectProvider<AccessTokenConverter> tokenConverter, AuthorizationServerProperties properties)
		throws Exception {

	this.details = details;
	this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
	this.tokenStore = tokenStore.getIfAvailable();
	this.tokenConverter = tokenConverter.getIfAvailable();
	this.properties = properties;
}