Create new user on Keycloack 10.0.1 from curl command - java

Currently I try to create a user from curl command via Keycloak's Admin REST API. I can authenticate myself as an admin, I have a good answer, but when I want to create a user then we are getting error like: 548 {"error":"HTTP 401 Unauthorized"}
Here are my curl commands:
#!/bin/bash
echo "* Request for authorization"
RESULT=`curl --data "username=rahul&password=password&grant_type=password& client_id=admin-cli" http://localhost:8080/auth/realms/demo/protocol/openid-connect/token`
echo "\n"
echo "* Recovery of the token"
TOKEN=`echo $RESULT | sed 's/.*access_token":"//g' | sed 's/".*//g'`
echo "\n"
echo "* Display token"
echo $TOKEN
echo "\n"
echo " * user creation\n"
curl -v http://localhost:8080/auth/admin/realms/demo/users -H "Content-Type: application/json" -H "Authorization: bearer $TOKEN" --data '{"firstName":"xyz","lastName":"xyz", "email":"demo2#gmail.com", "enabled":"true"}'
Error logs:
curl -v http://localhost:8080/auth/admin/realms/demo/users -H "Content-Type: application/json" -H "Authorization: bearer $TOKEN" --data '{"firstName":"xyz","lastName":"xyz", "email":"demo2#gmail.com", "enabled":"true"}'
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying ::1:8080...
* Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> POST /auth/admin/realms/demo/users HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.70.0
> Accept: */*
> Content-Type: application/json
> Authorization: bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJuNGhwUUdSeUZDcmhCTzJZbWhwc0FOWG9ZY0Ztak9CMmF3Y0RPdTNNOHhRIn0.eyJleHAiOjE1OTEwMTE0MDEsImlhdCI6MTU5MTAxMTEwMSwianRpIjoiYWMxYTYyZTEtYzUwMi00NzQ0LTgwMDAtMGQ2MWFkMzU2YzIxIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL2RlbW8iLCJzdWIiOiJjYTc0MDk1Ni1jOTQ2LTQ2ZjktODBkZS1jOTFkZDc4MWJjMTIiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhZG1pbi1jbGkiLCJzZXNzaW9uX3N0YXRlIjoiMDdjODFjODQtM2FlOS00NzUyLTkxMzgtMWY4Yzg2Zjg3NWMzIiwiYWNyIjoiMSIsInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwibmFtZSI6IlJhaHVsIEt1bWFyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoicmFodWwiLCJnaXZlbl9uYW1lIjoiUmFodWwiLCJmYW1pbHlfbmFtZSI6Ikt1bWFyIiwiZW1haWwiOiJhYmNAYWJjLmNvbSJ9.BP1krGeTyTVPhKY8zHCmYowNwnGWl-lgMN7XKukUjRgxl6EEJwERwtbiruX0Qv6bZOAx5VMCntcWLPQgCTFzFXJSOnqf_YLKoUEUKrB3Lp8RHgAax0daPFVp2F86cAQ4x_ExADqepcujinvi1qP-wyWidEEVq6_j6aprzLl59y8cN6mWYL2yIZ2Vb6ZnjFHLOsOo-GZBsE1t31nG8rqPscKKhGVj7SLwexnPXCATmqYW1sc6LJgUUh2zcJrI-L8hgfyTyUHrgzi5gB7YE5mRi3M1vyHfmKNSvnca-UXo7O8OHzTzTmrDQcaTrk86xaSCcL4qm-7s9xHLeYGMAqwGEQ
> Content-Length: 81
>
} [81 bytes data]
* upload completely sent off: 81 out of 81 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 401 Unauthorized
< Connection: keep-alive
< X-XSS-Protection: 1; mode=block
< Strict-Transport-Security: max-age=31536000; includeSubDomains
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< 548{"error":"HTTP 401 Unauthorized"}
* Connection #0 to host localhost left intact

"HTTP 401 Unauthorized" as the error message correct implies is that the request is unauthorized. This means that the authentication details in your call are incorrect.
In your request, you send the bearer prefix as "bearer";
Content-Type: application/json
Authorization: bearer <>
Content-Length: 81
Change this to "Bearer <>" and see if it works.
Good day!

Related

Sending templates through Mailgun Java API returns 400 despite following spec

I am trying to use the mailgun Java API for my kotlin project and want to send emails using templates. I believe I have followed the docs but I am getting a 400 Bad Request response.
My kotlin code looks like:
val client = MailgunClient.config("https://api.eu.mailgun.net/", "<raw-api-key>")
.logLevel(Logger.Level.HEADERS)
.createApi<MailgunMessagesApi>(MailgunMessagesApi::class.java)
val message = Message.builder()
.from("Sender name <sender#domain1.com>")
.to("receiver#domain2.com")
.template("template_name")
.subject("Hello")
.mailgunVariables(
mapOf(Pair("param1": "Hello"), Pair("param2": "world"), Pair("param3": "2020-01-01"))
.build()
client.sendMessageFeignResponse(domain, message)
The response logging I get says:
HTTP/1.1 400 Bad Request
access-control-allow-credentials: true
access-control-allow-origin: *
cache-control: no-store
content-length: 78
content-type: application/json;
date: Thu, 22 Dec 2022 00:54:29 GMT
strict-transport-security:
x-xss-protection: 1; mode=block
{}
feign.Response$ByteArrayBody#1744d3cb
I have tried the following and it works in the command line:
curl -s --user 'api:<raw-api-key>' \
https://api.eu.mailgun.net/v3/<user-domain>/messages \
-F from='Sender name <sender#domain1.com>' \
-F to=receiver#domain2.com \
-F template='template_name' \
-F subject='Hello' \
-F t:variables='{"param1": "Hello", "param2": "world", "param3": "2020-01-01"}'

Not able to see the response message using cURL

I am trying to call an API using cURL.
Using the Advanced Rest Client(ARC) when I send a request using this URL:
http://localhost:8080/jcr/root/myfolder/integrationTestNode
I receive this response:
Status:
500: Internal Server Error
Loading time: 37 ms
Date: Thu, 28 Jul 2016 06:20:11 GMT
Content-Type: text/plain
Content-Length: 88
And a message
Failed to delete filejavax.jcr.PathNotFoundException: /root/myfolder/integrationTestNode
Which is exactly what I want.
But when I try the same using cURL in a shell script I am unable to see the message.
Here is the script:
url="http://localhost:8080/jcr/root/myfolder/integrationTestNode"
echo ${url}
curl -u amit:pass --verbose -I -X DELETE \
--url "${url}"
echo " ----------------------------------------------------------------------------"
And here is the response of the script:
http://localhost:8080/jcr/root/myfolder/integrationTestNode
* timeout on name lookup is not supported
* Trying ::1...
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Connected to localhost (::1) port 8080 (#0)
* Server auth using Basic with user 'amit'
> DELETE /jcr/root/myfolder/integrationTestNode HTTP/1.1
> Host: localhost:8080
> Authorization: Basic YW1pdDpwYXNz
> User-Agent: curl/7.49.1
> Accept: */*
>
< HTTP/1.1 500 Internal Server Error
< Date: Thu, 28 Jul 2016 06:25:26 GMT
< Content-Type: text/plain
< Content-Length: 88
<
* Excess found in a non pipelined read: excess = 88 url = /jcr/root/myfolder/int egrationTestNode (zero-length body)
0 88 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0HT TP/1.1 500 Internal Server Error
Date: Thu, 28 Jul 2016 06:25:26 GMT
Content-Type: text/plain
Content-Length: 88
How can I see the response message using cURL ?
I am using javax.ws.rs.core.Response.status().entity("").build() to send the message.

Jersey ExceptionMapper implementations skipped on deploy

In my pet project I have a simple jersey (v 2.13) resource that performs some crud operations, and the input is validated by hibernate-validator (v 5.0.1.Final).
The problem is that while the junit tests works as expected, when I deploy the webapp all the ExceptionMapper implementations are ignored.
Here some details:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public JsonResult<User> addUser(#Valid Userbean user) {
//do stuff...
}
The validation is made by hibernate-validator.
the Userbean is annotate with:
#NotNull
private String password;
I've created an ExceptionMapper implementation:
#Provider
public class ValidationExceptionMapper implements ExceptionMapper<ValidationException> {
#Override
public Response toResponse(ValidationException e) {
return Response.status(422).build();
}
}
Leaving aside that on validation the proper status code should be 400, my problem is that while in my junit-test everything goes fine...
Userbean entity = new Userbean();
entity.setUsername(username);
Response response = target.path("users").request(MediaType.APPLICATION_JSON).post(Entity.json(entity));
int status = response.getStatus();
assertEquals(422 status);
...I cannot reproduce the same behaviour when I run it on tomcat (I've tried tomcat7 / tomcat 8 and also glassfish 4.1)
I always get a 400 status code instead of 422 and ValidationExceptionMapper is being skipped.
$ curl -v -X POST -H "Content-Type: application/json" --data "{\"username\":\"MrFoo\"}" http://localhost:8080/playground-webapp/jaxrs/jersey/users/
* About to connect() to localhost port 8080 (#0)
* Trying ::1... connected
> POST /playground-webapp/jaxrs/jersey/users/ HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: localhost:8080
> Accept: */*
> Content-Type: application/json
> Content-Length: 20
>
* upload completely sent off: 20out of 20 bytes
< HTTP/1.1 400 Bad Request
< Server: Apache-Coyote/1.1
< Content-Type: text/html;charset=utf-8
< Content-Language: en
< Content-Length: 990
< Date: Sun, 28 Dec 2014 15:07:34 GMT
< Connection: close
<
* Closing connection #0
<html><head><title>Apache Tomcat/7.0.52 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 400 - Bad Request</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>Bad Request</u></p><p><b>description</b> <u>The request sent by the client was syntactically incorrect.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.52</h3></body></html>
The same call made on the test server works as expected:
curl -v -X POST -H "Content-Type: application/json" --data "{\"username\":\"MrFoo\"}" http://localhost:8080/users/
* About to connect() to localhost port 8080 (#0)
* Trying ::1... Connessione rifiutata
* Trying 127.0.0.1... connected
> POST /users/ HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: localhost:8080
> Accept: */*
> Content-Type: application/json
> Content-Length: 20
>
* upload completely sent off: 20out of 20 bytes
< HTTP/1.1 422
< Content-Type: application/json
< Date: Sun, 28 Dec 2014 15:05:35 GMT
< Content-Length: 94
<
* Connection #0 to host localhost left intact
the code of the server I use for junit is:
#Before
public void setUpClient() throws Exception {
ResourceConfig rc = new UserResourceConfig();
rc.property("contextConfig", appContext);
server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, rc);
server.start();
....
Thanks in advance for your help.

ATG 11 REST call with parameters

I need to call method using ATG 11 REST API.
public String getString(String str) {
return str;
}
I created actor properties configuration like this:
$class=atg.service.actor.ActorChainService
definitionFile=/path/to/service/accountServiceActor.xml
And that my accountServiceActor.xml:
<?xml version="1.0" encoding="UTF-8"?>
<actor-template default-chain-id="cartService" xsi:noNamespaceSchemaLocation="http://www.atg.com/xsds/actorChain_1.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<actor-chain id="getString" transaction="TX_SUPPORTS">
<component id="getString" name="/path/to/service/AccountService"
method="getString" method-return-var="str">
<input name="str" value="${param.str}" />
<output id="str" name="str" value="${str}" />
</component>
</actor-chain>
</actor-template>
Also I updated AccessControlServlet.properties and ActorChainRestRegistry.properties
So my rest call is here:
curl -L -v -b customer_cookies.txt -X POST -H "Content-Type: application/json" -d '{ "str" : "value" }' http://localhost:7003/path/to/service/AccountServiceActor/getString
And i am getting this error:
* Adding handle: conn: 0x7f8eb9803000
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7f8eb9803000) send_pipe: 1, recv_pipe: 0
* About to connect() to localhost port 7003 (#0)
* Trying ::1...
* Connected to localhost (::1) port 7003 (#0)
> POST /path/to/service/AccountServiceActor/getString HTTP/1.1
> User-Agent: curl/7.30.0
> Host: localhost:7003
> Accept: */*
> Cookie: DYN_USER_CONFIRM=f0f599f9f11aa5571d7055c2b4c7c9d5; DYN_USER_ID=240004; JSESSIONID=6iUR5qvjjBHPhSNq6zMh_B6dn18lwhKFWvPbOZxTekUIhsFPqf3r!-1528908093
> Content-Type: application/json
> Content-Length: 20
>
* upload completely sent off: 20 out of 20 bytes
< HTTP/1.1 500 Internal Server Error
< Connection: close
< Date: Tue, 26 Aug 2014 11:19:21 GMT
< Content-Length: 265
< Content-Type: text/html; charset=UTF-8
< X-ATG-Version: version=QVRHUGxhdGZvcm0vMTEuMA==
* Replaced cookie JSESSIONID="fcMSCqdKrO-PvMyLalmJHSnuHBa0VEBaJscD01nZYZDOXCXs6Q3j!-1528908093" for domain localhost, path /, expire 0
< Set-Cookie: JSESSIONID=fcMSCqdKrO-PvMyLalmJHSnuHBa0VEBaJscD01nZYZDOXCXs6Q3j!-1528908093; path=/; HttpOnly
< X-Powered-By: Servlet/3.0 JSP/2.2
<
CONTAINER:atg.service.actor.ActorException: There was an error while trying to find a method.; SOURCE:java.lang.NoSuchMethodException: path.to.service.impl.AccountService.getString(null)
What i am doing wrong? Help me to make my configuration correct.
<input name="str" class-name="java.lang.String" value="${param.str}" />
Please add class-name attribute in your input parameter:Snippet:
1-Enclose http://localhost:7003/path/to/service/AccountServiceActor/getString in double qoutes,i.e
"http://localhost:7003/path/to/service/AccountServiceActor/getString".
2-Also replace '{ "str" : "value" }' with "{ "str" : "value" }"
Please make sure of the following points :
Actor property file name and Actor xml file name should be the same
i.e. in your case accountServiceActor.xml and AccountServiceActor.properties
Use the URL with /rest/model/ i.e. in your case http://localhost:7003/rest/model/path/to/service/AccountServiceActor/getString
Make sure that in the ActorChainRestRegistry.propeties the URL is correctly registered i.e. in your case registeredUrls+=/path/to/service/accountServiceActor/getString
Make sure that the method getString() exist in the component /path/to/service/AccountService :)

cURL JSON + Cookies + Header Params + Jersey

I'm trying to send a request, I do the following in curl:
curl -v --header "location: 60.004:8.456" --cookie "sessionToken=~session" -i -X PUT -H 'Content-Type: application/json' -d '{"data":"{"FCT":"Welcome", "Uni":"Welcome to DI"}"}' localhost:8080/tester/apps/e39/data
and for some reason it matches the class but no this method:
#PUT
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response createDocumentRoot(JSONObject inputJsonObj,
#Context UriInfo ui, #Context HttpHeaders hh) {
}
Edit:
The class is defined with #Path("{appId}/data")
The problem isn't the paths, as I've debugged it and seen it identifies the class right, it just throws the bad request after going inside the class without entering any method.
Here is the curl verbose:
* About to connect() to localhost port 8080 (#0)
* Trying 127.0.0.1... connected
> PUT /tester/apps/e39/data HTTP/1.1
> User-Agent: curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: localhost:8080
> Accept: */*
> Cookie: sessionToken=~session
> location: 60.004:8.456
> Content-Type: application/json
> Content-Length: 60
>
* upload completely sent off: 60out of 60 bytes
< HTTP/1.1 400 Bad Request
HTTP/1.1 400 Bad Request
< Server: Apache-Coyote/1.1
Server: Apache-Coyote/1.1
< Content-Type: text/html;charset=utf-8
Content-Type: text/html;charset=utf-8
< Content-Length: 990
Content-Length: 990
< Date: Tue, 02 Jul 2013 21:46:56 GMT
Date: Tue, 02 Jul 2013 21:46:56 GMT
< Connection: close
Connection: close
The problem was in the json syntax that was incorrect, I had
'{"data":"{"FCT":"Welcome", "Uni":"Welcome to DI"}"}'
after changing to this, it worked fine:
'{"data":
{"FCT":"Welcome",
"Uni":"Welcome to DI"}}'
I used a JSON online parser to check the json syntax, here is the link incase someone needs it:
http://json.parser.online.fr/

Categories

Resources