Azure Devops Java HttpsURLConnection authorization - azure-devops

HttpsURLConnection problem, getting a 401 error when running an ADO API to create a new work item. It works from curl command line, but not in Java.
I have tried various suggestions and alternatives I have found, but so far no luck. I am using a PAT generated from ADO for password, so not sure if that is related to the problem. I tried revoking the PAT and regenerate, but it did not help. Can someone tell me what I am doing wrong here?
This works:
curl -u me:mypassword -x myproxy.corp:80 \
'https://dev.azure.com/mycompany/_apis/wit/workitems/$Bug?api-version=6.0' \
-H 'Content-Type: application/json-patch+json' \
--data-binary '[{"op":"add","path":"/fields/System.Title","value":"Test API"}]'
But this does not work. It gets a 401 error:
public static void createIncident() {
String input = "[{\"op\":\"add\",\"path\":\"/fields/System.Title\",\"value\":\"Test API\"}]";
String userpass="me:mypassword";
String basicAuth = "Basic :" + new String(Base64.getEncoder().encode(userpass.getBytes()));
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("myproxy.corp", 80));
try {
URL url = new URL("https://dev.azure.com/mycompany/_apis/wit/workitems/$Bug?api-version=6.0");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(proxy);
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Accept", "application/json-patch+json");
conn.setRequestProperty("Content-Type", "application/json-patch+json");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpsURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

C# Download File from HTTP File Directory getting 401 error or 403 error

I’m trying to download several files from a local network device:
http file directory
I want to write a code that will automatically download all those .avi files to my pc drive.
I have 2 problems:
Problem 1: AUTHENTICATING using WebClient class only.
If I use WebClient class only to connect, I get a 401 Unauthorized error.
Code:
try
{
using (WebClient myWebClient = new WebClient())
{
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = new NetworkCredential("user", "pword");
String userName = "user";
String passWord = "pword";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
myWebClient.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
Console.WriteLine("Header AUTHORIZATION: "+ myWebClient.Headers[HttpRequestHeader.Authorization].ToString());
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}
Error Message: Failure to authenticate
401 Unauthorized Error
Problem 2: Was able to authenticate using WebProxy class but can’t download . Getting 403 Not found error.
Code:
try
{
using (WebClient myWebClient = new WebClient())
{
WebProxy wp = new WebProxy("http://192.168.2.72:81/sd/20170121/record000/",false);
wp.Credentials = new NetworkCredential("user","pword");
Console.WriteLine("Web Proxy: " + wp.Address);
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = wp.Credentials;
myWebClient.Proxy = wp;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\"\n\n", filename, wp.Address);
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}
Error Message: 403 Not Found
DOWNLOAD ERROR: System.Net.WebException: The remote server returned an error: (404) Not Found.
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at System.Net.WebClient.DownloadFile(String address, String fileName)
at ConsoleApplication2.Program.Main(String[] args) in C:\Users\Gordon\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 139
Please help me identify if there are any mistakes in my code or is there a better way to submit credentials and download all the files.
Thanks in advance!
I'm not Dot Net developer, I'm just sharing my opinion.
In the second point you have mentioned that you are getting 403 which is the Http status code for Acces Denied. I feel your credentials are not valid or you don't have privilege to do the operation.

How to access Spring REST API in JHipster with standalone

i need to call de jhipster rest service in a java sheduling standalone.
but i dont know how, I try with HttpClient libraries and use CredentialsProvider to set de username and password
I cant login use this
HttpGet httpget = new HttpGet("http://localhost:8080/#Login");
but when I try to get de rest jason api i get HTTP 401 Unauthorized
I see de Gatlin Test make in scala and its like there are simulating a web-browser.
So I am stacking here, and I will apreciate anybody that can give me some suggest in how to do these.
These is the code
HttpHost targetHost = new HttpHost("localhost", 8080, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(DEFAULT_USER,DEFAULT_PASS));
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
client = HttpClientBuilder.create().build();
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Estatus Codee : " +statusCode);
String output;
In this call a have de estatus 401
response = client.execute(new HttpGet(URL_PROMOTORES), context);
statusCode = response.getStatusLine().getStatusCode();
System.out.println("Estatus Codee : " +statusCode);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
response.close();
client.close();
Thanks in advance.
I don't think you should use basicAuth because it is for HTTP basic authentication (RFC 2617) which is different from what JHipster uses in your case login/password form encoded and session.

Authorisation issue while accessing a page from repository in CQ5.

I'm trying to hit a page which contains a xml structure. for that i'm using this code
#Reference
private SlingRepository repository;
adminSession = repository.loginAdministrative( repository.getDefaultWorkspace());
String pageUrl = "http://localhost:4504"+page+".abc.htm";
conn = (HttpURLConnection)new URL(pageUrl).openConnection();
conn.setRequestProperty("Accept-Charset", charset);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); // Do as if you'rusing Firefox 3.6.3
urlResponse = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader( new InputStreamReader(urlResponse) );
While accesing the page i'm getting this issue
org.apache.sling.auth.core.impl.SlingAuthenticator getAnonymousResolver: `Anonymous access not allowed by configuration - requesting credentials`
I'm logged in as an admin and whenever i'm directly hitting this urlfrom browser it is working properly bt while accessing it thriugh my code i'm getting this error.
any suggestion ?
If you are trying to call an url on an author instance, the following method I use in one of my projects might help (using apache commons HttpClient):
private InputStream getContent(final String url)
HttpClient httpClient = new HttpClient();
httpClient.getParams().setAuthenticationPreemptive(true);
httpClient.getState().setCredentials(new AuthScope(null, -1, null),
new UsernamePasswordCredentials("admin", "admin"));
try {
GetMethod get = new GetMethod(url);
httpClient.executeMethod(get);
if (get.getStatusCode() == HttpStatus.SC_OK) {
return get.getResponseBodyAsStream();
} else {
LOGGER.error("HTTP Error: ", get.getStatusCode());
}
} catch (HttpException e) {
LOGGER.error("HttpException: ", e);
} catch (IOException e) {
LOGGER.error("IOException: ", e);
}
}
Though at it is using admin:admin it only works on a local dev instance, if you are on a productive environment, I wouldn't put the admin password in plaintext, even though it is onyl code...
You are mixing up sling credentials & http credentials. While you are logged in at the sling-repository the http session is not aware of any authentication informations!

Activemq jolokia rest api for deleting a queue?

Is there a way to delete a queue with ActiveMQ rest api on 5.9.0? I know you can purge a queue with
"http://" + host + ":" + port + "/api/jolokia/exec/org.apache.activemq:brokerName=localhost,destinationName=" + queueName + ",destinationType=Queue,type=Broker/purge()";
But what is the one for deleting?
You should use the following URL pattern:
http://hostname:8161/hawtio/jolokia/exec/org.apache.activemq:type=Broker,brokerName=MyBroker/removeQueue(java.lang.String)/MyQueue
You can read about the format to access JMX operations thorugh jolokia here.
This one works.
curl --location --request GET 'http://localhost:8161/api/jolokia/exec/org.apache.activemq:type=Broker,brokerName=<brokerName>/removeQueue/<queueName>' --header 'Authorization: Basic <token>' \
Courtesy: brettPorter
Here is a java f'n that does it:
public static String removeQueue(String queueName) throws ClientProtocolException, IOException, URISyntaxException {
String username = "admin";
String password = "admin";
URI mqUrl = new URI( YOUR ACTIVE MQ URI HERE );
HttpHost targetHost = new HttpHost(mqUrl.getHost(), mqUrl.getPort(), "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
// Add AuthCache to the execution context
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
HttpClient client = HttpClientBuilder.create().build();
String uri = "http://" + mqUrl.getHost() + ":" + mqUrl.getPort() + "/hawtio/jolokia/exec/org.apache.activemq:type=Broker,brokerName=localhost/removeQueue/" + queueName;
HttpResponse response = client.execute(new HttpGet(uri), context);
if (response.getStatusLine().getStatusCode() != 200) {
throw new IOException(response.getStatusLine().toString());
}
return IOUtils.toString(response.getEntity().getContent());
}

Can't upload file to Google Drive from service account

I am trying to upload a file to google drive using google service account.
Driver Service
public static Drive getDriveService(String secretKeyFile) throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(DriveScopes.DRIVE)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(secretKeyFile))
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).setApplicationName("appl name").build();
return service;
}
Insert File
private static File insertFile(Drive service, String title, String description,String mimeType, String filename) {
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
Main Method
Drive service=null;
try {
String secretFile= "somedigit-privatekey.p12";
service = getDriveService(secretFile);
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
File insertFile = insertFile(service, "test title", "File description", "text/plain", "c:\\test.txt");
List list = service.files().list();
System.out.println("Files Id : "+insertFile.getId());
System.out.println("Count Files : "+list.size());
Now, my questions is :
How and where can i check that file was uploaded?
Why it returns the file ID but list.size() is zero.
It returns the download link also but when i paste that link in
browser it doesn't download any file.
You are creating a listing request but not executing it. Use execute method to make the request:
service.files().list().execute();
If you paste the download link into the browser, it will respond with 401, because your download request should also contain a valid Authorization header. Use the following snippet to download the file programmatically.
HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
InputStream stream = resp.getContent();
stream is an input stream for the file content.
Or add an Authorization: Bearer <access token> to the request you're making elsewhere.