List of usage examples for org.apache.http.auth AuthenticationException AuthenticationException
public AuthenticationException(final String message)
From source file:com.mxhero.plugin.cloudstorage.onedrive.api.OneDrive.java
/** * Perform entire 4 steps process of Redeem OneDrive for Business API according to documentation {@link https://dev.onedrive.com/auth/aad_oauth.htm} * /* ww w . j a v a 2 s . c o m*/ * Step 1: Redeem the authorization code for tokens * Step 2: Discover the OneDrive for Business resource URI * Step 3: Redeem refresh token for an access token to call OneDrive API * Step 4: It is not documented but retriever Email address for user access token. * * @param redeemRequest the redeem request * @return the one drive business object which encapsulate credential info, such as access and refresh token and sharepoint URL for further OneDrive for Business API calls * @throws AuthenticationException the authentication exception */ public static BusinessCredential redeemBusiness(RedeemRequest redeemRequest) throws AuthenticationException { try { Map<String, Object> redeemBusinessApiResource = redeemBusinessApiResource( ApiEnviroment.graphApiUrl.getValue(), redeemRequest.getClientId(), redeemRequest.getClientSecret(), redeemRequest.getRedirectUri(), redeemRequest.getCode()); Map<String, Object> redeemBusinessApi = redeemBusinessApiResource( redeemRequest.getSharepointResourceId(), redeemRequest.getClientId(), redeemRequest.getClientSecret(), redeemRequest.getRedirectUri(), redeemRequest.getCode()); String userEmail = businessEmail((String) redeemBusinessApiResource.get("access_token")); logger.debug("Redeem for OneDrive Business API sharepoint specific URL {}", redeemBusinessApi); return BusinessCredential.builder().sharepointEndpointUri(redeemRequest.getSharepointEndpointUri()) .sharepointResourceId(redeemRequest.getSharepointResourceId()) .accessToken((String) redeemBusinessApi.get("access_token")) .refreshToken((String) redeemBusinessApi.get("refresh_token")) .tokenType((String) redeemBusinessApi.get("token_type")).user(userEmail).build(); } catch (Exception e) { throw new AuthenticationException( "Could not redeem code " + redeemRequest.getCode() + " for OneDrive Business API"); } }
From source file:freeipa.client.negotiation.JBossNegotiateScheme.java
/** * Produces Negotiate authorization Header based on token created by processChallenge. * * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials * from JAAS will be used instead. * @param request The request being authenticated * * @throws AuthenticationException if authorization string cannot be generated due to an authentication failure * * @return an Negotiate authorization Header *///from w w w . j a v a2 s . c o m @Override public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (state != State.CHALLENGE_RECEIVED) { throw new IllegalStateException("Negotiation authentication process has not been initiated"); } try { String key = null; if (isProxy()) { key = ExecutionContext.HTTP_PROXY_HOST; } else { key = ExecutionContext.HTTP_TARGET_HOST; } HttpHost host = (HttpHost) context.getAttribute(key); if (host == null) { throw new AuthenticationException("Authentication host is not set " + "in the execution context"); } String authServer; if (!this.stripPort && host.getPort() > 0) { authServer = host.toHostString(); } else { authServer = host.getHostName(); } System.out.println("init " + authServer); final Oid negotiationOid = new Oid(SPNEGO_OID); final GSSManager manager = GSSManager.getInstance(); final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); if (token == null) { token = new byte[0]; } token = gssContext.initSecContext(token, 0, token.length); if (token == null) { state = State.FAILED; throw new AuthenticationException("GSS security context initialization failed"); } state = State.TOKEN_GENERATED; String tokenstr = new String(base64codec.encode(token)); System.out.println("Sending response '" + tokenstr + "' back to the auth server"); CharArrayBuffer buffer = new CharArrayBuffer(32); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Negotiate "); buffer.append(tokenstr); return new BufferedHeader(buffer); } catch (GSSException gsse) { state = State.FAILED; if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.NO_CRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) throw new AuthenticationException(gsse.getMessage(), gsse); // other error throw new AuthenticationException(gsse.getMessage()); } }
From source file:org.ohmage.sync.StreamSyncAdapterTest.java
public void testOnPerformSyncForStreams_authErrorUploading_restartsBatch() throws Exception { Streams fakeStreams = new Streams(); fakeStreams.add(fakeStream);//from ww w . jav a2 s. c o m when(fakeWriter.moveToNextBatch()).thenReturn(true, false); whenAccountStillExists(); when(fakeOhmageService.uploadStreamData(fakeStreamId, fakeStreamVersion, fakeWriter)) .thenThrow(new AuthenticationException("")); mSyncAdapter.performSyncForStreams(fakeAccount, fakeStreams, fakeWriter, fakeSyncResult); verify(fakeWriter).restartBatch(); }
From source file:org.ohmage.auth.AuthenticatorTest.java
public void testGetAuthToken_authErrorUsingRefreshToken_notifiesUser() throws Exception { setAuthTokenCached(false);//from w ww . j av a2s . c om setAccountRefreshToken(); setAccessTokenFailure(refreshToken, new AuthenticationException("")); Bundle data = mAuthenticator.getAuthToken(null, fakeAccount, AuthUtil.AUTHTOKEN_TYPE, null); verifyNotifyUserBundle(data); }
From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.JBossNegotiateScheme.java
/** * Produces Negotiate authorization Header based on token created by processChallenge. * /*from w w w . j a v a2 s . c o m*/ * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials * from JAAS will be used instead. * @param request The request being authenticated * * @throws AuthenticationException if authorisation string cannot be generated due to an authentication failure * * @return an Negotiate authorisation Header */ @Override public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (state != State.CHALLENGE_RECEIVED) { throw new IllegalStateException("Negotiation authentication process has not been initiated"); } try { String key = null; if (isProxy()) { key = ExecutionContext.HTTP_PROXY_HOST; } else { key = ExecutionContext.HTTP_TARGET_HOST; } HttpHost host = (HttpHost) context.getAttribute(key); if (host == null) { throw new AuthenticationException("Authentication host is not set " + "in the execution context"); } String authServer; if (!this.stripPort && host.getPort() > 0) { authServer = host.toHostString(); } else { authServer = host.getHostName(); } if (log.isDebugEnabled()) { log.debug("init " + authServer); } /* * Using the SPNEGO OID is the correct method. Kerberos v5 works for IIS but not JBoss. Unwrapping the initial token * when using SPNEGO OID looks like what is described here... * * http://msdn.microsoft.com/en-us/library/ms995330.aspx * * Another helpful URL... * * http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/ * tsec_SPNEGO_token.html * * Unfortunately SPNEGO is JRE >=1.6. */ /** Try SPNEGO by default, fall back to Kerberos later if error */ negotiationOid = new Oid(SPNEGO_OID); boolean tryKerberos = false; try { GSSManager manager = getManager(); GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); } catch (GSSException ex) { // BAD MECH means we are likely to be using 1.5, fall back to Kerberos MECH. // Rethrow any other exception. if (ex.getMajor() == GSSException.BAD_MECH) { log.debug("GSSException BAD_MECH, retry with Kerberos MECH"); tryKerberos = true; } else { throw ex; } } if (tryKerberos) { /* Kerberos v5 GSS-API mechanism defined in RFC 1964. */ log.debug("Using Kerberos MECH " + KERBEROS_OID); negotiationOid = new Oid(KERBEROS_OID); GSSManager manager = getManager(); GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); } if (token == null) { token = new byte[0]; } token = gssContext.initSecContext(token, 0, token.length); if (token == null) { state = State.FAILED; throw new AuthenticationException("GSS security context initialization failed"); } /* * IIS accepts Kerberos and SPNEGO tokens. Some other servers Jboss, Glassfish? seem to only accept SPNEGO. Below * wraps Kerberos into SPNEGO token. */ if (spengoGenerator != null && negotiationOid.toString().equals(KERBEROS_OID)) { token = spengoGenerator.generateSpnegoDERObject(token); } state = State.TOKEN_GENERATED; String tokenstr = new String(Base64.encodeBase64(token, false)); if (log.isDebugEnabled()) { log.debug("Sending response '" + tokenstr + "' back to the auth server"); } return new BasicHeader("Authorization", "Negotiate " + tokenstr); } catch (GSSException gsse) { state = State.FAILED; if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.NO_CRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) throw new AuthenticationException(gsse.getMessage(), gsse); // other error throw new AuthenticationException(gsse.getMessage()); } catch (IOException ex) { state = State.FAILED; throw new AuthenticationException(ex.getMessage()); } }
From source file:org.ohmage.auth.AuthenticatorTest.java
public void testGetAuthToken_authErrorUsingRefreshTokenAndGoogleAccount_triesToGetGoogleAuth() throws Exception { setAuthTokenCached(false);//from w ww . ja va2 s . c o m setAccountRefreshToken(); when(fakeOhmageService.getAccessToken(refreshToken)).thenThrow(new AuthenticationException("")) .thenReturn(token); setHasGoogleAccount(true); setGetGoogleAuthTokenResult(null); mAuthenticator.getAuthToken(null, fakeAccount, AuthUtil.AUTHTOKEN_TYPE, null); verify(fakeAccountManager).getUserData(fakeAccount, Authenticator.USER_DATA_GOOGLE_ACCOUNT); verify(fakeAuthHelper).googleAuthGetToken(fakeGoogleEmail); }
From source file:org.ohmage.sync.StreamSyncAdapterTest.java
public void testOnPerformSyncForStreams_authErrorAfterRefreshing_setsAuthExceptionInSyncResult() throws Exception { Streams fakeStreams = new Streams(); fakeStreams.add(fakeStream);/*from w ww. ja v a 2 s . co m*/ when(fakeWriter.moveToNextBatch()).thenReturn(true, false); whenAccountStillExists(); when(fakeOhmageService.uploadStreamData(fakeStreamId, fakeStreamVersion, fakeWriter)) .thenThrow(new AuthenticationException("")); mSyncAdapter.performSyncForStreams(fakeAccount, fakeStreams, fakeWriter, fakeSyncResult); assertEquals(1, fakeSyncResult.stats.numAuthExceptions); }
From source file:net.java.sip.communicator.service.httputil.HttpUtils.java
/** * Executes the method and return the result. Handle ask for password * when hitting password protected site. * Keep asking for password till user clicks cancel or enters correct * password. When 'remember password' is checked password is saved, if this * password and username are not correct clear them, if there are correct * they stay saved./*w w w. j av a 2 s. c o m*/ * @param httpClient the configured http client to use. * @param req the request for now it is get or post. * @param redirectHandler handles redirection, should we redirect and * the actual redirect. * @param parameters if we are redirecting we can use already filled * username and password in order to avoid asking the user twice. * * @return the result http entity. */ private static HttpEntity executeMethod(DefaultHttpClient httpClient, HttpRequestBase req, RedirectHandler redirectHandler, List<NameValuePair> parameters) throws Throwable { // do it when response (first execution) or till we are unauthorized HttpResponse response = null; int redirects = 0; while (response == null || response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) { // if we were unauthorized, lets clear the method and recreate it // for new connection with new credentials. if (response != null && (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN)) { if (logger.isDebugEnabled()) logger.debug("Will retry http connect and " + "credentials input as latest are not correct!"); throw new AuthenticationException("Authorization needed"); } else response = httpClient.execute(req); // if user click cancel no need to retry, stop trying if (!((HTTPCredentialsProvider) httpClient.getCredentialsProvider()).retry()) { if (logger.isDebugEnabled()) logger.debug("User canceled credentials input."); break; } // check for post redirect as post redirects are not handled // automatically // RFC2616 (10.3 Redirection 3xx). // The second request (forwarded method) can only be a GET or HEAD. Header locationHeader = response.getFirstHeader("location"); if (locationHeader != null && req instanceof HttpPost && (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || response.getStatusLine().getStatusCode() == HttpStatus.SC_SEE_OTHER) && redirects < MAX_REDIRECTS) { HttpRequestBase oldreq = req; oldreq.abort(); String newLocation = locationHeader.getValue(); // lets ask redirection handler if any if (redirectHandler != null && redirectHandler.handleRedirect(newLocation, parameters)) { return null; } req = new HttpGet(newLocation); req.setParams(oldreq.getParams()); req.setHeaders(oldreq.getAllHeaders()); redirects++; response = httpClient.execute(req); } } // if we finally managed to login return the result. if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return response.getEntity(); } // is user has canceled no result needed. return null; }
From source file:org.ohmage.auth.AuthenticatorTest.java
public void testGetAuthToken_userRecoverableErrorWhenAuthtokenFromGoogle_sendsErrorViaIntent() throws Exception { setAuthTokenCached(false);/*w ww.j av a 2 s .c om*/ setAccountRefreshToken(); setAccessTokenFailure(refreshToken, new AuthenticationException("")); setHasGoogleAccount(true); UserRecoverableAuthException fakeException = new UserRecoverableAuthException("msg", new Intent()); setGetGoogleAuthTokenResult(fakeException); Bundle data = mAuthenticator.getAuthToken(null, fakeAccount, AuthUtil.AUTHTOKEN_TYPE, null); Intent intent = data.getParcelable(AccountManager.KEY_INTENT); assertNotNull(intent); assertEquals(intent.getComponent().getClassName(), AuthenticatorActivity.class.getName()); assertEquals(fakeException, intent.getSerializableExtra(AuthenticatorActivity.EXTRA_HANDLE_USER_RECOVERABLE_ERROR)); }