Authorization failed while wget azure REST API - java

I am trying to collect azure metrics using REST api. I have a free subscription to azure account.
I am using the following wget to get the json message.
wget https://management.azure.com/subscriptions/XXXXXXX/resourceGroups/RG_SOUTH_INDIA/providers/Microsoft.Compute/virtualMachineScaleSets/linuxscal/metrics?api-version=2014-04-01
XXXXXXX- is my subscription id.
I get the following Error message.
Resolving management.azure.com... 13.67.231.219
Connecting to management.azure.com|13.67.231.219|:443... connected.
HTTP request sent, awaiting response... 401 Unauthorized
Authorization failed.
What is wrong with my subscription/Authorization?!!
Thanks in Advance for your help guys!! Am Stuck!!

You need to include an Authorization header with a Bearer token in your call:
GET /subscriptions?api-version=2015-01-01 HTTP/1.1
Host: management.azure.com
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json
Take a look at armclient, since you really don't want to do all this by hand (or by curl):
https://www.npmjs.com/package/armclient
// ES6
import ArmClient, { clientCredentials } from 'armclient';
const client = ArmClient({
subscriptionId: '111111-2222-3333333',
auth: clientCredentials({
tenantId: '444444-555555-666666666',
clientId: '777777-888888-999999999',
clientSecret: 'aaaabbbbbccccc' // or servicePrincipalPassword
})
});
Your /metrics call becomes:
client.get('/resourceGroups/RG_SOUTH_INDIA/providers/Microsoft.Compute/virtualMachineScaleSets/linuxscal/metrics', { 'api-version': '2014-04-01' })
.then((res) => {
console.log(res.body);
console.log(res.headers);
})
.catch((err) => {
console.log(err);
});

By specifying the option --user and --ask-password wget will ask for the credentials. Below is an example. Change the username and link to your needs
wget --user=username --ask-password https://YOUR_URL

Related

Unable to find /oauth/device/code Auth0 Java API

Is there an API to fetch the device code via Auth0 Java API, we use the following snippet in Go, the question is if there is a standard API or should we make a HTTP request call
url := "https://dev-foo.us.auth0.com/oauth/device/code"
payload := strings.NewReader("client_id=RO6N7mr&scope=openid&audience=https://dev-foo.us.auth0.com/api/v2/")
req, _ := http.NewRequest("POST", url, payload)
The documentation tells you that you need to send a POST request like the following:
POST https://YOUR_DOMAIN/oauth/device/code
Content-Type:
application/x-www-form-urlencoded
client_id=YOUR_CLIENT_ID&scope=SCOPE&audience=API_IDENTIFIER
and the response would look like
HTTP/1.1 200 OK
Content-Type: application/json
{
"device_code":"GmRh...k9eS",
"user_code":"WDJB-MJHT",
"verification_uri":"https://YOUR_DOMAIN/device",
"verification_uri_complete":"https://YOUR_DOMAIN/device?user_code=WDJB-MJHT",
"expires_in":900, //in seconds
"interval":5
}

Using Vert.x Web Client to send GET requests properly with headers

I have an internal endpoint that I am trying to send GET requests to with Vert.x Web Client with Java. So far, I am unable to successfully get any data back.
If I cURL the endpoint, it works just fine (these are internal endpoints). The service I am trying to send GET requests to requires a few headers , and data as well:
curl -H "Accept:application/json" -H "Content-Type:application/json" -H "alpha:192.168.10.20" -d '{"mutate":"*"}' http://my-endpoint.com/api/get-items
But if I try to use this in one of my router endpoints in Vert.x, I get an error:
WebClient webClient = WebClient.create(vertx);
webClient.get("http://my-endpoint.com/api/get-items")
.putHeader("Accept", "application/json")
.putHeader("Content-Type", "application/json")
.putHeader("alpha", "192.168.10.20")
.sendJsonObject(new JsonObject().put("mutate", "*"), ar -> {
if (ar.succeeded()) {
System.out.println("##### WEBCLIENT #####");
System.out.println(ar);
} else {
System.out.println("CAUSE: " + ar.cause().getMessage());
}
});
The error message I get from the else statement is:
CAUSE: Connection refused: localhost/127.0.0.1:80
What am I doing wrong? I've been using this for reference: Vert.x Web Client
===========================================
SOLUTION
===========================================
I had to change
webClient.get("http://my-endpoint.com/api/get-items")
to
webClient.post(80, "my-endpoint.com", "/api/get-items")
Also had to add .as(BodyCodec.jsonArray()) underneath the above line because the result I was getting was a Json Array.
You need to change
webClient.get("http://my-endpoint.com/api/get-items")
to
webClient.get(80, "my-endpoint.com", "/api/get-items")

HttpClientErrorException 406 null is thrown in rest template spring mvc [duplicate]

In my Ruby on Rails application I tried to upload an image through the POSTMAN REST client in Base64 format. When I POST the image I am getting a 406 Not Acceptable Response. When I checked my database, the image was there and was successfully saved.
What is the reason for this error, is there anything I need to specify in my header?
My request:
URL --- http://localhost:3000/exercises.json
Header:
Content-Type - application/json
Raw data:
{
"exercise": {
"subbodypart_ids": [
"1",
"2"
],
"name": "Exercise14"
},
"image_file_name": "Pressurebar Above.jpg",
"image":"******base64 Format*******"
}
Your operation did not fail.
Your backend service is saying that the response type it is returning is not provided in the Accept HTTP header in your Client request.
Ref: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Find out the response (content type) returned by Service.
Provide this (content type) in your request Accept header.
http://en.wikipedia.org/wiki/HTTP_status_code -> 406
406 Not Acceptable
The resource identified by the request is only capable of generating response entities which have content characteristics not
acceptable according to the accept headers sent in the request.
406 happens when the server cannot respond with the accept-header specified in the request.
In your case it seems application/json for the response may not be acceptable to the server.
You mentioned you're using Ruby on Rails as a backend. You didn't post the code for the relevant method, but my guess is that it looks something like this:
def create
post = Post.create params[:post]
respond_to do |format|
format.json { render :json => post }
end
end
Change it to:
def create
post = Post.create params[:post])
render :json => post
end
And it will solve your problem. It worked for me :)
"Sometimes" this can mean that the server had an internal error, and wanted to respond with an error message (ex: 500 with JSON payload) but since the request headers didn't say it accepted JSON, it returns a 406 instead. Go figure. (in this case: spring boot webapp).
In which case, your operation did fail. But the failure message was obscured by another.
You can also receive a 406 response when invalid cookies are stored or referenced in the browser - for example, when running a Rails server in Dev mode locally.
If you happened to run two different projects on the same port, the browser might reference a cookie from a different localhost session.
This has happened to me...tripped me up for a minute. Looking in browser > Developer Mode > Network showed it.
const request = require('request');
const headers = {
'Accept': '*/*',
'User-Agent': 'request',
};
const options = {
url: "https://example.com/users/6",
headers: headers
};
request.get(options, (error, response, body) => {
console.log(response.body);
});
Changing header to Accept: */* resolved my issue and make sure you don't have any other Accept Header
In my case, I added:
Content-Type: application/x-www-form-urlencoded
solved my problem completely.
If you are using 'request.js' you might use the following:
var options = {
url: 'localhost',
method: 'GET',
headers:{
Accept: '*/*'
}
}
request(options, function (error, response, body) {
...
})
In my case for a API in .NET-Core, the api is set to work with XML (by default is set to response with JSON), so I add this annotation in my Controller :
[Produces("application/xml")]
public class MyController : ControllerBase {...}
Thank you for putting me on the path !
It could also be due to a firewall blocking the request. In my case the request payload contained string properties - "like %abc%" and ampersand symbol "&" - which caused the firewall to think it is a security risk (eg. a sql injection attack) and it blocked the request. Note here the request does not actually go to the server but is returned at the firewall level itself.
In my case, there were no application server logs generated so I knew that the request did not actually reach the server and was blocked before that. The logs that helped me were Web application firewall (WAF) logs.

Custom error page on SPNEGO authentication failure

I have a Spring MVC REST endpoint which I successfully configured to be secured by Kerberos as recommended. On successful authentication everything works. The problem is when it comes to custom 401 error page.
I have it configured as (I'm spring-boot 1.3.5) as follows:
#Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401.html"));
}
This works nicely which I can confirm by switching to e.g. Basic auth and providing wrong credentials.
When back with Kerberos - if I access my secured endpoint with kinit in place everything works and in curl I see the detailed requests:
curl -v -u : --negotiate http://my-enpoint:8080/
> GET / HTTP/1.1
> Host: ...:8080
> User-Agent: curl/7.43.0
> Accept: */*
< HTTP/1.1 401 Unauthorized
< ...
< WWW-Authenticate: Negotiate
> GET / HTTP/1.1
> Host: ...:8080
> Authorization: Negotiate YIIH7 ...
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< ...
Now if I do kdestroy and do the curl again:
curl -v -u : --negotiate http://my-enpoint:8080/
> GET / HTTP/1.1
> Host:...8080
> User-Agent: curl/7.43.0
> Accept: */*
< HTTP/1.1 401 Unauthorized
< ...
< WWW-Authenticate: Negotiate
... and that's it. In this case spring returns 401 as expected response which is part of the handshake and therefore no error page is sent.
And here comes my two questions:
How can I return the 401 error page when the thing dies in the middle of the handshake?
How could spring possibly fallback to any other authentication as fallback (form, basic) if it tries to negotiate but there is no response from the client at all?
So back with my investigation ...
This behaviour I observed is expected. The clients (browser, curl) doesn't continue with authentication if they can't authenticate. The key to provide custom page is the SpnegoEntrypoint. It allows to specify forwardUrl in it and it's javadoc says:
Instantiates a new spnego entry point. This constructor enables
security configuration to use SPNEGO in combination with login form as
fallback for clients that do not support this kind of authentication.
The point is the forward url any resource which will be included in the first 401 response. You can include any page, not just form login. In my case I'm including custom 401 error page because I don't do any authentication fallback.
#Bean
public SpnegoEntryPoint spnegoEntryPoint() {
return new SpnegoEntryPoint("/error/401.html");
}
And then the communication looks like client sends GET and get's back 401 response with my custom error page in body. If the client is able to negotiate it ignores the response body completely and resubmits the request with appropriate token. If it can't authenticate it displays whatever it gets back - the custom error page.
As a response to your first question:
I had the same use case, but chose an alternative solution in which I extended the SpnegoEntryPoint with one that added a small JSON body to the response to be consumed by REST clients:
public class JsonSpnegoEntryPoint extends SpnegoEntryPoint {
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex)
throws IOException, ServletException {
response.getWriter().write("{\"message\": \"Spnego negotiate, expecting to be called with negotiate-flags set\"}");
super.commence(request, response, ex);
}
}

Dynamics CRM 2016.Web API Auth. I have token, now what?

Using ADAL libs for java I managed to get Access,Refresh and ID Tokens using my office365 credentials.
Now my intention is using REST Web APIs, my intention is to create an entity, as a proof of concept. Based on my experience with other venders and REST APIs, once you have a valid token, you just add it as a Authorization header like:
Authorization=Bearer 709709JHKLJHKJLhHKHKJHKH...etc
Is something similar to this in Dynamic CRM 2016?
Here here is nice info about composing a POST http request, but I am missing the Authorization part... Any idea guys?
Here is a valid GET request to pull back accounts.
GET https://<CRM DOMAIN>.com/api/data/v8.1/accounts HTTP/1.1
Authorization: Bearer:<TOKEN GOES HERE>
Host: <CRM DOMAIN>.com
And here is a valid POST
POST https://<CRM DOMAIN>.com/api/data/v8.1/accounts HTTP/1.1
Content-Type: application/json; charset=utf-8
Accept: application/json
Authorization: Bearer:<TOKEN GOES HERE>
Host: <CRM DOMAIN>.com
Content-Length: 224
{
"name": "Sample Account",
"creditonhold": false,
"address1_latitude": 47.639583,
"description": "This is the description of the sample account",
"revenue": 5000000,
"accountcategorycode": 1
}

Categories

Resources