Java Code Examples for org.springframework.security.oauth2.common.OAuth2AccessToken#getValue()
The following examples show how to use
org.springframework.security.oauth2.common.OAuth2AccessToken#getValue() .
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: OAuth2CookieHelper.java From tutorials with MIT License | 6 votes |
/** * Create cookies using the provided values. * * @param request the request we are handling. * @param accessToken the access token and enclosed refresh token for our cookies. * @param rememberMe whether the user had originally checked "remember me". * @param result will get the resulting cookies set. */ public void createCookies(HttpServletRequest request, OAuth2AccessToken accessToken, boolean rememberMe, OAuth2Cookies result) { String domain = getCookieDomain(request); log.debug("creating cookies for domain {}", domain); Cookie accessTokenCookie = new Cookie(ACCESS_TOKEN_COOKIE, accessToken.getValue()); setCookieProperties(accessTokenCookie, request.isSecure(), domain); log.debug("created access token cookie '{}'", accessTokenCookie.getName()); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); Cookie refreshTokenCookie = createRefreshTokenCookie(refreshToken, rememberMe); setCookieProperties(refreshTokenCookie, request.isSecure(), domain); log.debug("created refresh token cookie '{}', age: {}", refreshTokenCookie.getName(), refreshTokenCookie .getMaxAge()); result.setCookies(accessTokenCookie, refreshTokenCookie); }
Example 2
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 3
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 4
Source File: OAuth2AuthorizationServerConfig.java From NFVO with Apache License 2.0 | 6 votes |
/** * Method returns a token that can be used to request a specific image file contained in the * NFVImage repository from the REST API. * * @param imageId ID of the image that can be retrieved with the token * @return the oauth2 token for fetching image files from the image repository */ public String getNewImageToken(String imageId) { Set<GrantedAuthority> authorities = new HashSet<>(); authorities.add(new SimpleGrantedAuthority(imageId)); OAuth2Request oAuth2Request = buildOAuth2Request("vimdriver" + imageId, authorities); User userPrincipal = new User( "vimdriver" + imageId, "" + Math.random() * 1000, true, true, true, true, authorities); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities); OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken); OAuth2AccessToken token = imageTokenServices.createAccessToken(auth); return token.getValue(); }
Example 5
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 6
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 7
Source File: OAuth2CookieHelper.java From cubeai with Apache License 2.0 | 6 votes |
/** * Create cookies using the provided values. * * @param request the request we are handling. * @param accessToken the access token and enclosed refresh token for our cookies. * @param rememberMe whether the user had originally checked "remember me". * @param result will get the resulting cookies set. */ public void createCookies(HttpServletRequest request, OAuth2AccessToken accessToken, boolean rememberMe, OAuth2Cookies result) { String domain = getCookieDomain(request); log.debug("creating cookies for domain {}", domain); Cookie accessTokenCookie = new Cookie(ACCESS_TOKEN_COOKIE, accessToken.getValue()); setCookieProperties(accessTokenCookie, request.isSecure(), domain); log.debug("created access token cookie '{}'", accessTokenCookie.getName()); OAuth2RefreshToken refreshToken = accessToken.getRefreshToken(); Cookie refreshTokenCookie = createRefreshTokenCookie(refreshToken, rememberMe); setCookieProperties(refreshTokenCookie, request.isSecure(), domain); log.debug("created refresh token cookie '{}', age: {}", refreshTokenCookie.getName(), refreshTokenCookie .getMaxAge()); result.setCookies(accessTokenCookie, refreshTokenCookie); }
Example 8
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 9
Source File: MongoClientTokenServices.java From spring-security-mongo with MIT License | 5 votes |
@Override public void saveAccessToken(final OAuth2ProtectedResourceDetails resource, final Authentication authentication, final OAuth2AccessToken accessToken) { removeAccessToken(resource, authentication); final MongoOAuth2ClientToken mongoOAuth2ClientToken = new MongoOAuth2ClientToken(UUID.randomUUID().toString(), accessToken.getValue(), SerializationUtils.serialize(accessToken), clientKeyGenerator.extractKey(resource, authentication), authentication.getName(), resource.getClientId()); mongoOAuth2ClientTokenRepository.save(mongoOAuth2ClientToken); }
Example 10
Source File: OAuth2FeignRequestInterceptor.java From spring-cloud-security with Apache License 2.0 | 5 votes |
/** * Try to acquire the token using a access token provider. * @return valid access token * @throws UserRedirectRequiredException in case the user needs to be redirected to an * approval page or login page */ protected OAuth2AccessToken acquireAccessToken() throws UserRedirectRequiredException { AccessTokenRequest tokenRequest = oAuth2ClientContext.getAccessTokenRequest(); if (tokenRequest == null) { throw new AccessTokenRequiredException( "Cannot find valid context on request for resource '" + resource.getId() + "'.", resource); } String stateKey = tokenRequest.getStateKey(); if (stateKey != null) { tokenRequest.setPreservedState( oAuth2ClientContext.removePreservedState(stateKey)); } OAuth2AccessToken existingToken = oAuth2ClientContext.getAccessToken(); if (existingToken != null) { oAuth2ClientContext.setAccessToken(existingToken); } OAuth2AccessToken obtainableAccessToken; obtainableAccessToken = accessTokenProvider.obtainAccessToken(resource, tokenRequest); if (obtainableAccessToken == null || obtainableAccessToken.getValue() == null) { throw new IllegalStateException( " Access token provider returned a null token, which is illegal according to the contract."); } oAuth2ClientContext.setAccessToken(obtainableAccessToken); return obtainableAccessToken; }
Example 11
Source File: JwtTokenRedisStore.java From onetwo with Apache License 2.0 | 5 votes |
@Override public void removeAccessToken(OAuth2AccessToken token) { super.removeAccessToken(token); String tokenId = token.getValue(); String key = getStoreKey(tokenId); redisTemplate.delete(key); }
Example 12
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 13
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 14
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 15
Source File: _OAuth2AuthenticationAccessToken.java From jhipster-ribbon-hystrix with GNU General Public License v3.0 | 5 votes |
@PersistenceConstructor public OAuth2AuthenticationAccessToken(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication authentication, String authenticationId) { this.id = UUID.randomUUID().toString(); this.tokenId = oAuth2AccessToken.getValue(); this.oAuth2AccessToken = oAuth2AccessToken; this.authenticationId = authenticationId; this.userName = authentication.getName(); this.clientId = authentication.getOAuth2Request().getClientId(); this.authentication = authentication; if(oAuth2AccessToken.getRefreshToken() != null) { this.refreshToken = oAuth2AccessToken.getRefreshToken().getValue(); } }
Example 16
Source File: MyOAuth2RestTemplate.java From springboot-security-wechat with Apache License 2.0 | 5 votes |
protected OAuth2AccessToken acquireAccessToken(OAuth2ClientContext oauth2Context) throws UserRedirectRequiredException { AccessTokenRequest accessTokenRequest = oauth2Context.getAccessTokenRequest(); if (accessTokenRequest != null) { System.out.println("accesstokeRequest == " + accessTokenRequest.getCurrentUri()); } if(accessTokenRequest == null) { throw new AccessTokenRequiredException("No OAuth 2 security context has been established. Unable to access resource '" + this.resource.getId() + "'.", this.resource); } else { String stateKey = accessTokenRequest.getStateKey(); if(stateKey != null) { System.out.println("stateKey == " + stateKey); accessTokenRequest.setPreservedState(oauth2Context.removePreservedState(stateKey)); } OAuth2AccessToken existingToken = oauth2Context.getAccessToken(); if(existingToken != null) { accessTokenRequest.setExistingToken(existingToken); } OAuth2AccessToken accessToken = null; accessToken = this.accessTokenProvider.obtainAccessToken(this.resource, accessTokenRequest); if(accessToken != null && accessToken.getValue() != null) { oauth2Context.setAccessToken(accessToken); return accessToken; } else { throw new IllegalStateException("Access token provider returned a null access token, which is illegal according to the contract."); } } }
Example 17
Source File: OAuth2ClientTokenSevices.java From OAuth-2.0-Cookbook with MIT License | 5 votes |
@Override public void saveAccessToken(OAuth2ProtectedResourceDetails resource, Authentication authentication, OAuth2AccessToken accessToken) { ClientUser clientUser = getClientUser(authentication); clientUser.accessToken = accessToken.getValue(); clientUser.expirationTime = accessToken.getExpiration().getTime(); clientUser.additionalInformation = accessToken.getAdditionalInformation(); users.put(clientUser.username, clientUser); }
Example 18
Source File: OAuthClient.java From cf-java-client-sap with Apache License 2.0 | 5 votes |
public String getAuthorizationHeader() { OAuth2AccessToken accessToken = getToken(); if (accessToken != null) { return accessToken.getTokenType() + " " + accessToken.getValue(); } return null; }
Example 19
Source File: OAuth2TokenDAO.java From entando-core with GNU Lesser General Public License v3.0 | 4 votes |
@Override public void storeAccessToken(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { Connection conn = null; PreparedStatement stat = null; try { conn = this.getConnection(); String tokenValue = accessToken.getValue(); if (null != this.getAccessToken(tokenValue, conn)) { logger.debug("storeAccessToken: Stored Token already exists"); return; } conn.setAutoCommit(false); stat = conn.prepareStatement(INSERT_TOKEN); stat.setString(1, accessToken.getValue()); if (accessToken instanceof OAuth2AccessTokenImpl) { stat.setString(2, ((OAuth2AccessTokenImpl) accessToken).getClientId()); } else if (null != authentication.getOAuth2Request()) { stat.setString(2, authentication.getOAuth2Request().getClientId()); } else { stat.setNull(2, Types.VARCHAR); } stat.setTimestamp(3, new Timestamp(accessToken.getExpiration().getTime())); stat.setString(4, accessToken.getRefreshToken().getValue()); if (accessToken instanceof OAuth2AccessTokenImpl) { stat.setString(5, ((OAuth2AccessTokenImpl) accessToken).getGrantType()); stat.setString(6, ((OAuth2AccessTokenImpl) accessToken).getLocalUser()); } else { if (null != authentication.getOAuth2Request()) { stat.setString(5, authentication.getOAuth2Request().getGrantType()); } else { stat.setNull(5, Types.VARCHAR); } if (authentication.getPrincipal() instanceof UserDetails) { stat.setString(6, ((UserDetails) authentication.getPrincipal()).getUsername()); } else { stat.setString(6, authentication.getPrincipal().toString()); } } stat.executeUpdate(); conn.commit(); } catch (Exception t) { this.executeRollback(conn); logger.error("Error while adding an access token", t); throw new RuntimeException("Error while adding an access token", t); } finally { closeDaoResources(null, stat, conn); } }
Example 20
Source File: UacUserServiceImpl.java From paascloud-master with Apache License 2.0 | 4 votes |
@Override public void handlerLoginData(OAuth2AccessToken token, final SecurityUser principal, HttpServletRequest request) { final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent")); //获取客户端操作系统 final String os = userAgent.getOperatingSystem().getName(); //获取客户端浏览器 final String browser = userAgent.getBrowser().getName(); final String remoteAddr = RequestUtil.getRemoteAddr(request); // 根据IP获取位置信息 final String remoteLocation = opcRpcService.getLocationById(remoteAddr); final String requestURI = request.getRequestURI(); UacUser uacUser = new UacUser(); Long userId = principal.getUserId(); uacUser.setLastLoginIp(remoteAddr); uacUser.setId(userId); uacUser.setLastLoginTime(new Date()); uacUser.setLastLoginLocation(remoteLocation); LoginAuthDto loginAuthDto = new LoginAuthDto(userId, principal.getLoginName(), principal.getNickName(), principal.getGroupId(), principal.getGroupName()); // 记录token日志 String accessToken = token.getValue(); String refreshToken = token.getRefreshToken().getValue(); uacUserTokenService.saveUserToken(accessToken, refreshToken, loginAuthDto, request); // 记录最后登录信息 taskExecutor.execute(() -> this.updateUser(uacUser)); // 记录操作日志 UacLog log = new UacLog(); log.setGroupId(principal.getGroupId()); log.setGroupName(principal.getGroupName()); log.setIp(remoteAddr); log.setLocation(remoteLocation); log.setOs(os); log.setBrowser(browser); log.setRequestUrl(requestURI); log.setLogType(LogTypeEnum.LOGIN_LOG.getType()); log.setLogName(LogTypeEnum.LOGIN_LOG.getName()); taskExecutor.execute(() -> uacLogService.saveLog(log, loginAuthDto)); }