Java Code Examples for org.springframework.security.oauth2.client.OAuth2RestTemplate#getAccessToken()
The following examples show how to use
org.springframework.security.oauth2.client.OAuth2RestTemplate#getAccessToken() .
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: DataFlowClientAutoConfigurationAgaintstServerTests.java From spring-cloud-dataflow with Apache License 2.0 | 6 votes |
@Test public void usingUserWithViewRoles() throws Exception { final ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails(); resourceDetails.setClientId("myclient"); resourceDetails.setClientSecret("mysecret"); resourceDetails.setUsername("bob"); resourceDetails.setPassword("bobspassword"); resourceDetails .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token"); final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken(); System.setProperty("accessTokenAsString", accessToken.getValue()); context = new AnnotationConfigApplicationContext(TestApplication.class); final DataFlowOperations dataFlowOperations = context.getBean(DataFlowOperations.class); final AboutResource about = dataFlowOperations.aboutOperation().get(); assertNotNull(about); assertEquals("bob", about.getSecurityInfo().getUsername()); assertEquals(1, about.getSecurityInfo().getRoles().size()); }
Example 2
Source File: DataFlowClientAutoConfigurationAgaintstServerTests.java From spring-cloud-dataflow with Apache License 2.0 | 6 votes |
@Test public void usingUserWithAllRoles() throws Exception { final ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails(); resourceDetails.setClientId("myclient"); resourceDetails.setClientSecret("mysecret"); resourceDetails.setUsername("user"); resourceDetails.setPassword("secret10"); resourceDetails .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token"); final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken(); System.setProperty("accessTokenAsString", accessToken.getValue()); context = new AnnotationConfigApplicationContext(TestApplication.class); final DataFlowOperations dataFlowOperations = context.getBean(DataFlowOperations.class); final AboutResource about = dataFlowOperations.aboutOperation().get(); assertNotNull(about); assertEquals("user", about.getSecurityInfo().getUsername()); assertEquals(7, about.getSecurityInfo().getRoles().size()); }
Example 3
Source File: OAuth2RestTemplateConfigurer.java From spring-oauth2-keycloak-connector with Apache License 2.0 | 6 votes |
@Bean public OAuth2RestTemplate oauth2RestTemplate(OAuth2ProtectedResourceDetails details) { OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(details); LOG.debug("Begin OAuth2RestTemplate: getAccessToken"); /* To validate if required configurations are in place during startup */ oAuth2RestTemplate.getAccessToken(); LOG.debug("End OAuth2RestTemplate: getAccessToken"); return oAuth2RestTemplate; }
Example 4
Source File: LocalServerSecurityWithOAuth2Tests.java From spring-cloud-skipper with Apache License 2.0 | 6 votes |
@Test public void testAccessRootUrlWithOAuth2AccessToken() throws Exception { final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); resourceDetails.setClientId("myclient"); resourceDetails.setClientSecret("mysecret"); resourceDetails.setGrantType("client_credentials"); resourceDetails .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token"); final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken(); final String accessTokenAsString = accessToken.getValue(); localSkipperResource.getMockMvc().perform(get("/api").header("Authorization", "bearer " + accessTokenAsString)) .andDo(print()).andExpect(status().isOk()); }
Example 5
Source File: LocalServerSecurityWithOAuth2Tests.java From spring-cloud-skipper with Apache License 2.0 | 6 votes |
@Test public void testAccessAboutUrlWithOAuth2AccessToken() throws Exception { final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); resourceDetails.setClientId("myclient"); resourceDetails.setClientSecret("mysecret"); resourceDetails.setGrantType("client_credentials"); resourceDetails .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token"); final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken(); final String accessTokenAsString = accessToken.getValue(); localSkipperResource.getMockMvc() .perform(get("/api/about").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.versionInfo.server.name", is("Spring Cloud Skipper Server"))) .andExpect(jsonPath("$.versionInfo.server.version", notNullValue())); }
Example 6
Source File: Oauth2ClientRestTemplateTest.java From spring-boot with Apache License 2.0 | 6 votes |
@Test public void testClientCredentialsRestTemplate() throws Exception { ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails(); details.setId("4"); details.setClientId(client_id); details.setClientSecret(client_secret); details.setAccessTokenUri(access_token_uri); // details.setScope(Arrays.asList("read write")); OAuth2RestTemplate operations = new OAuth2RestTemplate(details,new DefaultOAuth2ClientContext()); // OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); operations.setAccessTokenProvider(new ClientCredentialsAccessTokenProvider()); // OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails(),oAuth2ClientContext()); DefaultOAuth2AccessToken token=(DefaultOAuth2AccessToken)operations.getAccessToken(); token.setTokenType("Bearer"); System.out.println("client_id : " + client_id); System.out.println("source_url : " + source_url); // OAuth2RestOperations operations = restTemplate.clientCredentialsRestTemplate(client_id, client_secret, access_token_uri, scopes); // getForObject 发送 get 方法 System.out.println(JSON.toJSONString(operations.getForObject(source_url, JsonNode.class))); // getForObject 发送 get 方法 }
Example 7
Source File: LocalServerSecurityWithOAuth2Tests.java From spring-cloud-dataflow with Apache License 2.0 | 6 votes |
@Test public void testAccessRootUrlWithOAuth2AccessToken() throws Exception { final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); resourceDetails.setClientId("myclient"); resourceDetails.setClientSecret("mysecret"); resourceDetails.setGrantType("client_credentials"); resourceDetails .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token"); final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken(); final String accessTokenAsString = accessToken.getValue(); localDataflowResource.getMockMvc().perform(get("/").header("Authorization", "bearer " + accessTokenAsString)) .andDo(print()).andExpect(status().isOk()); }
Example 8
Source File: LocalServerSecurityWithOAuth2Tests.java From spring-cloud-dataflow with Apache License 2.0 | 6 votes |
@Test public void testAccessSecurityInfoUrlWithOAuth2AccessToken() throws Exception { final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); resourceDetails.setClientId("myclient"); resourceDetails.setClientSecret("mysecret"); resourceDetails.setGrantType("client_credentials"); resourceDetails .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token"); final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken(); final String accessTokenAsString = accessToken.getValue(); localDataflowResource.getMockMvc() .perform(get("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.authenticated", is(Boolean.TRUE))) .andExpect(jsonPath("$.authenticationEnabled", is(Boolean.TRUE))) .andExpect(jsonPath("$.roles", hasSize(7))); }
Example 9
Source File: CustomConfigAuthorizationServerIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() { ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read")); OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); OAuth2AccessToken accessToken = restTemplate.getAccessToken(); assertNotNull(accessToken); }
Example 10
Source File: SsoAuthClient.java From cola with MIT License | 5 votes |
/** * 登录 * * @param username * @param password * @return */ public OAuth2AccessToken login(String username, String password) { ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails(); details.setUsername(username); details.setPassword(password); details.setAccessTokenUri(this.properties.getAccessTokenUri()); details.setClientId(this.properties.getClientId()); details.setClientSecret(this.properties.getClientSecret()); OAuth2RestTemplate auth2RestTemplate = new OAuth2RestTemplate(details); auth2RestTemplate.setAccessTokenProvider(new ResourceOwnerPasswordAccessTokenProvider()); return auth2RestTemplate.getAccessToken(); }
Example 11
Source File: LocalServerSecurityWithOAuth2AndExternalAuthoritiesTests.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
@Test public void testDataflowCallingExternalAuthoritiesServer() throws Exception { final String[] roles = {"VIEW", "CREATE", "MANAGE"}; final ObjectMapper objectMapper = new ObjectMapper(); externalAuthoritiesServer.enqueue(new MockResponse() .setBody(objectMapper.writeValueAsString(roles)) .addHeader("Content-Type", "application/json")); final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); resourceDetails.setClientId("myclient"); resourceDetails.setClientSecret("mysecret"); resourceDetails.setGrantType("client_credentials"); resourceDetails .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token"); Assert.assertEquals(0, externalAuthoritiesServer.getRequestCount()); final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken(); final String accessTokenAsString = accessToken.getValue(); localDataflowResource.getMockMvc() .perform(get("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.authenticated", is(Boolean.TRUE))) .andExpect(jsonPath("$.authenticationEnabled", is(Boolean.TRUE))) .andExpect(jsonPath("$.roles", hasSize(3))); assertThat(externalAuthoritiesServer.getRequestCount(), is(1)); final RecordedRequest recordedRequest = externalAuthoritiesServer.takeRequest(); assertThat(recordedRequest.getHeader("Authorization"), is("Bearer " + accessTokenAsString)); }
Example 12
Source File: LocalServerSecurityWithOAuth2Tests.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
@Test public void testAccessSecurityInfoUrlWithOAuth2AccessToken2TimesAndLogout() throws Exception { final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); resourceDetails.setClientId("myclient"); resourceDetails.setClientSecret("mysecret"); resourceDetails.setGrantType("client_credentials"); resourceDetails .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token"); final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken(); final String accessTokenAsString = accessToken.getValue(); localDataflowResource.getMockMvc() .perform(get("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.authenticated", is(Boolean.TRUE))) .andExpect(jsonPath("$.authenticationEnabled", is(Boolean.TRUE))) .andExpect(jsonPath("$.roles", hasSize(7))); boolean oAuthServerResponse = oAuth2RestTemplate.getForObject("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/revoke_token", Boolean.class); assertTrue(Boolean.valueOf(oAuthServerResponse)); localDataflowResource.getMockMvc() .perform(get("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isUnauthorized()); localDataflowResource.getMockMvc() .perform(get("/logout").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isFound()); localDataflowResource.getMockMvc() .perform(get("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isUnauthorized()); }
Example 13
Source File: LocalServerSecurityWithOAuth2Tests.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
@Test public void testAccessSecurityInfoUrlWithOAuth2AccessTokenPasswordGrant2Times() throws Exception { final ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails(); resourceDetails.setClientId("myclient"); resourceDetails.setClientSecret("mysecret"); resourceDetails.setUsername("user"); resourceDetails.setPassword("secret10"); resourceDetails .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token"); final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken(); final String accessTokenAsString = accessToken.getValue(); localDataflowResource.getMockMvc() .perform(get("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.authenticated", is(Boolean.TRUE))) .andExpect(jsonPath("$.authenticationEnabled", is(Boolean.TRUE))) .andExpect(jsonPath("$.roles", hasSize(7))); localDataflowResource.getMockMvc() .perform(get("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.authenticated", is(Boolean.TRUE))) .andExpect(jsonPath("$.authenticationEnabled", is(Boolean.TRUE))) .andExpect(jsonPath("$.roles", hasSize(7))); }
Example 14
Source File: LocalServerSecurityWithOAuth2Tests.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
@Test public void testAccessSecurityInfoUrlWithOAuth2AccessToken2Times() throws Exception { final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); resourceDetails.setClientId("myclient"); resourceDetails.setClientSecret("mysecret"); resourceDetails .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token"); final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails); final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken(); final String accessTokenAsString = accessToken.getValue(); localDataflowResource.getMockMvc() .perform(get("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.authenticated", is(Boolean.TRUE))) .andExpect(jsonPath("$.authenticationEnabled", is(Boolean.TRUE))) .andExpect(jsonPath("$.roles", hasSize(7))); localDataflowResource.getMockMvc() .perform(get("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.authenticated", is(Boolean.TRUE))) .andExpect(jsonPath("$.authenticationEnabled", is(Boolean.TRUE))) .andExpect(jsonPath("$.roles", hasSize(7))); }
Example 15
Source File: OAuth2TokenRequestFilter.java From JuniperBot with GNU General Public License v3.0 | 5 votes |
public OAuth2AccessToken load(TokenRequestDto requestDto) { OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource); restTemplate.setAccessTokenProvider(tokenProvider); if (requestDto.getCode() != null) { AccessTokenRequest tokenRequest = restTemplate.getOAuth2ClientContext().getAccessTokenRequest(); tokenRequest.setCurrentUri(requestDto.getRedirectUri()); tokenRequest.setAuthorizationCode(requestDto.getCode()); } try { return restTemplate.getAccessToken(); } catch (OAuth2Exception e) { throw new BadCredentialsException("Could not obtain access token", e); } }
Example 16
Source File: ExecuteHandler.java From spring-cloud-shop with MIT License | 5 votes |
@Override public void execute(final String jobName, final String jobGroup) { // 1. 获取数据库执行的job任务 JobInfoMapper jobInfoMapper = ShopSpringContext.getBean(JobInfoMapper.class); JobInfo jobInfo = new JobInfo(); jobInfo.setJobName(jobName); jobInfo.setJobStatus(JobStatusEnums.NORMAL.getCode()); JobInfo selectJobInfo = jobInfoMapper.selectOne(new QueryWrapper<>(jobInfo)); // 访问的资源请求地址 if (Objects.nonNull(selectJobInfo)) { Map<String, String> paramMap = new ConcurrentHashMap<>(); String url = "http://" + selectJobInfo.getServiceName() + selectJobInfo.getServiceMethod(); if (!StringUtils.isEmpty(selectJobInfo.getParams())) { paramMap.putAll(JSON.parseObject(selectJobInfo.getParams(), Map.class)); } OAuth2RestTemplate template = ShopSpringContext.getBean(OAuth2RestTemplate.class); // 得到服务鉴权访问token OAuth2AccessToken accessToken = template.getAccessToken(); // 设置请求消息头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.setBearerAuth(accessToken.toString()); // 得到 RestTemplate 访问的负载均衡对象 RestTemplate restTemplate = ShopSpringContext.getBean("restTemplate", RestTemplate.class); ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, new HttpEntity<>(paramMap, headers), Object.class); log.info("执行服务调用结束,返回结果 result = {}", JSON.toJSONString(responseEntity)); } else { log.error("未找到执行的定时任务 jobName = {}, jobGroup = {}", jobName, jobGroup); } }
Example 17
Source File: CustomConfigAuthorizationServerIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenOAuth2Context_whenAccessTokenIsRequestedByClientWithWriteScope_ThenAccessTokenIsNotNull() { ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung-admin", singletonList("write")); OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); OAuth2AccessToken accessToken = restTemplate.getAccessToken(); assertNotNull(accessToken); }
Example 18
Source File: SsoAuthClient.java From cola with MIT License | 5 votes |
/** * 短信登录 * * @param phoneNumber 手机号码 * @param credential 验证码 * @return */ public OAuth2AccessToken loginBySms(String phoneNumber, String credential) { SmsResourceDetails details = new SmsResourceDetails(); details.setPhoneNumber(phoneNumber); details.setCredential(credential); details.setAccessTokenUri(this.properties.getAccessTokenUri()); details.setClientId(this.properties.getClientId()); details.setClientSecret(this.properties.getClientSecret()); OAuth2RestTemplate auth2RestTemplate = new OAuth2RestTemplate(details); auth2RestTemplate.setAccessTokenProvider(new SmsAccessTokenProvider()); return auth2RestTemplate.getAccessToken(); }
Example 19
Source File: SsoAuthClient.java From cola with MIT License | 5 votes |
/** * openId登录 * * @param openId openid * @param provider 供应商 * @return */ public OAuth2AccessToken loginByOpenId(String openId, String provider) { OpenIdResourceDetails details = new OpenIdResourceDetails(); details.setOpenId(openId); details.setProvider(provider); details.setAccessTokenUri(this.properties.getAccessTokenUri()); details.setClientId(this.properties.getClientId()); details.setClientSecret(this.properties.getClientSecret()); OAuth2RestTemplate auth2RestTemplate = new OAuth2RestTemplate(details); auth2RestTemplate.setAccessTokenProvider(new OpenIdAccessTokenProvider()); return auth2RestTemplate.getAccessToken(); }
Example 20
Source File: DefaultConfigAuthorizationServerIntegrationTest.java From tutorials with MIT License | 3 votes |
@Test public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() { ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("client", asList("read", "write")); OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails); OAuth2AccessToken accessToken = restTemplate.getAccessToken(); assertNotNull(accessToken); }