List of usage examples for org.springframework.security.oauth2.common.util OAuth2Utils GRANT_TYPE
String GRANT_TYPE
To view the source code for org.springframework.security.oauth2.common.util OAuth2Utils GRANT_TYPE.
Click Source Link
From source file:org.cloudfoundry.identity.uaa.login.util.LocalUaaRestTemplate.java
@Override protected OAuth2AccessToken acquireAccessToken(OAuth2ClientContext oauth2Context) throws UserRedirectRequiredException { ClientDetails client = clientDetailsService.loadClientByClientId(getClientId()); Set<String> scopes = new HashSet<>(); for (GrantedAuthority authority : client.getAuthorities()) { scopes.add(authority.getAuthority()); }// w w w .j a v a2 s. c o m Set<String> resourceIds = new HashSet<>(); resourceIds.add(Origin.UAA); Set<String> responseTypes = new HashSet<>(); responseTypes.add("token"); Map<String, String> requestParameters = new HashMap<>(); requestParameters.put(OAuth2Utils.CLIENT_ID, "login"); requestParameters.put(OAuth2Utils.GRANT_TYPE, "client_credentials"); OAuth2Request request = new OAuth2Request(requestParameters, "login", (Collection<? extends GrantedAuthority>) Collections.EMPTY_SET, true, scopes, resourceIds, null, responseTypes, Collections.EMPTY_MAP); OAuth2Authentication authentication = new OAuth2Authentication(request, null); OAuth2AccessToken result = tokenServices.createAccessToken(authentication); oauth2Context.setAccessToken(result); return result; }
From source file:com.example.ProxyAuthorizationServerTokenServices.java
private MultiValueMap<String, String> createForm(String refreshToken, TokenRequest tokenRequest) { MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set(OAuth2Utils.GRANT_TYPE, "refresh_token"); form.set("refresh_token", refreshToken); if (!tokenRequest.getScope().isEmpty()) { form.set(OAuth2Utils.SCOPE, OAuth2Utils.formatParameterList(tokenRequest.getScope())); }/*from w w w . j a v a 2s .co m*/ return form; }
From source file:com.haulmont.restapi.ldap.LdapAuthController.java
@RequestMapping(value = "/v2/ldap/token", method = RequestMethod.POST) public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters, HttpServletRequest request) throws HttpRequestMethodNotSupportedException { if (!ldapConfig.getLdapEnabled()) { log.debug("LDAP authentication is disabled. Property cuba.rest.ldap.enabled is false"); throw new InvalidGrantException("LDAP is not supported"); }//from www. j a v a 2 s. co m if (!(principal instanceof Authentication)) { throw new InsufficientAuthenticationException( "There is no client authentication. Try adding an appropriate authentication filter."); } String grantType = parameters.get(OAuth2Utils.GRANT_TYPE); if (!"password".equals(grantType)) { throw new InvalidGrantException("grant type not supported for ldap/token endpoint"); } String username = parameters.get("username"); if (restApiConfig.getStandardAuthenticationUsers().contains(username)) { log.info("User {} is not allowed to use external login in REST API", username); throw new BadCredentialsException("Bad credentials"); } String ipAddress = request.getRemoteAddr(); String password = parameters.get("password"); OAuth2AccessTokenResult tokenResult = authenticate(username, password, request.getLocale(), ipAddress, parameters); return ResponseEntity.ok(tokenResult.getAccessToken()); }
From source file:org.energyos.espi.datacustodian.oauth.EspiTokenEnhancer.java
@Transactional(rollbackFor = { javax.xml.bind.JAXBException.class }, noRollbackFor = {
javax.persistence.NoResultException.class,
org.springframework.dao.EmptyResultDataAccessException.class })
@Override/*from w ww .j ava 2s . c o m*/
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken);
System.out.printf("EspiTokenEnhancer: OAuth2Request Parameters = %s\n",
authentication.getOAuth2Request().getRequestParameters());
System.out.printf("EspiTokenEnhancer: Authorities = %s\n", authentication.getAuthorities());
String clientId = authentication.getOAuth2Request().getClientId();
ApplicationInformation ai = null;
// [mjb20150102] Allow REGISTRATION_xxxx and ADMIN_xxxx to use same
// ApplicationInformation record
String ci = clientId;
String clientCredentialsScope = accessToken.getScope().toString();
if (ci.indexOf("REGISTRATION_") != -1) {
if (ci.substring(0, "REGISTRATION_".length()).equals("REGISTRATION_")) {
ci = ci.substring("REGISTRATION_".length());
}
}
if (ci.indexOf("_admin") != -1) {
ci = ci.substring(0, ci.indexOf("_admin"));
}
// Confirm Application Information record exists for ClientID requesting
// an access token
try {
ai = applicationInformationService.findByClientId(ci);
} catch (NoResultException | EmptyResultDataAccessException e) {
System.out.printf(
"\nEspiTokenEnhancer: ApplicationInformation record not found!\n"
+ "OAuth2Request Parameters = %s\n",
authentication.getOAuth2Request().getRequestParameters() + " client_id = " + clientId);
throw new AccessDeniedException(String.format("No client with requested id: %s", clientId));
}
Map<String, String> requestParameters = authentication.getOAuth2Request().getRequestParameters();
String grantType = requestParameters.get(OAuth2Utils.GRANT_TYPE);
grantType = grantType.toLowerCase();
// Is this a "client_credentials" access token grant_type request?
if (grantType.contentEquals("client_credentials")) {
// Processing a "client_credentials" access token grant_type
// request.
// Reject a client_credentials request if Authority equals
// "ROLE_USER"
if (authentication.getAuthorities().toString().contains("[ROLE_USER]")) {
throw new InvalidGrantException(String.format("Client Credentials not valid for ROLE_USER\n"));
}
// Create Authorization and add authorizationURI to /oath/token
// response
Authorization authorization = authorizationService.createAuthorization(null, result.getValue());
result.getAdditionalInformation().put("authorizationURI",
ai.getDataCustodianResourceEndpoint()
+ Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
.replace("{authorizationId}", authorization.getId().toString()));
// Create Subscription
Subscription subscription = subscriptionService.createSubscription(authentication);
// Initialize Authorization record
authorization.setThirdParty(authentication.getOAuth2Request().getClientId());
authorization.setAccessToken(accessToken.getValue());
authorization.setTokenType(accessToken.getTokenType());
authorization.setExpiresIn((long) accessToken.getExpiresIn());
authorization.setAuthorizedPeriod(new DateTimeInterval((long) 0, (long) 0));
authorization.setPublishedPeriod(new DateTimeInterval((long) 0, (long) 0));
if (accessToken.getRefreshToken() != null) {
authorization.setRefreshToken(accessToken.getRefreshToken().toString());
}
// Remove "[" and "]" surrounding Scope in accessToken structure
authorization.setScope(accessToken.getScope().toString().substring(1,
(accessToken.getScope().toString().length() - 1)));
// set the authorizationUri
authorization.setAuthorizationURI(ai.getDataCustodianResourceEndpoint()
+ Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
.replace("{authorizationId}", authorization.getId().toString()));
// Determine resourceURI value based on Client's Role
Set<String> role = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (role.contains("ROLE_DC_ADMIN")) {
authorization.setResourceURI(ai.getDataCustodianResourceEndpoint() + "/");
} else {
if (role.contains("ROLE_TP_ADMIN")) {
authorization.setResourceURI(ai.getDataCustodianResourceEndpoint()
+ Routes.BATCH_BULK_MEMBER.replace("espi/1_1/resource/", "").replace("{bulkId}", "**"));
} else {
if (role.contains("ROLE_UL_ADMIN")) {
authorization
.setResourceURI(ai.getDataCustodianResourceEndpoint() + Routes.BATCH_UPLOAD_MY_DATA
.replace("espi/1_1/resource/", "").replace("{retailCustomerId}", "**"));
} else {
if (role.contains("ROLE_TP_REGISTRATION")) {
authorization.setResourceURI(ai.getDataCustodianResourceEndpoint()
+ Routes.ROOT_APPLICATION_INFORMATION_MEMBER.replace("espi/1_1/resource/", "")
.replace("{applicationInformationId}", ai.getId().toString()));
}
}
}
}
authorization.setApplicationInformation(applicationInformationService.findByClientId(ci));
authorization.setRetailCustomer(retailCustomerService.findById((long) 0));
authorization.setUpdated(new GregorianCalendar());
authorization.setStatus("1"); // Set authorization record status as
// "Active"
authorization.setSubscription(subscription);
authorizationService.merge(authorization);
// Add resourceURI to access_token response
result.getAdditionalInformation().put("resourceURI", authorization.getResourceURI());
// Initialize Subscription record
subscription.setAuthorization(authorization);
subscription.setUpdated(new GregorianCalendar());
subscriptionService.merge(subscription);
} else if (grantType.contentEquals("authorization_code")) {
try {
// Is this a refresh_token grant_type request?
Authorization authorization = authorizationService
.findByRefreshToken(result.getRefreshToken().getValue());
// Yes, update access token
authorization.setAccessToken(accessToken.getValue());
authorizationService.merge(authorization);
// Add ResourceURI and AuthorizationURI to access_token response
result.getAdditionalInformation().put("resourceURI", authorization.getResourceURI());
result.getAdditionalInformation().put("authorizationURI", authorization.getAuthorizationURI());
} catch (NoResultException | EmptyResultDataAccessException e) {
// No, process as initial access token request
// Create Subscription and add resourceURI to /oath/token
// response
Subscription subscription = subscriptionService.createSubscription(authentication);
result.getAdditionalInformation().put("resourceURI",
ai.getDataCustodianResourceEndpoint()
+ Routes.BATCH_SUBSCRIPTION.replace("espi/1_1/resource/", "")
.replace("{subscriptionId}", subscription.getId().toString()));
// Create Authorization and add authorizationURI to /oath/token
// response
Authorization authorization = authorizationService.createAuthorization(subscription,
result.getValue());
result.getAdditionalInformation().put("authorizationURI",
ai.getDataCustodianResourceEndpoint()
+ Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
.replace("{authorizationId}", authorization.getId().toString()));
// Update Data Custodian subscription structure
subscription.setAuthorization(authorization);
subscription.setUpdated(new GregorianCalendar());
subscriptionService.merge(subscription);
RetailCustomer retailCustomer = (RetailCustomer) authentication.getPrincipal();
// link in the usage points associated with this subscription
List<Long> usagePointIds = resourceService.findAllIdsByXPath(retailCustomer.getId(),
UsagePoint.class);
Iterator<Long> it = usagePointIds.iterator();
while (it.hasNext()) {
UsagePoint up = resourceService.findById(it.next(), UsagePoint.class);
up.setSubscription(subscription);
resourceService.persist(up); // maybe not needed??
}
// Update Data Custodian authorization structure
authorization.setApplicationInformation(applicationInformationService
.findByClientId(authentication.getOAuth2Request().getClientId()));
authorization.setThirdParty(authentication.getOAuth2Request().getClientId());
authorization.setRetailCustomer(retailCustomer);
authorization.setAccessToken(accessToken.getValue());
authorization.setTokenType(accessToken.getTokenType());
authorization.setExpiresIn((long) accessToken.getExpiresIn());
if (accessToken.getRefreshToken() != null) {
authorization.setRefreshToken(accessToken.getRefreshToken().toString());
}
// Remove "[" and "]" surrounding Scope in accessToken structure
authorization.setScope(accessToken.getScope().toString().substring(1,
(accessToken.getScope().toString().length() - 1)));
authorization.setAuthorizationURI(ai.getDataCustodianResourceEndpoint()
+ Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
.replace("{authorizationId}", authorization.getId().toString()));
authorization.setResourceURI(ai.getDataCustodianResourceEndpoint()
+ Routes.BATCH_SUBSCRIPTION.replace("espi/1_1/resource/", "").replace("{subscriptionId}",
subscription.getId().toString()));
authorization.setUpdated(new GregorianCalendar());
authorization.setStatus("1"); // Set authorization record status
// as "Active"
authorization.setSubscription(subscription);
authorization.setAuthorizedPeriod(new DateTimeInterval((long) 0, (long) 0));
authorization.setPublishedPeriod(new DateTimeInterval((long) 0, (long) 0));
authorizationService.merge(authorization);
}
} else {
System.out.printf(
"EspiTokenEnhancer: Invalid Grant_Type processed by Spring Security OAuth2 Framework:\n"
+ "OAuth2Request Parameters = %s\n",
authentication.getOAuth2Request().getRequestParameters());
throw new AccessDeniedException(String.format("Unsupported ESPI OAuth2 grant_type"));
}
return result;
}
From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java
@Test void refreshTokenGrant_rejectsAccessTokens_ClientCredentialsGrantType() throws Exception { createClientAndUserInRandomZone();// w ww .j a v a 2s .c o m String tokenResponse = mockMvc .perform(post("/oauth/token").header("Host", getZoneHostUrl(zone)) .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param(OAuth2Utils.GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS).param("client_secret", SECRET) .param(OAuth2Utils.CLIENT_ID, client.getClientId())) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); String accessToken = (String) JsonUtils.readValue(tokenResponse, new TypeReference<Map<String, Object>>() { }).get("access_token"); mockMvc.perform(post("/oauth/token").header("Host", getZoneHostUrl(zone)).accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, accessToken) .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, client.getClientId())) .andExpect(status().isUnauthorized()); }
From source file:org.cloudfoundry.identity.client.UaaContextFactory.java
protected UaaContext fetchTokenFromCode(final TokenRequest request) { String clientBasicAuth = getClientBasicAuthHeader(request); RestTemplate template = new RestTemplate(); if (request.isSkipSslValidation()) { template.setRequestFactory(getNoValidatingClientHttpRequestFactory()); }//from ww w. j a va 2 s .c om HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add(OAuth2Utils.GRANT_TYPE, "authorization_code"); form.add(OAuth2Utils.REDIRECT_URI, request.getRedirectUri().toString()); String responseType = "token"; if (request.wantsIdToken()) { responseType += " id_token"; } form.add(OAuth2Utils.RESPONSE_TYPE, responseType); form.add("code", request.getAuthorizationCode()); ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST, new HttpEntity<>(form, headers), CompositeAccessToken.class); return new UaaContextImpl(request, null, token.getBody()); }
From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java
@Test void refreshTokenGrant_rejectsAccessTokens_PasswordGrantType() throws Exception { createClientAndUserInRandomZone();//from w w w . j a va2s .c om String body = mockMvc .perform(post("/oauth/token").accept(MediaType.APPLICATION_JSON_VALUE) .header("Host", getZoneHostUrl(zone)) .header("Authorization", "Basic " + new String( Base64.encode((client.getClientId() + ":" + SECRET).getBytes()))) .param("grant_type", GRANT_TYPE_PASSWORD).param("client_id", client.getClientId()) .param("client_secret", SECRET).param("username", user.getUserName()) .param("password", SECRET)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); Map<String, Object> bodyMap = JsonUtils.readValue(body, new TypeReference<Map<String, Object>>() { }); String accessToken = (String) bodyMap.get("access_token"); mockMvc.perform(post("/oauth/token").header("Host", getZoneHostUrl(zone)).accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, accessToken) .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, client.getClientId())) .andExpect(status().isUnauthorized()); }
From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java
@Test void refreshTokenGrant_rejectsIdTokens() throws Exception { createClientAndUserInRandomZone();/*from ww w .j a va 2s . c om*/ String body = mockMvc .perform(post("/oauth/token").accept(MediaType.APPLICATION_JSON_VALUE) .header("Host", getZoneHostUrl(zone)) .header("Authorization", "Basic " + new String( Base64.encode((client.getClientId() + ":" + SECRET).getBytes()))) .param("grant_type", GRANT_TYPE_PASSWORD).param("client_id", client.getClientId()) .param("client_secret", SECRET).param("username", user.getUserName()) .param("password", SECRET)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); Map<String, Object> bodyMap = JsonUtils.readValue(body, new TypeReference<Map<String, Object>>() { }); String idToken = (String) bodyMap.get("id_token"); mockMvc.perform(post("/oauth/token").header("Host", getZoneHostUrl(zone)).accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, idToken) .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, client.getClientId())) .andExpect(status().isUnauthorized()); }
From source file:org.cloudfoundry.identity.client.UaaContextFactory.java
protected UaaContext authenticateSaml2BearerAssertion(final TokenRequest request) { RestTemplate template = new RestTemplate(); if (request.isSkipSslValidation()) { template.setRequestFactory(getNoValidatingClientHttpRequestFactory()); }//w ww .jav a 2s . co m HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add(OAuth2Utils.CLIENT_ID, request.getClientId()); form.add("client_secret", request.getClientSecret()); form.add(OAuth2Utils.GRANT_TYPE, "urn:ietf:params:oauth:grant-type:saml2-bearer"); form.add("assertion", request.getAuthCodeAPIToken()); ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST, new HttpEntity<>(form, headers), CompositeAccessToken.class); return new UaaContextImpl(request, null, token.getBody()); }
From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java
@Test void refreshTokenGrantType_requiresAuthorizedGrantType() throws Exception { client = setUpClients("clientwithrefresh", "", "scim.me", "password,refresh_token", true); ClientDetails clientWithoutRefresh = setUpClients("passwordclient", "", "scim.me", "password", true); user = setUpUser("joe-user", "", OriginKeys.UAA, "uaa"); String refreshToken = getJwtRefreshToken(client.getClientId(), SECRET, user.getUserName(), SECRET, "localhost"); mockMvc.perform(post("/oauth/token").header("Host", "localhost").accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, refreshToken) .param("client_secret", SECRET).param(OAuth2Utils.CLIENT_ID, clientWithoutRefresh.getClientId())) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.error_description").value("Unauthorized grant type: refresh_token")); }