下面列出了org.apache.http.client.AuthenticationHandler#org.apache.http.auth.AuthenticationException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Definition readWsdl( WSDLReader wsdlReader, String uri, String username, String password ) throws WSDLException, HopException, AuthenticationException {
try {
HttpProtocol http = new HttpProtocol();
Document doc = XmlHandler.loadXmlString( http.get( wsdlURI.toString(), username, password ), true, false );
if ( doc != null ) {
return ( wsdlReader.readWSDL( doc.getBaseURI(), doc ) );
} else {
throw new HopException( "Unable to get document." );
}
} catch ( MalformedURLException mue ) {
throw new HopException( mue );
} catch ( AuthenticationException ae ) {
// re-throw this. If not IOException seems to catch it
throw ae;
} catch ( IOException ioe ) {
throw new HopException( ioe );
}
}
public Token authenticate() throws AuthenticationException {
Token bьььь044Cь = Token.bьььь044Cь(Type.SHORT_TERM);
bьььь044Cь.loadToken(this.b04140414Д0414ДД);
b0439ййййй(bьььь044Cь);
if (bьььь044Cь.isTokenExpired()) {
Log.d(bДД04140414ДД, "Credentials expired or do not exist. Requesting new token.");
rrcrcc login = new cccrrr(this.b04140414Д0414ДД, this.bД041404140414ДД, ccccrr.getAppName(), ccccrr.useSSL()).login(this.bД0414Д0414ДД.getUserName(), this.bД0414Д0414ДД.getPassword());
if (login.requestUnauthorized()) {
b0449щ0449044904490449();
throw new AuthenticationException();
} else if (login.requestTimedOut()) {
bщ04490449044904490449();
if (((bХ0425Х042504250425 + b04250425Х042504250425) * bХ0425Х042504250425) % bХХ0425042504250425 != bХ04250425042504250425) {
bХ0425Х042504250425 = 30;
bХ04250425042504250425 = 78;
}
return bьььь044Cь;
}
}
bщщ0449044904490449(bьььь044Cь);
return bьььь044Cь;
}
/**
* Send HTTP GET request to {@link #endpointUrl}, updates {@link #csrfToken}
* token
*
* @return true if {@link #endpointUrl} is accessible
* @throws IOException
* @throws ClientProtocolException
* @throws AuthenticationException
*/
protected void fetchCsrfTokenFromHac() throws ClientProtocolException, IOException, AuthenticationException {
final HttpGet getRequest = new HttpGet(getEndpointUrl());
try {
final HttpResponse response = httpClient.execute(getRequest, getContext());
final String responseString = new BasicResponseHandler().handleResponse(response);
csrfToken = getCsrfToken(responseString);
if (StringUtil.isBlank(csrfToken)) {
throw new AuthenticationException(ErrorMessage.CSRF_TOKEN_CANNOT_BE_OBTAINED);
}
} catch (UnknownHostException error) {
final String errorMessage = error.getMessage();
final Matcher matcher = HACPreferenceConstants.HOST_REGEXP_PATTERN.matcher(getEndpointUrl());
if (matcher.find() && matcher.group(1).equals(errorMessage)) {
throw new UnknownHostException(
String.format(ErrorMessage.UNKNOWN_HOST_EXCEPTION_MESSAGE_FORMAT, matcher.group(1)));
}
throw error;
}
}
@Override
public Header authenticate(Credentials credentials, HttpRequest request, HttpContext context)
throws AuthenticationException {
Args.notNull(credentials, "Credentials");
Args.notNull(request, "HTTP request");
// the bearer token is stored in the password field, not credentials.getUserPrincipal().getName()
String bearerToken = credentials.getPassword();
CharArrayBuffer buffer = new CharArrayBuffer(64);
if (isProxy()) {
buffer.append("Proxy-Authorization");
} else {
buffer.append("Authorization");
}
buffer.append(": Bearer ");
buffer.append(bearerToken);
return new BufferedHeader(buffer);
}
protected static void processStandardHttpResponseCodes(HttpResponse httpResponse) throws AuthenticationException, IOException {
int code = httpResponse.getStatusLine().getStatusCode();
Log.d(TAG, "Response http code: " + code);
if (code >= 200 && code <= 299)
return;
if (code == HttpStatus.SC_UNAUTHORIZED || code == HttpStatus.SC_FORBIDDEN) {
String OTP = getHeaderValue(httpResponse, "X-GitHub-OTP");
if (code == HttpStatus.SC_UNAUTHORIZED && OTP != null && OTP.contains("required")) {
throw new OTPAuthenticationException(Utils.trimToNull(OTP.replace("required;", "")));
}
throw new AuthenticationException("Authentication problem: " + getResponseContentAsString(httpResponse));
} else if (code == HttpStatus.SC_BAD_REQUEST || code == HttpStatus.SC_NOT_FOUND) {
throw new InvalidObjectException("HttpCode=" + code + " message: " + getResponseContentAsString(httpResponse));
} else {
throw new IOException("HttpCode=" + code + " message: " + getResponseContentAsString(httpResponse));
}
}
private void processChallenges(
final Map<String, Header> challenges,
final AuthState authState,
final AuthenticationHandler authHandler,
final HttpResponse response,
final HttpContext context)
throws MalformedChallengeException, AuthenticationException {
AuthScheme authScheme = authState.getAuthScheme();
if (authScheme == null) {
// Authentication not attempted before
authScheme = authHandler.selectScheme(challenges, response, context);
authState.setAuthScheme(authScheme);
}
String id = authScheme.getSchemeName();
Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
if (challenge == null) {
throw new AuthenticationException(id +
" authorization challenge expected, but not found");
}
authScheme.processChallenge(challenge);
if (DEBUG) {
Logger.debug("Authorization challenge processed");
}
}
private Definition readWsdl( WSDLReader wsdlReader, String uri, String username, String password ) throws WSDLException, KettleException, AuthenticationException {
try {
HTTPProtocol http = new HTTPProtocol();
Document doc = XMLHandler.loadXMLString( http.get( wsdlURI.toString(), username, password ), true, false );
if ( doc != null ) {
return ( wsdlReader.readWSDL( doc.getBaseURI(), doc ) );
} else {
throw new KettleException( "Unable to get document." );
}
} catch ( MalformedURLException mue ) {
throw new KettleException( mue );
} catch ( AuthenticationException ae ) {
// re-throw this. If not IOException seems to catch it
throw ae;
} catch ( IOException ioe ) {
throw new KettleException( ioe );
}
}
@Test
public void httpClientGetsClosed() throws IOException, AuthenticationException {
CloseableHttpClient httpClient = Mockito.mock( CloseableHttpClient.class );
CloseableHttpResponse response = Mockito.mock( CloseableHttpResponse.class );
HTTPProtocol httpProtocol = new HTTPProtocol() {
@Override CloseableHttpClient openHttpClient( String username, String password ) {
return httpClient;
}
};
String urlAsString = "http://url/path";
when( httpClient.execute( Matchers.argThat( matchesGet() ) ) ).thenReturn( response );
StatusLine statusLine = new BasicStatusLine( new ProtocolVersion( "http", 2, 0 ), HttpStatus.SC_OK, "blah" );
BasicHttpEntity entity = new BasicHttpEntity();
String content = "plenty of mocks for this test";
entity.setContent( new ByteArrayInputStream( content.getBytes() ) );
when( response.getEntity() ).thenReturn( entity );
when( response.getStatusLine() ).thenReturn( statusLine );
assertEquals( content, httpProtocol.get( urlAsString, "", "" ) );
verify( httpClient ).close();
}
/**
* Performs a get on urlAsString using username and password as credentials.
* <p>
* If the status code returned not -1 and 401 then the contents are returned. If the status code is 401 an
* AuthenticationException is thrown.
* <p>
* All other values of status code are not dealt with but logic can be added as needed.
*
* @param urlAsString
* @param username
* @param password
* @return
* @throws AuthenticationException
* @throws IOException
*/
public String get( String urlAsString, String username, String password )
throws IOException, AuthenticationException {
HttpClient httpClient;
HttpGet getMethod = new HttpGet( urlAsString );
if ( !Utils.isEmpty( username ) ) {
HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
clientBuilder.setCredentials( username, password );
httpClient = clientBuilder.build();
} else {
httpClient = HttpClientManager.getInstance().createDefaultClient();
}
HttpResponse httpResponse = httpClient.execute( getMethod );
int statusCode = httpResponse.getStatusLine().getStatusCode();
StringBuilder bodyBuffer = new StringBuilder();
if ( statusCode != -1 ) {
if ( statusCode != HttpStatus.SC_UNAUTHORIZED ) {
// the response
InputStreamReader inputStreamReader = new InputStreamReader( httpResponse.getEntity().getContent() );
int c;
while ( ( c = inputStreamReader.read() ) != -1 ) {
bodyBuffer.append( (char) c );
}
inputStreamReader.close();
} else {
throw new AuthenticationException();
}
}
// Display response
return bodyBuffer.toString();
}
/**
* Load and parse the WSDL file using the wsdlLocator.
*
* @param wsdlLocator A WSDLLocator instance.
* @param username to use for authentication
* @param password to use for authentication
* @return wsdl Definition.
* @throws WSDLException on error.
*/
private Definition parse(WSDLLocator wsdlLocator, String username, String password ) throws WSDLException,
HopException, AuthenticationException {
WSDLReader wsdlReader = getReader();
try {
return wsdlReader.readWSDL( wsdlLocator );
} catch ( WSDLException we ) {
readWsdl( wsdlReader, wsdlURI.toString(), username, password );
return null;
}
}
/**
* @deprecated (4.2) Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
*/
@Deprecated
public Header authenticate(
final Credentials credentials,
final HttpRequest request ) throws AuthenticationException {
return authenticate(credentials, request, null);
}
public void run() {
try {
this.b043Dн043Dннн.authenticate();
if (((b0417041704170417ЗЗ + b0417ЗЗЗ0417З) * b0417041704170417ЗЗ) % bЗ041704170417ЗЗ != bЗЗЗЗ0417З) {
b0417041704170417ЗЗ = bЗЗ04170417ЗЗ();
bЗЗЗЗ0417З = bЗЗ04170417ЗЗ();
}
} catch (AuthenticationException e) {
try {
e.printStackTrace();
} catch (Exception e2) {
throw e2;
}
}
}
@Override
@Deprecated
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
return authenticate(credentials, request, null);
}
private void shouldReturn401AndGivenMessage(String uri, String username, String password, String content, String message) throws IOException, AuthenticationException {
HttpResponse response = put(uri, username, password, content);
assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
assertNotNull(result);
assertTrue(result.contains(message));
}
private void shouldReturn200AndSuccessMessage(String uri, String username, String password, String content) throws IOException, AuthenticationException {
HttpResponse deployResponse = put(uri, username, password, content);
assertEquals(HttpStatus.SC_OK, deployResponse.getStatusLine().getStatusCode());
String result = IOUtils.toString(deployResponse.getEntity().getContent(), StandardCharsets.UTF_8);
assertNotNull(result);
assertEquals("Success", result);
if (StringUtils.isEmpty(content)) {
return;
}
assertEquals(HttpStatus.SC_OK, super.getAuthenticated(uri, username, password).getStatusCode());
assertEquals(content, super.getAuthenticated(uri, username, password).parseAsString());
}
private Header basicSchema(HttpPost request) {
try {
return new BasicScheme().authenticate(getCredentials(configurationProvider), request, null);
} catch (AuthenticationException e) {
LOG.error("Could not initialize BasicSchema");
}
return null;
}
/**
* Retrieves csrf token from response body
*
* @param responseBody
* response body of GET method
* @return csrf token
* @throws AuthenticationException
*/
protected String getCsrfToken(String responseBody) throws AuthenticationException {
if (StringUtil.isBlank(responseBody)) {
throw new AuthenticationException(ErrorMessage.CSRF_RESPONSE_CANNOT_BE_BLANK);
}
final Document document = Jsoup.parse(responseBody);
return document.select(Meta.CSRF_META_TAG).attr(Meta.CSRF_META_TAG_CONTENT);
}
public static void fileUpload() throws IOException {
File file = new File("/home/vigneshwaran/VIGNESH/nu-test5.txt");
DefaultHttpClient httpclient = new DefaultHttpClient();
UsernamePasswordCredentials upc = new UsernamePasswordCredentials("[email protected]", "");
HttpPost httppost = new HttpPost("http://api.localhostr.com/file");
try {
httppost.addHeader(new BasicScheme().authenticate(upc, httppost));
} catch (AuthenticationException ex) {
Logger.getLogger(LocalhostrUploaderPlugin.class.getName()).log(Level.SEVERE, null, ex);
}
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("name", new StringBody(file.getName()));
mpEntity.addPart("file", cbFile);
httppost.setEntity(mpEntity);
System.out.println("Now uploading your file into localhost...........................");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
String tmp = EntityUtils.toString(resEntity);
System.out.println(tmp);
downloadlink = tmp.substring(tmp.indexOf("http:"));
downloadlink = downloadlink.substring(0, downloadlink.indexOf("\""));
System.out.println("download link : " + downloadlink);
}
// uploadresponse = response.getLastHeader("Location").getValue();
// System.out.println("Upload response : " + uploadresponse);
}
public Credentials addCredentials(final HttpRequestBase httpRequest) {
Credentials credentials = null;
if (user != null) {
credentials = new UsernamePasswordCredentials(user, password != null ? password : "");
try {
httpRequest.addHeader(new BasicScheme().authenticate(credentials, httpRequest, null));
} catch (final AuthenticationException e) {
throw new ArangoDBException(e);
}
}
return credentials;
}
public static void addCredentialsToRequest(HttpUriRequest request) {
String principal = SubjectUtils.getCurrentEffectivePrincipalName();
if ( principal != null ) {
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(principal, PASSWORD_PLACEHOLDER);
try {
request.addHeader(new BasicScheme().authenticate(credentials, request, null));
} catch (AuthenticationException e) {
// impossible
}
}
}
public static void addCredentialsToRequest(HttpUriRequest request) {
String principal = SubjectUtils.getCurrentEffectivePrincipalName();
if ( principal != null ) {
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(principal, PASSWORD_PLACEHOLDER);
try {
request.addHeader(new BasicScheme().authenticate(credentials, request, null));
} catch (AuthenticationException e) {
// impossible
}
}
}
public static Response<?> postNoData(Context context, GHCredentials apiCredentials, String url, Map<String, String> headers) throws
URISyntaxException, IOException, AuthenticationException {
if (!Utils.isInternetConnectionAvailable(context))
throw new NoRouteToHostException("Network not available");
Log.d(TAG, "Going to perform POST request to " + url);
try {
URI uri = new URI(url);
DefaultHttpClient httpClient = prepareHttpClient(uri);
HttpPost httpPost = new HttpPost(uri);
setAuthenticationHeader(httpPost, apiCredentials);
setHeaders(httpPost, headers);
// create response object here to measure request duration
Response<String> ret = new Response<String>();
ret.requestStartTime = System.currentTimeMillis();
HttpResponse httpResponse = httpClient.execute(httpPost);
parseResponseHeaders(context, httpResponse, ret);
processStandardHttpResponseCodes(httpResponse);
ret.snapRequestDuration();
writeReponseInfo(ret, context);
return ret;
} catch (IOException e) {
logGithubAPiCallError(context, e);
throw e;
}
}
public static Response<String> deleteToURL(Context context, GHCredentials apiCredentials, String url, Map<String, String> headers)
throws URISyntaxException, IOException, AuthenticationException {
if (!Utils.isInternetConnectionAvailable(context))
throw new NoRouteToHostException("Network not available");
try {
URI uri = new URI(url);
DefaultHttpClient httpClient = prepareHttpClient(uri);
HttpDelete httpPut = new HttpDelete(uri);
setAuthenticationHeader(httpPut, apiCredentials);
setHeaders(httpPut, requestGzipCompression(headers));
// create response object here to measure request duration
Response<String> ret = new Response<String>();
ret.requestStartTime = System.currentTimeMillis();
HttpResponse httpResponse = httpClient.execute(httpPut);
parseResponseHeaders(context, httpResponse, ret);
processStandardHttpResponseCodes(httpResponse);
ret.data = getResponseContentAsString(httpResponse);
ret.snapRequestDuration();
writeReponseInfo(ret, context);
return ret;
} catch (IOException e) {
logGithubAPiCallError(context, e);
throw e;
}
}
/**
* @param lastModified timestamp used in "If-Modified-Since" http header, can be null
* @return null if lastModified used and nothing new
* @throws InvalidObjectException
* @throws NoRouteToHostException
* @throws AuthenticationException
* @throws IOException
* @throws JSONException
* @throws URISyntaxException
*/
protected NotificationStream readNotificationStreamFromServer(String lastModified) throws InvalidObjectException, NoRouteToHostException,
AuthenticationException, IOException, JSONException, URISyntaxException {
NotificationStreamParser.IRepoVisibilityAdapter rva = createRepoVisibilityAdapter();
String url = prepareNotificationLoadingURL(rva);
Map<String, String> headers = null;
if (lastModified != null) {
headers = new HashMap<String, String>();
headers.put("If-Modified-Since", lastModified);
}
Response<JSONArray> resp = RemoteSystemClient.getJSONArrayFromUrl(context, authenticationManager.getGhApiCredentials(context), url, headers);
if (resp.notModified)
return null;
NotificationStream ns = NotificationStreamParser.parseNotificationStream(null, resp.data, rva);
ns.setLastModified(resp.lastModified);
if (lastModified == null)
ns.setLastFullUpdateTimestamp(System.currentTimeMillis());
//handle paging
while (resp.linkNext != null) {
resp = RemoteSystemClient.getJSONArrayFromUrl(context, authenticationManager.getGhApiCredentials(context), resp.linkNext, headers);
NotificationStreamParser.parseNotificationStream(ns, resp.data, rva);
}
return ns;
}
private String remoteLogin(Context context, GHCredentials cred, String otp) throws JSONException, NoRouteToHostException, AuthenticationException,
ClientProtocolException, URISyntaxException, IOException {
Map<String, String> headers = null;
otp = Utils.trimToNull(otp);
if (otp != null) {
headers = new HashMap<String, String>();
headers.put("X-GitHub-OTP", otp);
}
String content = GH_AUTH_REQ_CONTENT.replace("*fp*", System.currentTimeMillis() + "");
Response<String> resp = RemoteSystemClient.putToURL(context, cred, GH_AUTH_REQ_URL, headers, content);
JSONObject jo = new JSONObject(resp.data);
return jo.getString("token");
}
protected WatchedRepositories readFromServer(String url) throws InvalidObjectException, NoRouteToHostException, AuthenticationException, IOException,
JSONException, URISyntaxException {
Response<JSONArray> resp = RemoteSystemClient.getJSONArrayFromUrl(context, authenticationManager.getGhApiCredentials(context), url, null);
if (resp.notModified)
return null;
WatchedRepositories ns = WatchedRepositoriesParser.parseNotificationStream(resp.data);
ns.setLastFullUpdateTimestamp(System.currentTimeMillis());
return ns;
}
@Test
public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
final HttpPost request = new HttpPost(SAMPLE_URL);
request.setEntity(new StringEntity("in the body of the POST"));
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");
request.addHeader(new BasicScheme().authenticate(creds, request, null));
instance.execute(request);
}
@Test
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
httpPost.setEntity(new StringEntity("test post"));
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
/**
* Performs a get on urlAsString using username and password as credentials.
* <p>
* If the status code returned not -1 and 401 then the contents are returned. If the status code is 401 an
* AuthenticationException is thrown.
* <p>
* All other values of status code are not dealt with but logic can be added as needed.
*
* @param urlAsString The url to connect to
* @param username Basic Authentication username
* @param password Basic Authentication password
* @return If the status code returned not -1 and 401 then the contents are returned. If the status code is 401 an
* AuthenticationException is thrown.
* @throws AuthenticationException
* @throws IOException
*/
public String get( String urlAsString, String username, String password )
throws IOException, AuthenticationException {
HttpGet getMethod = new HttpGet( urlAsString );
try ( CloseableHttpClient httpClient = openHttpClient( username, password ) ) {
HttpResponse httpResponse = httpClient.execute( getMethod );
int statusCode = httpResponse.getStatusLine().getStatusCode();
StringBuilder bodyBuffer = new StringBuilder();
if ( statusCode != -1 ) {
if ( statusCode != HttpStatus.SC_UNAUTHORIZED ) {
// the response
InputStreamReader inputStreamReader = new InputStreamReader( httpResponse.getEntity().getContent() );
int c;
while ( ( c = inputStreamReader.read() ) != -1 ) {
bodyBuffer.append( (char) c );
}
inputStreamReader.close();
} else {
throw new AuthenticationException();
}
}
// Display response
return bodyBuffer.toString();
}
}
@Test
public void getsAResponse() throws IOException, AuthenticationException {
stubFor( get( urlEqualTo( "/some/thing" ) )
.willReturn( aResponse()
.withHeader( "Content-Type", "text/plain" )
.withBody( HELLO_WORLD ) ) );
HTTPProtocol httpProtocol = new HTTPProtocol();
assertEquals( HELLO_WORLD, httpProtocol.get( "http://localhost:55555/some/thing", "", "" ) );
}