IPPException when querying Visma Net Account table - json

When I make a request using Postman to query the Visma Net API /account endpoint, I get a HTTP 400 Bad Request error:
{
"ExceptionType": "IPPException",
"ExceptionMessage": "",
"ExceptionFaultCode": "12002",
"ExceptionMessageID": "12002_12002_some-guid",
"ExceptionDetails": ""
}
The request I send is to:
https://integration.visma.net/API/controller/api/v1/account?active=true
I put the received Bearer token from the OAuth authentication step in the Authorization header.

A 12002 code is returned by Visma.net for at least the following cases:
The company ID is not set (in Swagger site: enter the ID in top right corner, retrieve list of companies available to you using Context in list).
The user is not authenticated on the company ID provided in the HTTP header.
To use swagger: https://integration.visma.net/API-index/.
The ipp-company-id in the top right corner of the visma.net API swagger site can also manually be handled.
Besides the Authorization header, you set two headers:
ipp-company-id: the company id
ipp-application-type: always "Visma.net Financials"
Best is to enter into a partner agreement with Visma. They have a lot of additional information and training videos. Note that implicit grant is not supported, only code grant flow, so there are some security risks involved when running on untrusted devices. Best is to acquire a client ID per untrusted environment or use visma.net APIs only from your own trusted environment.

Related

Is using authentication as context RESTful?

I am wondering if implicitly using the currently authenticated user as context for API interactions is RESTful or not. For example, assuming all my API calls are authenticated using standard HTTP security:
Should a query to retrieve a list of orders for the user be explicit?
NO: http://example.com/orders
YES: http://example.com/orders?userid=1234
When placing a POST to create a new order, should the JSON contain the user?
NO: { orderref: 'EXAM/1', items: { ... } }
YES: { userid: 1234, orderref: 'EXAM/1', items: { ... } }
Either way I'll be securing so that the API will only allow actions for the current user, but should I make the API caller state the userid for each action?
I would say you should only pass the user ID as a query if you have access to many user's orders and need to filter them by user.
If a user has access to only their own orders they should not have to pass a user ID - the base queryset should limit it based on their own authentication details. Arguably that may not be RESTful, but don't worry about that - most API's may not be 100% RESTful and you should do what makes sense for your application rather than worrying about whether it's RESTful - it's a guide, not a cast-iron requirement.
In any case depending on what type of authentication you use (BASIC or TOKEN), you have to send the user info in your API call (Headers) which makes the request to the API.
So when you say if it is valid to use the authenticated user from the Context, of course it is
sample code here
The api call
headers.Authorization = 'Bearer ' + localStorage.getItem("tokenkey");
Obtain user from the request
RequestContext.Principal.Identity.Name
Is it RESTful? I would argue that: yes it is. There is no REST spec, so there's nothing really that says that it isn't. HTTP does allow this, and HTTP Caches should actually by default consider responses to GET requests with an Authorization header as private.
Should you use this design? I don't know! I think there's benefits to having per-user endpoints, because in the future it might allow User A to inspect the orders of User B.
In our API we actually have an example of an API similar to yours, but we do both.
We have a /users/1234 endpoint.
We also have a /current-user endpoint.
Initially the /current-user endpoint just redirected to the uri of the actual current user, but eventually we decided we're actually just going to return the full object without redirecting (due to browsers not behaving nicely with redirects).
The current-user endpoint does have a self link still that points to the real user resource.
So to sum it up. I think you are in the clear here, but I argue that there are strong design benefits to creating resources that have a consistent representation regardless of who's looking at it. It makes things a bit simpler and nicer.
And also don't forget that there's no reason why you can't, if you are actually following REST. All a client should care about is that there's a link somewhere to a list of orders and it shouldn't care what it's url is.
+1 for Matthew Daly's answer. Especially when the authenticated user has only access to his own orders (I assume that).
In case that your authenticated user can access more order lists than only his own, I would go like that:
/orders: the authenticated user's orders.
/orders/123: the specific user's orders.
If 123 equals the authenticated user's id - so what? It would be most likely no problem case for your client.
By designing a REST service you think of the comfort that the developers could have, when they use your API. I would say, this one is a comfortable solution.
Should a query to retrieve a list of orders for the user be explicit?
NO: http://example.com/orders
YES: http://example.com/orders?userid=1234
When placing a POST to create a new order, should the JSON contain the
user?
NO: { orderref: 'EXAM/1', items: { ... } }
YES: { userid: 1234, orderref: 'EXAM/1', items: { ... } }
If user queries only its own orders, user id shouldn't be passed explicitly in the query - you should pass user token in HTTP header and your code should extract user id by provided token and determine whether authorized user has rights to see or modify particular data.
In case you want to let one user get or modify another user data then you would make additional endpoint - something like users/{userId}/orders or users/{userId}/orders/{orderId}. You would still pass user token via HTTP header and your implementation should check if user has admin rights for this action.

Keycloak: Validate access token and get keycloak ID

I need to be able to do the following (with plain cURL & JSON server-side- no frameworks or Java):
Use a string representation of a Keycloak access token I have been given by a 3rd party to verify that the token is valid.
If the token is valid, get the Keycloak ID for that user.
How do I do this using plain old HTTP posts? I've found lots of Java examples but I need to know the raw HTTP POSTs and responses underneath.
Is it something like this to validate the token?
/auth/realms/<realm>/protocols/openid-connect/validate?access_token=accesstokenhere
What does this return in terms of data (sorry I currently have no test server to interrogate)?
Thanks.
The validate endpoint does not seem to work now. It used to return access token. I am using the keycloak 2.5.1 now. As mentioned in post by Matyas (and in the post referenced by him), had to use introspect token endpoint.
In my testing Bearer authentication did not work. Had to use Basic authentication header along with base64 encoded client credentials.
base64.encode("<client_id:client_secret>".getBytes("utf-8"))
The response from introspect endpoint is in JSON format as shared in post referenced by Maytas, has many fields based on type of token being introspected. In my case token_type_hint was set as access_token.
requestParams = "token_type_hint=access_token&token=" + accessToken
The response included required user details like username, roles and resource access. Also included OAuth mandated attributes like active, exp, iss etc. See rfc7662#page-6 for details.
Maybe you need this:
http://lists.jboss.org/pipermail/keycloak-user/2016-April/005869.html
The only one problem is that, introspect is not working with public clients.
The key url is:
"http://$KC_SERVER/$KC_CONTEXT/realms/$REALM/protocol/openid-connect/token/introspect"
You need to authorize your client e.g. with basic auth, and need to give the requester token to introspect:
curl -u "client_id:client_secret" -d "token=access_token_to_introspect" "http://$KC_SERVER/$KC_CONTEXT/realms/$REALM/protocol/openid-connect/token/introspect"

What's wrong with this authorization exchange?

I've set up a MediaWiki server on an Azure website with the PluggableAuth and OpenID Connect extensions. The latter uses the PHP OpenID Connect Basic Client library. I am an administrator in the Azure AD domain example.com, wherein I've created an application with App ID URI, sign-on URL and reply URL all set to https://wiki.azurewebsites.net/. When I navigate to the wiki, I observe the following behavior (cookie values omitted for now):
Client Request
GET https://wiki.azurewebsites.net/ HTTP/1.1
RP Request
GET https://login.windows.net/example.com/.well-known/openid-configuration
IP Response
(some response)
RP Response
HTTP/1.1 302 Moved Temporarily
Location: https://login.windows.net/{tenant_id}/oauth2/authorize?response_type=code&redirect_uri=https%3A%2F%2Fwiki.azurewebsites.net%2F&client_id={client_id}&nonce={nonce}&state={state}
Client Request
(follows redirect)
IP Response
HTTP/1.1 302 Found
Location: https://wiki.azurewebsites.net/?code={code}&state={state}&session_state={session_state}
Client Request
(follows redirect)
RP Request (also repeats #2 & #3)
POST https://login.windows.net/{tenant_id}/oauth2/token
grant_type=authorization_code&code={code}&redirect_uri=https%3A%2F%2Fwiki.azurewebsites.net%2F&client_id={client_id}&client_secret={client_secret}
IP Response
(As interpreted by MediaWiki; I don't have the full response logged at this time)
AADSTS50001: Resource identifier is not provided.
Note that if I change the OpenID PHP client to provide the 'resource' parameter in step 8, I get the following error response from AAD instead:
RP Request
POST https://login.windows.net/{tenant_id}/oauth2/token
grant_type=authorization_code&code={code}&redirect_uri=https%3A%2F%2Fwiki.azurewebsites.net%2F&resource=https%3A%2F%2Fwiki.azurewebsites.net%2F&client_id={client_id}&client_secret={client_secret}
IP Response
AADSTS90027: The client '{client_id}' and resource 'https://wiki.azurewebsites.net/' identify the same application.
(This has come up before.)
Update
I've made some progress based on #jricher's suggestions, but after working through several more errors I've hit one that I can't figure out. Once this is all done I'll submit pull requests to the affected libraries.
Here's what I've done:
I've added a second application to the example.com Azure AD domain, with the App ID URI set to mediawiki://wiki.azurewebsites.net/, as a dummy "resource". I also granted the https://wiki.azurewebsites.net/ application delegated access to this new application.
Passing in the dummy application's URI as the resource parameter in step #8, I'm now getting back the access, refresh, and ID tokens in #9!
The OpenID Connect library requires that the ID token be signed, but while Azure AD signs the access token it doesn't sign the ID token. It comes with the following properties: {"typ":"JWT","alg":"none"}. So I had to modify the library to allow the caller to specify that unsigned ID tokens are considered "verified". Grrr.
Okay, next it turns out that the claims can't be verified because the OpenID Provider URL I specified and the issuer URL returned in the token are different. (Seriously?!) So, the provider has to be specified as https://sts.windows.net/{tenant_id}/, and then that works.
Next, I found that I hadn't run the MediaWiki DB upgrade script for the OpenID Connect extension yet. Thankfully that was a quick fix.
After that, I am now left with (what I hope is) the final problem of trying to get the user info from AAD's OpenID Connect UserInfo endpoint. I'll give that its own section.
Can't get the user info [Updated]
This is where I am stuck now. After step #9, following one or two intermediate requests to get metadata and keys for verifying the token, the following occurs:
RP Request:
(Updated to use GET with Authorization: Bearer header, per MSDN and the spec.)
GET https://login.windows.net/{tenant_id}/openid/userinfo
Authorization: Bearer {access_token}
IP Response:
400 Bad Request
AADSTS50063: Credential parsing failed. AADSTS90010: JWT tokens cannot be used with the UserInfo endpoint.
(If I change #10 to be either a POST request, with access_token in the body, or a GET request with access_token in the query string, AAD returns the error: AADSTS70000: Authentication failed. UserInfo token is not valid. The same occurs if I use the value of the id_token in place of the access_token value that I received.)
Help?
Update
I'm still hoping someone can shed light on the final issue (the UserInfo endpoint not accepting the bearer token), but I may split that out into a separate question. In the meantime, I'm adding some workarounds to the libraries (PRs coming soon) so that the claims which are already being returned in the bearer token can be used instead of making the call to the UserInfo endpoint. Many thanks to everyone who's helped out with this.
There's also a nagging part of me that wonders if the whole thing would not have been simpler with the OpenID Connect Basic Profile. I assume there's a reason why that was not implemented by the MediaWiki extension.
Update 2
I just came across a new post from Vittorio Bertocci that includes this helpful hint:
...in this request the application is asking for a token for itself! In Azure AD this is possible only if the requested token is an id_token...
This suggests that just changing the token request type in step 8 from authorization_code to id_token could remove the need for the non-standard resource parameter and also make the ugly second AAD application unnecessary. Still a hack, but it feels like much less of one.
Justin is right. For authorization code grant flow, your must specify the resource parameter in either the authorization request or the token request.
Use &resource=https%3A%2F%2Fgraph.windows.net%2F to get an access token for the Azure AD Graph API.
Use &resource=https%3A%2F%2Fmanagement.core.windows.net%2F to get a token for the Azure Service Management APIs.
...
Hope this helps
Microsoft's implementation of OpenID Connect (and OAuth2) has a known bug where it requires the resource parameter to be sent by the client. This is an MS-specific parameter and requiring it unfortunately breaks compatibility with pretty much every major OAuth2 and OpenID Connect library out there. I know that MS is aware of the issue (I've been attempting to do interoperability testing with their team for quite a while now), but I don't know of any plans to fix the problem.
So in the mean time, your only real path is to hack your client software so that it sends a resource parameter that the AS will accept. It looks like you managed to make it send the parameter, but didn't send a value that it liked.
I had issues getting this running on Azure, even though I got something working locally. Since I was trying to setup a private wiki anyway, I ended up enabling Azure AD protection for the whole site by turning on:
All Settings -> Features -> Authentication / Authorization
From within the website in https://portal.azure.com
This made it so you had to authenticate to Azure-AD before you saw any page of the site. Once you were authenticated a bunch of HTTP Headers are set for the application with your username, including REMOTE_USER. As a result I used the following plugin to automatically log the already authenticated user into Azure:
https://www.mediawiki.org/wiki/Extension:Auth_remoteuser

Role-based access control with REST (HTTP)?

I'm creating a system with a JavaScript client that will communicate with the server over REST (HTTP)[JSON].
I am using role-based access control to manage the calls.
Example: [explicit URL will stay the same]
Anonymous -> request \
Server -> route to login form: \login\
User (now with cookie!) -> request \
if (user->role == "manager") return "\manager-homepage\";
else return "\homepage\";
Since REST is stateless how would I go about managing this use-case?
Do I send the cookie with each request, and the returned HTTP status codes will tell the JS where to route?
[Which would be rather inefficient + open to MITM attacks]
Can you not use a standard authentication scheme, such as http digest?
Example: [from Wikipedia page]
The client asks for a page that requires authentication but does not provide a username and password. Typically this is because the user simply entered the address or followed a link to the page.
The server responds with the 401 "client-error" response code, providing the authentication realm and a randomly-generated, single-use value called a nonce.
At this point, the browser will present the authentication realm (typically a description of the computer or system being accessed) to the user and prompt for a username and password. The user may decide to cancel at this point.
Once a username and password have been supplied, the client re-sends the same request but adds an authentication header that includes the response code.
In this example, the server accepts the authentication and the page is returned. If the username is invalid and/or the password is incorrect, the server might return the "401" response code and the client would prompt the user again.
Note: A client may already have the required username and password without needing to prompt the user, e.g. if they have previously been stored by a web browser.
See also this answer to a very similar question: REST and authentication variants
Depending on your desired security level, you could serve the whole thing over ssl. That will prevent mitm attacks.

How can I access auth-only Twitter API methods from a web application

I have a web application for iPhone, which will ultimately run within a PhoneGap application - but for now I'm running it in Safari.
The application needs to access tweets from Twitter friends, including private tweets. So I've implemented OAuth using the Scribe library. I successfully bounce users to Twitter, have them authenticate, then bounce back.
At this point the web app has oAuth credentials (key and token) which it persists locally. From here on I'd like it to user the Twitter statuses/user_timeline.json method to grab tweets for a particular user. I have the application using JSONP requests to do this with unprotected tweets successfully; when it accesses the timeline of a private Twitter feed, an HTTP basic authentication dialog appears in the app.
I believe that I need to provide the OAuth credentials to Twitter, so that my web application can identify and authenticate itself. Twitter recommends doing so through the addition of an HTTP Authorization header, but as I'm using JSONP for the request I don't think this is an option for me. Am I right in assuming this?
My options therefore appear to either be putting the oAuth credentials as query-string parameters (which Twitter recommends against, but documentation suggests still supports); or proxying all the Tweets through an intermediate server. I'd rather avoid the latter.
I access the Twitter API using URLs of the form
http://api.twitter.com/1/statuses/user_timeline.json?user_id=29191439&oauth_nonce=XXXXXXXXXXX&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1272323042&oauth_consumer_key=XXXXXXXXXX&oauth_signature=XXXXXXXXXX&oauth_version=1.0
When user_id is a public user, this works fine. When user_id is a private user, I get that HTTP Basic Auth dialog. Any idea what I'm doing wrong? I'm hoping it's something embarrassingly simple like "forgetting an important parameter"...
The oAuth stanza needs to be exact, as per http://dev.twitter.com/pages/auth#auth-request - I ended up building an Authorization: header that I could first check with curl.
I built it using the really helpful interactive request checker at http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iv-signing-requests/
Here's a friends API request for a protected user:
curl -v -H 'Authorization: OAuth realm="https://api.twitter.com/1/friends/ids.json", oauth_consumer_key="XXXXXXXXXXXXXXXX", oauth_token="XXXXXXXXXXXXXXXX", oauth_nonce="XXXXXXXXXXXXXXXX", oauth_timestamp="1300728665", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_signature="XXXXXXXXXXXXXXXX%3D"' https://api.twitter.com/1/friends/ids.json?user_id=254723679
It's worth re-iterating that as you've tried to do, instead of setting the Authorization header via e.g. jquery's beforeSend function, that for cross-domain JSONP requests (which can't add HTTP headers) you can make oAuth requests by putting all the relevant key/value pairs in the GET request. This should hopefully help out various other questioners, e.g
Set Headers with jQuery.ajax and JSONP?
Modify HTTP Headers for a JSONP request
Using only JQuery to update Twitter (OAuth)
Your request looks like it has a couple of problems; it's missing the user's oauth_token plus the oauth_signature doesn't look like it has been base64 encoded (because it's missing a hex encoded = or ==, %3 or %3D%3D respectively).
Here's my GET equivalent using oAuth encoded querystring params, which you can use in a cross-domain JSONP call:
https://api.twitter.com/1/friends/ids.json?user_id=254723679&realm=https://api.twitter.com/1/friends/ids.json&oauth_consumer_key=XXXXXXXXXXXXXXXX&oauth_token=XXXXXXXXXXXXXXXX&oauth_nonce=XXXXXXXXXXXXXXXX&oauth_timestamp=1300728665&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_signature=XXXXXXXXXXXXXXXX%3D
I was struggling with similar problem of making JSONP requests from Jquery, the above answer helped just to add what I did to achieve my solution.
I am doing server to server oauth and then I send oauth token, secret, consumer key and secret (this is temporary solution by the time we put a proxy to protect consumer secret). You can replace this to token acquiring code at client.
Oauth.js and Sha1.js download link!
Once signature is generated.
Now there are 2 problems:
JSONP header cannot be edited
Signed arguments which needs to be sent as part of oauth have problem with callback=? (a regular way of using JSONP).
As above answer says 1 cannot be done.
Also, callback=? won't work as the parameter list has to be signed and while sending the request to remote server Jquery replace callback=? to some name like callback=Jquery1232453234. So a named handler has to be used.
function my_twitter_resp_handler(data){
console.log(JSON.stringify(data));
}
and getJSON did not work with named function handler, so I used
var accessor = {
consumerSecret: XXXXXXXXXXXXXXXXXXXXXX,
tokenSecret : XXXXXXXXXXXXXXXXXXXXXX
};
var message = { action: "https://api.twitter.com/1/statuses/home_timeline.json",
method: "GET",
parameters: []
};
message.parameters.push(['realm', "https://api.twitter.com/1/statuses/home_timeline.json"]);
message.parameters.push(['oauth_version', '1.0']);
message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
message.parameters.push(['oauth_consumer_key', XXXXXXXXXXXXXXXX]);
message.parameters.push(['oauth_token', XXXXXXXXXXXXXXX]);
message.parameters.push(['callback', 'my_twitter_resp_handler']);
OAuth.completeRequest(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
Create url with base url and key value pairs from parameterMap
jQuery.ajax({
url: url,
dataType: "jsonp",
type: "GET",
});