Java Examples for org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException
The following java examples will help you to understand the usage of org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException. These source code samples are taken from different open source projects.
Example 1
Project: eclipse-integration-cloudfoundry-master File: CloudErrorUtil.java View source code |
/** * Error due to invalid credentials, typically 401 or 403 HTTP errors. * Returns null if the error is NOT an invalid credentials error. * @param error error to parse * @return Error message if invalid credentials error (401 or 403), or null. */ public static String getInvalidCredentialsError(Throwable error) { if (isUnauthorisedException(error)) { return Messages.ERROR_WRONG_EMAIL_OR_PASSWORD_UNAUTHORISED; } else if (isForbiddenException(error)) { return Messages.ERROR_WRONG_EMAIL_OR_PASSWORD_FORBIDDEN; } else { OAuth2AccessDeniedException oauthException = null; if (error instanceof OAuth2AccessDeniedException) { oauthException = (OAuth2AccessDeniedException) error; } else if (error.getCause() instanceof OAuth2AccessDeniedException) { oauthException = (OAuth2AccessDeniedException) error.getCause(); } if (oauthException != null) { return NLS.bind(Messages.ERROR_ACCESS_TOKEN, oauthException.getOAuth2ErrorCode()); } } return null; }
Example 2
Project: easylocate-master File: OAuth2ContextSetup.java View source code |
/** * Get the current access token. Should be available inside a test method as long as a resource has been setup with * {@link OAuth2ContextConfiguration @OAuth2ContextConfiguration}. * * @return the current access token initializing it if necessary */ public OAuth2AccessToken getAccessToken() { if (resource == null || client == null) { return null; } if (accessToken != null) { return accessToken; } try { if (accessTokenProvider != null) { client.setAccessTokenProvider(accessTokenProvider); } return client.getAccessToken(); } catch (OAuth2AccessDeniedException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } if (cause instanceof Error) { throw (Error) cause; } throw e; } }
Example 3
Project: identity-sample-apps-master File: OpenIDTokenProvider.java View source code |
@Override public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException { AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) details; if (request.getAuthorizationCode() == null) { if (request.getStateKey() == null) { throw getRedirectForAuthorization(resource, request); } obtainAuthorizationCode(resource, request); } return retrieveToken(request, resource, getParametersForTokenRequest(resource, request), getHeadersForTokenRequest(request)); }
Example 4
Project: spring-security-oauth-master File: AuthorizationCodeAccessTokenProvider.java View source code |
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; }
Example 5
Project: cloudpier-core-master File: OauthClient.java View source code |
public OAuth2AccessToken getToken(String username, String password) { OAuth2ProtectedResourceDetails resource = getImplicitResource(); Map<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put("credentials", String.format("{\"username\":\"%s\",\"password\":\"%s\"}", username, password)); AccessTokenRequest request = new DefaultAccessTokenRequest(); request.setAll(parameters); ImplicitAccessTokenProvider provider = new ImplicitAccessTokenProvider(); provider.setRestTemplate(restTemplate); OAuth2AccessToken token = null; try { token = provider.obtainAccessToken(resource, request); } catch (OAuth2AccessDeniedException oauthEx) { HttpStatus status = HttpStatus.valueOf(oauthEx.getHttpErrorCode()); CloudFoundryException cfEx = new CloudFoundryException(status, oauthEx.getMessage()); cfEx.setDescription(oauthEx.getSummary()); throw cfEx; } return token; }
Example 6
Project: spring-cloud-dataflow-master File: ManualOAuthAuthenticationProvider.java View source code |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { final String username = authentication.getName(); final String password = authentication.getCredentials().toString(); final ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails(); resource.setUsername(username); resource.setPassword(password); resource.setAccessTokenUri(accessTokenUri); resource.setClientId(oAuth2ClientProperties.getClientId()); resource.setClientSecret(oAuth2ClientProperties.getClientSecret()); resource.setGrantType("password"); final OAuth2RestTemplate template = new OAuth2RestTemplate(resource, new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest())); template.setAccessTokenProvider(userAccessTokenProvider()); try { logger.warn("Authenticating user '{}' using accessTokenUri '{}'.", username, accessTokenUri); template.getAccessToken(); } catch (OAuth2AccessDeniedException e) { if (e.getCause() instanceof ResourceAccessException) { final String errorMessage = String.format("While authenticating user '%s': " + "Unable to access accessTokenUri '%s'.", username, accessTokenUri); logger.error(errorMessage + " Error message: {}.", e.getCause().getMessage()); throw new AuthenticationServiceException(errorMessage, e); } throw new BadCredentialsException(String.format("Access denied for user '%s'.", username), e); } catch (OAuth2Exception e) { throw new AuthenticationServiceException(String.format("Unable to perform OAuth authentication for user '%s'.", username), e); } final Collection<GrantedAuthority> authorities = new ArrayList<>(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password, authorities); return token; }
Example 7
Project: gmm-eclipse-plugins-master File: GenMyModelExplorer.java View source code |
private void addAccount(GMMCredential credential) { try { ProjectBinding[] projects = client.GETMyProjects(credential); ArrayList<Object> list = new ArrayList<Object>(); list.add(credential); for (ProjectBinding project : projects) { list.add(project); } if (save != null) { IMemento child = save.createChild("credential"); child.putString("username", credential.getUsername()); child.putString("password", credential.getPassword()); } content.addElement(list); content.initialize(); viewer.setContentProvider(content); keyStore.addCredential(credential.getUsername(), credential); } catch (OAuth2AccessDeniedException e) { IStatus err = new Status(Status.ERROR, Activator.PLUGIN_ID, Status.ERROR, "Login/password error\n\tPlease verify your information and be sure that you set a passord for your account.", e); StatusManager.getManager().handle(err, StatusManager.BLOCK); } }
Example 8
Project: shimmer-master File: GoogleFitShim.java View source code |
@Override public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException, OAuth2AccessDeniedException { OAuth2AccessToken accessToken = super.refreshAccessToken(resource, refreshToken, request); // Google does not replace refresh tokens, so we need to hold on to the existing refresh token... if (accessToken.getRefreshToken() == null) { ((DefaultOAuth2AccessToken) accessToken).setRefreshToken(refreshToken); } return accessToken; }
Example 9
Project: geoserver-master File: GeoServerOAuthAuthenticationFilter.java View source code |
protected String getPreAuthenticatedPrincipal(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Make sure the REST Resource Template has been correctly configured configureRestTemplate(); // Avoid retrieving the user name more than once /* * if (req.getAttribute(UserNameAlreadyRetrieved) != null) return (String) req.getAttribute(UserName); */ // Search for an access_token on the request (simulating SSO) String accessToken = req.getParameter("access_token"); if (accessToken != null) { restTemplate.getOAuth2ClientContext().setAccessToken(new DefaultOAuth2AccessToken(accessToken)); } // Setting up OAuth2 Filter services and resource template filter.setRestTemplate(restTemplate); filter.setTokenServices(tokenServices); // Validating the access_token Authentication authentication = null; try { authentication = filter.attemptAuthentication(req, null); } catch (Exception e) { if (e instanceof UserRedirectRequiredException) { if (filterConfig.getEnableRedirectAuthenticationEntryPoint() || req.getRequestURI().endsWith(filterConfig.getLoginEndpoint())) { this.aep.commence(req, resp, null); } else { if (resp.getStatus() != 302) { final AccessTokenRequest accessTokenRequest = restTemplate.getOAuth2ClientContext().getAccessTokenRequest(); if (accessTokenRequest.getPreservedState() != null && accessTokenRequest.getStateKey() != null) { accessTokenRequest.remove("state"); accessTokenRequest.remove(accessTokenRequest.getStateKey()); accessTokenRequest.setPreservedState(null); } } } } else if (e instanceof BadCredentialsException || e instanceof ResourceAccessException) { if (e.getCause() instanceof OAuth2AccessDeniedException) { LOGGER.log(Level.WARNING, "Error while trying to authenticate to OAuth2 Provider with the following Exception cause:", e.getCause()); } if (e instanceof ResourceAccessException) { LOGGER.log(Level.SEVERE, "Could not Authorize OAuth2 Resource due to the following exception:", e); } if (e instanceof ResourceAccessException || e.getCause() instanceof OAuth2AccessDeniedException) { LOGGER.log(Level.WARNING, "It is worth notice that if you try to validate credentials against an SSH protected Endpoint, you need either your server exposed on a secure SSL channel or OAuth2 Provider Certificate to be trusted on your JVM!"); LOGGER.info("Please refer to the GeoServer OAuth2 Plugin Documentation in order to find the steps for importing the SSH certificates."); } } } String principal = (authentication != null ? (String) authentication.getPrincipal() : null); if (principal != null && principal.trim().length() == 0) principal = null; try { if (principal != null && PreAuthenticatedUserNameRoleSource.UserGroupService.equals(getRoleSource())) { GeoServerUserGroupService service = getSecurityManager().loadUserGroupService(getUserGroupServiceName()); GeoServerUser u = service.getUserByUsername(principal); if (u != null && u.isEnabled() == false) { principal = null; handleDisabledUser(u, req); } } } catch (IOException ex) { throw new RuntimeException(ex); } req.setAttribute(UserNameAlreadyRetrieved, Boolean.TRUE); if (principal != null) req.setAttribute(UserName, principal); return principal; }
Example 10
Project: cloudpier-adapters-master File: OauthClient.java View source code |
public OAuth2AccessToken getToken(String username, String password) { OAuth2ProtectedResourceDetails resource = getImplicitResource(); Map<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put("credentials", String.format("{\"username\":\"%s\",\"password\":\"%s\"}", username, password)); AccessTokenRequest request = new DefaultAccessTokenRequest(); request.setAll(parameters); ImplicitAccessTokenProvider provider = new ImplicitAccessTokenProvider(); provider.setRestTemplate(restTemplate); OAuth2AccessToken token = null; try { token = provider.obtainAccessToken(resource, request); } catch (OAuth2AccessDeniedException oauthEx) { HttpStatus status = HttpStatus.valueOf(oauthEx.getHttpErrorCode()); CloudFoundryException cfEx = new CloudFoundryException(status, oauthEx.getMessage()); cfEx.setDescription(oauthEx.getSummary()); throw cfEx; } return token; }
Example 11
Project: uaa-master File: HttpsIntegrationTest.java View source code |
@Test public void test_self_signed_cert_should_fail() throws Exception { try { test_self_signed_cert(false); fail("Self signed cert should not pass this test"); } catch (OAuth2AccessDeniedException x) { assertEquals(ResourceAccessException.class, x.getCause().getClass()); } }