use of org.springframework.security.oauth2.provider.approval.Approval in project uaa by cloudfoundry.
the class OpenIdTokenGrantsIT method doOpenIdHybridFlowIdTokenAndCode.
private void doOpenIdHybridFlowIdTokenAndCode(Set<String> responseTypes, String responseTypeMatcher) {
BasicCookieStore cookies = new BasicCookieStore();
StringBuilder responseType = new StringBuilder();
Iterator<String> rTypes = responseTypes.iterator();
while (rTypes.hasNext()) {
String type = rTypes.next();
responseType.append(type);
if (rTypes.hasNext()) {
responseType.append(" ");
}
}
String state = new RandomValueStringGenerator().generate();
String clientId = "app";
String clientSecret = "appclientsecret";
String redirectUri = "http://localhost:8080/app/";
String uri = baseUrl + "/oauth/authorize?response_type={response_type}&" + "state={state}&client_id={client_id}&redirect_uri={redirect_uri}";
ResponseEntity<Void> result = restOperations.exchange(uri, HttpMethod.GET, new HttpEntity<>(null, getHeaders(cookies)), Void.class, responseType, state, clientId, redirectUri);
assertEquals(HttpStatus.FOUND, result.getStatusCode());
String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
if (result.getHeaders().containsKey("Set-Cookie")) {
for (String cookie : result.getHeaders().get("Set-Cookie")) {
int nameLength = cookie.indexOf('=');
cookies.addCookie(new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1)));
}
}
ResponseEntity<String> response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, getHeaders(cookies)), String.class);
// should be directed to the login screen...
assertTrue(response.getBody().contains("/login.do"));
assertTrue(response.getBody().contains("username"));
assertTrue(response.getBody().contains("password"));
String csrf = IntegrationTestUtils.extractCookieCsrf(response.getBody());
if (response.getHeaders().containsKey("Set-Cookie")) {
for (String cookie : response.getHeaders().get("Set-Cookie")) {
int nameLength = cookie.indexOf('=');
cookies.addCookie(new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1)));
}
}
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("username", user.getUserName());
formData.add("password", secret);
formData.add(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, csrf);
// Should be redirected to the original URL, but now authenticated
result = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST, new HttpEntity<>(formData, getHeaders(cookies)), Void.class);
assertEquals(HttpStatus.FOUND, result.getStatusCode());
cookies.clear();
if (result.getHeaders().containsKey("Set-Cookie")) {
for (String cookie : result.getHeaders().get("Set-Cookie")) {
int nameLength = cookie.indexOf('=');
cookies.addCookie(new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1)));
}
}
location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, getHeaders(cookies)), String.class);
if (response.getHeaders().containsKey("Set-Cookie")) {
for (String cookie : response.getHeaders().get("Set-Cookie")) {
int nameLength = cookie.indexOf('=');
cookies.addCookie(new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1)));
}
}
if (response.getStatusCode() == HttpStatus.OK) {
// The grant access page should be returned
assertTrue(response.getBody().contains("You can change your approval of permissions"));
formData.clear();
formData.add(USER_OAUTH_APPROVAL, "true");
formData.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody()));
result = restOperations.exchange(baseUrl + "/oauth/authorize", HttpMethod.POST, new HttpEntity<>(formData, getHeaders(cookies)), Void.class);
assertEquals(HttpStatus.FOUND, result.getStatusCode());
location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
} else {
// Token cached so no need for second approval
assertEquals(HttpStatus.FOUND, response.getStatusCode());
location = UriUtils.decode(response.getHeaders().getLocation().toString(), "UTF-8");
}
assertTrue("Wrong location: " + location, location.matches(redirectUri + responseTypeMatcher));
formData.clear();
formData.add("client_id", clientId);
formData.add("redirect_uri", redirectUri);
formData.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE);
formData.add("code", location.split("code=")[1].split("&")[0]);
HttpHeaders tokenHeaders = new HttpHeaders();
String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes()));
tokenHeaders.set("Authorization", basicDigestHeaderValue);
@SuppressWarnings("rawtypes") ResponseEntity<Map> tokenResponse = restOperations.exchange(baseUrl + "/oauth/token", HttpMethod.POST, new HttpEntity<>(formData, tokenHeaders), Map.class);
assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
@SuppressWarnings("unchecked") Map<String, String> body = tokenResponse.getBody();
Jwt token = JwtHelper.decode(body.get("access_token"));
assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
}
use of org.springframework.security.oauth2.provider.approval.Approval in project OpenID-Connect-Java-Spring-Server by mitreid-connect.
the class DeviceTokenGranter method getOAuth2Authentication.
/* (non-Javadoc)
* @see org.springframework.security.oauth2.provider.token.AbstractTokenGranter#getOAuth2Authentication(org.springframework.security.oauth2.provider.ClientDetails, org.springframework.security.oauth2.provider.TokenRequest)
*/
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
String deviceCode = tokenRequest.getRequestParameters().get("device_code");
// look up the device code and consume it
DeviceCode dc = deviceCodeService.findDeviceCode(deviceCode, client);
if (dc != null) {
// make sure the code hasn't expired yet
if (dc.getExpiration() != null && dc.getExpiration().before(new Date())) {
deviceCodeService.clearDeviceCode(deviceCode, client);
throw new DeviceCodeExpiredException("Device code has expired " + deviceCode);
} else if (!dc.isApproved()) {
// still waiting for approval
throw new AuthorizationPendingException("Authorization pending for code " + deviceCode);
} else {
// inherit the (approved) scopes from the original request
tokenRequest.setScope(dc.getScope());
OAuth2Authentication auth = new OAuth2Authentication(getRequestFactory().createOAuth2Request(client, tokenRequest), dc.getAuthenticationHolder().getUserAuth());
deviceCodeService.clearDeviceCode(deviceCode, client);
return auth;
}
} else {
throw new InvalidGrantException("Invalid device code: " + deviceCode);
}
}
use of org.springframework.security.oauth2.provider.approval.Approval in project theskeleton by codenergic.
the class UserOauth2ClientApprovalStoreTest method testAddApprovals.
@Test
public void testAddApprovals() {
assertThatThrownBy(() -> {
approvalStore.addApprovals(null);
}).isInstanceOf(NullPointerException.class);
when(userRepository.findByUsername(anyString())).thenReturn(Optional.of(new UserEntity()));
when(approvalRepository.findByUserUsernameAndClientIdAndScope(anyString(), anyString(), eq("read"))).thenReturn(new UserOAuth2ClientApprovalEntity().setUser(new UserEntity().setId("1")).setClient(new OAuth2ClientEntity().setId("2")).setScope("read").setApprovalStatus(ApprovalStatus.APPROVED));
approvalStore.addApprovals(Collections.singletonList(new Approval("1", "2", "read", new Date(), ApprovalStatus.APPROVED)));
verify(approvalRepository).findByUserUsernameAndClientIdAndScope(anyString(), anyString(), eq("read"));
when(approvalRepository.findByUserUsernameAndClientIdAndScope(anyString(), anyString(), eq("write"))).thenReturn(null);
approvalStore.addApprovals(Collections.singletonList(new Approval("1", "2", "write", new Date(), ApprovalStatus.APPROVED)));
verify(userRepository, atLeastOnce()).findByUsername(anyString());
verify(approvalRepository).findByUserUsernameAndClientIdAndScope(anyString(), anyString(), eq("write"));
verify(approvalRepository, times(2)).save(any(UserOAuth2ClientApprovalEntity.class));
}
use of org.springframework.security.oauth2.provider.approval.Approval in project theskeleton by codenergic.
the class UserOAuth2ClientApprovalEntity method toApproval.
public Approval toApproval() {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.setTime(Optional.ofNullable(getLastModifiedDate()).orElse(getCreatedDate()));
calendar.add(Calendar.DAY_OF_MONTH, 30);
return new Approval(user.getId(), client.getId(), scope, calendar.getTime(), approvalStatus);
}
use of org.springframework.security.oauth2.provider.approval.Approval in project spring-security-oauth by spring-projects.
the class AuthorizationCodeAccessTokenProvider method obtainAuthorizationCode.
public String obtainAuthorizationCode(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException {
AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) details;
HttpHeaders headers = getHeadersForAuthorizationRequest(request);
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
if (request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)) {
form.set(OAuth2Utils.USER_OAUTH_APPROVAL, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
for (String scope : details.getScope()) {
form.set(scopePrefix + scope, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
}
} else {
form.putAll(getParametersForAuthorizeRequest(resource, request));
}
authorizationRequestEnhancer.enhance(request, resource, form, headers);
final AccessTokenRequest copy = request;
final ResponseExtractor<ResponseEntity<Void>> delegate = getAuthorizationResponseExtractor();
ResponseExtractor<ResponseEntity<Void>> extractor = new ResponseExtractor<ResponseEntity<Void>>() {
@Override
public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
if (response.getHeaders().containsKey("Set-Cookie")) {
copy.setCookie(response.getHeaders().getFirst("Set-Cookie"));
}
return delegate.extractData(response);
}
};
// Instead of using restTemplate.exchange we use an explicit response extractor here so it can be overridden by
// subclasses
ResponseEntity<Void> response = getRestTemplate().execute(resource.getUserAuthorizationUri(), HttpMethod.POST, getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap());
if (response.getStatusCode() == HttpStatus.OK) {
// Need to re-submit with approval...
throw getUserApprovalSignal(resource, request);
}
URI location = response.getHeaders().getLocation();
String query = location.getQuery();
Map<String, String> map = OAuth2Utils.extractMap(query);
if (map.containsKey("state")) {
request.setStateKey(map.get("state"));
if (request.getPreservedState() == null) {
String redirectUri = resource.getRedirectUri(request);
if (redirectUri != null) {
request.setPreservedState(redirectUri);
} else {
request.setPreservedState(new Object());
}
}
}
String code = map.get("code");
if (code == null) {
throw new UserRedirectRequiredException(location.toString(), form.toSingleValueMap());
}
request.set("code", code);
return code;
}
Aggregations