Unable to create a session via CouchBase sync gateway admin REST API - couchbase

I am working on implementing custom authentication using cookie Auth. So, I was playing around the sync gateway REST API to create user and session. I could successfully create the user but unable to create session via /_session API.
Following are the steps I followed.
1. Create user
POST /cookbook/_user/ HTTP/1.1
Host: localhost:4985
Content-Type: application/json
{
"name": "chef123",
"password": "1234"
}
2. Get Users
GET /cookbook/_user/ HTTP/1.1
Host: localhost:4985
Content-Type: application/json
Respone :["chef123"]
3. Create Session
POST /cookbook/_session HTTP/1.1
Host: localhost:59840
Content-Type: application/json
{
"name": "chef123",
"ttl": 1800
}
Expected:
{
"cookie_name": "SyncGatewaySession",
"expires": "2014-11-07T16:42:11.675519255-08:00",
"session_id": "c2425fa7d734bc8c3f6c507854166bef56a5fbc6"
}
Instead received:
{"authentication_handlers":["default","cookie"],"ok":true,"userCtx":{"channels":{},"name":null}}
Can Anyone please explain why is the API giving the following response.
{"authentication_handlers":["default","cookie"],"ok":true,"userCtx":{"channels":{},"name":null}}

authentication_handlers is the method you used to create the session (it could be the built-in facebook or persona login features as well). userCtx has useful information on the data access for this user like:
channels: The channels the user was given access to via the Sync Function
admin_channels: The channels the user was given access to in the config file
roles: The roles of this user
See the session docs for details: http://developer.couchbase.com/documentation/mobile/1.2/develop/references/sync-gateway/admin-rest-api/session-admin/get-db-session-sessionid/index.html
To set up authentication with Sync Gateway you can check those blogs:
Adding user Sign Up to your Android app with Node.js and Couchbase Mobile
Adding Google Sign-In with Node.js to a Couchbase Mobile application

As mentioned in the comments by krishnan, the solution to this problem is removing the trailing slash from the URI. I had the same issue.
So, instead of: POST /cookbook/_session/
Use: POST /cookbook/_session

Related

Can't create composite roles in Keycloak using Admin REST Api

I'm attempting to manage roles and composites programmatically in my Keycloak 6.0.1 system using the Admin REST API. According to the documentation, this is what I want to be using:
https://www.keycloak.org/docs-api/6.0/rest-api/index.html#_roles_resource
Right off the bat, my base URL for Keycloak's API seems to be:
https://example.com/auth/admin
instead of /auth, as the docs seem to suggest. If I use the base URL specified in the docs I get a 404. I discovered this alternate URL structure by inspecting what the Kubernetes admin page was doing when I manage the installation through my browser.
In any case, I am now successfully creating roles using the POST /{realm}/clients/{id}/roles endpoint. Problems begin when I try to add a composite using POST /{realm}/clients/{id}/roles/{role-name}/composites with a POST like this:
/auth/admin/realms/REDACTED/clients/546052d9-6ba1-483e-93a5-a5fda51505b8/roles/%5ECouponAttemptsLog%25Unowned%25Write/composites
authorization: Bearer REDACTED
Content-Type: application/json
Accept: */*
Content-Length: 217
User-Agent: node-fetch/1.0 (+https://github.com/bitinn/node-fetch)
Accept-Encoding: gzip,deflate
Connection: close
Host: REDACTED
{"roles":[{"name":"^CouponAttemptsLog/id%Unowned%Write"},{"name":"^CouponAttemptsLog/code%Unowned%Write"},{"name":"^CouponAttemptsLog/eventId%Unowned%Write"},{"name":"^CouponAttemptsLog/attemptedDate%Unowned%Write"}]}
The error message logged by Keycloak is:
14:18:02,617 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (default task-4884) Uncaught server error: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
...and Keycloak returns a 500 response with no text.
As far as I can tell, this matches the expected request shape specified in the Keycloak 6 API documentation, and I'm at a loss for what could be causing this deserialization failure. Just for yuks, I tried sending in a naked JSON array as the body, with no improvement.
What am I doing wrong? I understand that the error from Keycloak means it's trying to convert something to an ArrayList which can't be, but I'm at a loss to figure out what and why.
It wants an array of role objects. Try this:
[
{
"name": "^CouponAttemptsLog/id%Unowned%Write"
},
{
"name": "^CouponAttemptsLog/code%Unowned%Write"
},
{
"name": "^CouponAttemptsLog/eventId%Unowned%Write"
},
{
"name": "^CouponAttemptsLog/attemptedDate%Unowned%Write"
}
]
Glancing at the code, I think you'll need to include a role id in addition the name...even if the doc says all fields within RoleRepresentation are optional.
I don't know if you solved your problem but in my case I need to use both id and name while assigning roles to composite role. And yes "partial" roles need to be created before assignment to composite role.
[
{
"id": UUID of created role
"name": "^CouponAttemptsLog/id%Unowned%Write"
}
]
Flow in my looks like this:
In a loop create partial role(s) - Keycloak api return location of new role in headers so you need to call GET to obtain role's json
Push {"id": UUID} to array - or even better {"id": UUID, "name": name } or whole role's representation (to call composites id is enough but in case of service roles you need both
Create composite role
Call composites endpoint

REST API Posting two request simultaneously with different properties fails with 403 status code due to CSRF check

I'm sending two post requests using the REST API: http://localhost:8111/app/rest/buildQueue but my second request fails with
403 Forbidden: Responding with 403 status code due to failed CSRF check: no "Origin" header is present and no authentication provided with the request, consider adding "Origin: http://localhost:8111" header.
I'm wondering why is this happening since if I run the build in the UI and change the params ex. build1 has %version=2% and build2 has %version=3% it will run parallel with each other running on different available agents.
Here's my json request:
REST API endpoint: http://localhost:8111/app/rest/buildQueue
JSON body:
{
"branchName": "master",
"buildType": {
"id": "DockerBuild",
"projectId": "Test"
},
"properties": {
"property": [
{
"name": "DOCKER_IMAGE_NAME",
"value": "test-3"
},
{
"name": "SNAPSHOT_DEPENDENCY_VERSION",
"value": "0.6"
}
]
}
}
Am I missing a parameter to be able to run builds in parallel with each other?
When you face problems regarding CSRF protection in TeamCity (for example, you get the "Responding with 403 status code due to failed CSRF check" response from the server), you can follow these steps:
If you use a reverse proxy, make sure you correctly configure Host/Origin headers, as described above. In the meantime, you may want to add the public URL of your server to CORS-enabled origins.
You can temporary disable CSRF protection at all by setting the teamcity.csrf.origin.check.enabled=logOnly internal property.
Information about failed CSRF attempts are logged into TeamCity/logs/teamcity-auth.log files. For more detailed diagnostics of the requests, enable debug-auth logging preset.
Try pass in the request header -H 'Origin: http://localhost:8111'
Maybe this can be useful for someone, I got the same error with a single POST using Postman:
403 Forbidden: Responding with 403 status code due to failed CSRF check: no "Origin" header is present and no authentication provided with the request, consider adding "Origin: http://teamcity:20011" header.
So I followed the recommendation of the error message, and in Header I added "Origin" with the value "http://teamcity:20011" and that fixed the issue. BTW, in Authorization I selected "Bearer Token" and I pasted the token generated previously through TeamCity. This is the call:
http://teamcity:20011/app/rest/buildQueue
I was just testing how to trigger a build using the API and it worked successfully. Now the following step is to implement this call using JavaScript.
Request a CSRF header with the appropriate request:
https://teamcity/authenticationTest.html?csrf
and set it in the "X-TC-CSRF-TOKEN" header of your POST request
If you specify an Access Token to the request header like Authorization: Bearer ..., you don't need to specify a CSRF token, and what you should actually check is if you're not sending Cookies.
This is from the developer in JetBrains:
If you're using a token-based authentication, there should be no need to provide CSRF token header and obtain it with authenticationTest.html call.
In this scenario, it is expected that there are no session Cookies in the HTTP request (otherwise, TeamCity will try to find a token).
I.e. basically, you should be able to do the HTTP call in no-session way by providing the Authorization: Bearer {{token}} header only.
https://youtrack.jetbrains.com/issue/TW-69566/Flaky-builds-with-CSRF-Header-X-TC-CSRF-Token-does-not-match-CSRF-session-value#focus=Comments-27-4644138.0-0
Well, the error and the documentation don't seem to explain this, though...

yii2 send API request command

Need to execute the following API call:
GET /v1/users HTTP/1.1
Host: https://api.someserver.com
Authorization: Bearer MyT0KenGoesH3r3
so far for Yii2 there is lots of documentation about creating your own API, but not how to send a query. Do I need an extension to do this, or am I looking at something like https://github.com/guzzle/guzzle?
There is a HTTP Client Extension for Yii 2. Take a look at https://github.com/yiisoft/yii2-httpclient

FIWARE-Lab KeyRock Access Token Request error

I'm testing the Authorization Code Grant protocol on the instance of KeyRock GE at FIWARE-Lab using DHC web client.
So far I have succeeded on implementing the Authorization Request, and I obtain the code to be used on the Access Token Request. The URL for the Authorization Request is the following (although not executed on DHC, but on a regular browser so I can introduce my user and password):
https://account.lab.fiware.org/oauth2/authorize/?response_type=code&client_id=2122&redirect_uri=http%3A%2F%2Flocalhost%2FCallback
I have checked that the client_id and the redirect_uri are both correct against the values related with my application at my account at FIWARE-Lab.
Executing the following request (can't post images, so I'll describe)
POST
https:// account.lab.fiware.org/oauth2/token?grant_type=authorization_code&code=<code>&redirect_uri=http%3A%2F%2Flocalhost%2FCallback -- <code> is the code obtained on the Auth. Request
Authorization: Basic <XXXX> --- <XXXX> is the result of base64(client_id+":"+client_secret)
Content-Type: application/x-www-form-urlencoded
...I get the following error message:
{
"error":{
"message": "create_access_token() takes exactly 3 arguments (2 given)",
"code": 400,
"title": "Bad Request"
}
}
I've checked the authorization is correct (Basic using the OAuth credentials from my application), and I'm using the same redirect_uri used at the previous Authorization Request, and the code obtained from it.
¿What is wrong?
P.S.: If I remove any or all of the query parameters, I still get the same error
Don't pass the parameters in the url. Instead, add them to request's body as query string:
POST /oauth2/token HTTP/1.1
Host: account.lab.fiware.org
Content-Type: application/x-www-form-urlencoded
Authorization: Basic <XXXX> --- <XXXX>
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=1234&redirect_uri=http%3A%2F%2Flocalhost%3A9000%2Fcodecallback.html
I suggest to follow the steps in the presentation:
Adding Identity Management and Access Control to your Application
It gives you details about what are the different requests that you have to follow and also what are the expected response of them.

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