REST: Not able to add cookie - rest

I am using Apache CXF framework for my REST based service.
In the HTTPServletResponse, I am adding a cookie (using addCookie(Cookie cookie) method) but it is not being added successfully because, whenever I call the same API again, I couldn't see/use the added cookie.
I am using a REST client to call the API and I could see Set-Cookie header in the Respose Headers, but it is not being set.
What would be the problem here?

Well, the cookie is set actually.You will notice that further requests to your api carry the cookie along with them in the "Request Headers". To check the cookie, include the following code snippet in your Service Implementation:
In the implementation class, add the following annotation
#Context
private HttpHeaders headers;
Now, in the method of that class where you want to check the headers, add this code
if(headers.getRequestHeaders() != null) {
for(Entry<String, List<String>> entry : headers.getRequestHeaders().entrySet()) {
System.out.println("entry.getKey() >>>>>>>>>>> "+entry.getKey());
System.out.println("entry.getValue() >>>>>>>>>> "+entry.getValue());
}
}
Here, entry.getKey() will show you the header name and entry.getValue() will be showing a list of string values that this key is holding. If set, your cookie will appear under the header "cookie". I hope that helps.
Thanks.

Related

Trying to figure out why GET method in restful web services called twice

I have a simple restful web services (Jersey framework) that handles a get request. I fired a request from soapUI (v4.6.4) that passes Authorization token in the request header. From the log statement in the service end, I noticed that it was called twice. First time base64 encoded token is captured and its value is printed then it got called again printing null value. I am trying to understand why this is happening. I read a few threads about it in the web but I was not able to find a clear answer for this case.
I wonder if the soapUI fires a request twice somehow...
#Path("/testservice")
public class MyTestService {
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/")
public String test(#Context HttpHeader headers) {
String token = headers.getRequestHeader().getFirst("Authorization");
System.out.println("token: " + token);
return token;
}
...
}

OpenTok Rest Service Invalid JWT Error on Fiddler Request

I'm trying to create OpenTok session by Rest services with JWT object as suggested. I tried to generate session with Fiddler.
Here is my fiddler request (JWT string has been changed with *** partially for security reasons)
POST https: //api.opentok.com/session/create HTTP/1.1
Host: api.opentok.com
X-OPENTOK-AUTH: json_web_token
Accept: application/json
Content-Length: 172
eyJ0eXAiOiJKV1QiL******iOiJIUzI1NiJ9.eyJpc3MiOjQ1NzM******OiJkZW5l******XQiOjE0ODI3OTIzO***SOMESIGNEDKEYHERE***.izvhwYcgwkGCyNjV*****2HRqiyBIYi9M
I got 403 {"code":-1,"message":"Invalid token format"} error probably means my JWT object is not correct. I tried creating it using http://jwt.io (as opentok suggests) and other sites and all seems correct and very similar to the one on tokbox (opentok) site.
I need an explanation to fix it and create a session.
May it be because I am using opentok trial?
JWT creation Parameters
I had the same problem. I resolved the error by setting the correct key-value pairs for the payload part.
Example of my payload is as follows in C#:
var payload = new Dictionary<string, object>()
{
{ "iss", "45728332" },
{ "ist", "project" },
{ "iat", ToUnixTime(issued) },
{ "exp", ToUnixTime(expire) }
};
The value of the "ist" should be set to "project", not the actual name of your project.
Update: Looking at your screenshot, I can say you have not set the secret key (here, it's your ApiKeySecret from TokBox account > project) at the very bottom right.
OK I have found the answer at last,
Your Opentok API Secret key should not be used directly as Sign parameter. In java as shown below, it should be encoded first.
Base64.encodeToString("db4******b51a4032a83*******5d19a*****e01".getBytes(),0)
I haven't tried it on http://jwt.io and fiddler but it seems it will work on it too. Thanks. Full code is below;
payload = Jwts.builder()
.setIssuedAt(currentTime)
.setIssuer("YOUR_OPENTOK_KEY")
.setExpiration(fiveMinutesAdded)
.claim("ist", "project")
.setHeaderParam("typ","JWT")
.signWith(SignatureAlgorithm.HS256, Base64.encodeToString("YOUR_OPENTOK_SECRET".getBytes(),0))
.compact();
return payload;

How do I add a field for a header for an authentication token for Swagger UI?

My team has just started creating RESTful services for data that has previously been handled by a large monolithic legacy application. We want to document the api with Swagger UI and I have set up with one problem.
I need to pass a SAML token as a header parameter, otherwise when we try to click on the "Try it out!" button I get a 401 Authentication error. How do I add a field to the Swagger UI so that someone can put a String for a SAML token to be sent in the request?
This is actually really easy. I saw references to the answer in the documentation but I didn't really understand what it was saying. There is a field at the top next to where your service URL goes and you can use that field to input a string to pass as a header value. That input field has an id of #input_apiKey.
Then in the index.html file you just add a line to the addApiKeyAuthorization() javascript function telling it to take the value of that field and pass it as whatever value you need.
Example:
function addApiKeyAuthorization(){
var key = $('#input_apiKey')[0].value;
if(key && key.trim() != "") {
swaggerUi.api.clientAuthorizations.add("samlToken", new SwaggerClient.ApiKeyAuthorization("samlToken", key, "header"));
swaggerUi.api.clientAuthorizations.add("Content-Type", new SwaggerClient.ApiKeyAuthorization("Content-Type", "application/json", "header"));
swaggerUi.api.clientAuthorizations.add("Accept", new SwaggerClient.ApiKeyAuthorization("Accept", "application/json", "header"));
}
}
$('#input_apiKey').change(addApiKeyAuthorization);
This sets the Content-Type and Accept headers to the same values for every request, and takes the value in that input field at the top of the page in the green header and sets it as my SAML token. So now if I paste in a valid SAML string my request works and I get data back!

Web API calls with RestSharp - prepends application/json to body causing null parameter on action

I have a Web API service that I'm trying to access via the console using RestSharp. My RestSharp code looks like this:
RestClient client = new RestClient(baseUrlString);
RestRequest request = new RestRequest("controllername/actionname");
request.RequestFormat = DataFormat.Json;
ProcessQuestion model = new ProcessQuestion()
{
Id = "123456",
InstanceId = "123",
UniqueId = "bfb16a18-d0d6-46ab-a5b3-2f0ebbfe8626",
PostedAnswer = new Dictionary<string, string>() { { "question_7907_1", "selected" }, { "question_7907_2", "selected" } }
};
request.AddBody(model);
var response = client.Execute(request)
My Web API action takes a model that has the same parameters as the above model. When the call executes, the binding fails and the parameter is null. I suspect this is due to the RestRequest.AddBody method prepending application/json to the body value as shown below:
{application/json={"Id":"123456","InstanceId":"123","UniqueId":"bfb16a18-d0d6-46ab-a5b3-2f0ebbfe8626","PostedAnswer":{"question_7907_1":"selected","question_7907_2":"selected"}}}
If I post using Fiddler the body binds to the model properly. Below is the body value I provided in Fiddler:
{'Id':'123456','InstanceId':'123','Uniqueid':'bfb16a18-d0d6-46ab-a5b3-2f0ebbfe8626','PostedAnswer':{'question_7907_1':'selected','question_7907_2':'selected'}}
Note that the body value in fiddler is the same with the exception of prepending the application/json key.
Also to note: I've tried what seems like everything...I've separated the parameters out in the action, used FromBody and FromUri attributes, tried custom DictionaryModelBinder's, tried custom ValueBinders, tried changing the way I'm using RestSharp (AddParameter with a RequestBody parameter, AddObject, different URL styles, etc.).
Has anyone else encountered this, and if so, did you solve it? I chose Web API for this service with hopes the model binding would work as it does in MVC, but I'm seeing that isn't the case.
Thanks
EDIT (resolved):
RestSharp automatically uses the JsonSerializer for objects passed in the AddBody method. I figured I was missing something simple, and indeed I was... Adding the Method.Post parameter to the RestRequest instantiation solved the problem.
Specify the method when creating the request:
RestRequest request = new RestRequest("controllername/actionname", Method.POST);
Not sure what the default serializer is for body - you can try making it explicit:
request.AddBody(request.JsonSerializer.Serialize(model));
I'm not sure where the 'application/json' is coming from - that's the Content-Type header you should be sending with your request, definitely not part of the body. So do this instead:
request.AddHeader("Content-type", "application/json; charset=utf-8");
If this doesn't help, try making your code as similar to the example on their site as possible. Try removing complexity (even if it means changing the required functionality) - get it to a point when it works and build additional functionality on that.
http://restsharp.org/

Setting Object as cookie in servlet

i am using cookie to avoid rpc call i am using cookie for user authentication for the first time (when he logs in ).For that i am unable to set an User object in the servlet as cookie .because cookie constructer allows on only string as value .
How can i set object as cookie ?
other than cookie is there any way to get the object fron HTTP session without making an RPC call ?
I assume you have some system for translating objects to and from JSONs. So simply translate the object into a JSON string, save it to the cookie, and translate it back into an object when you extract it from the cookie. I recommend the piriti library for handling JSONs (GWT comes with its own JSON handling library built in, but it has some limitations).
if(authenticated){
LoginPojo ch=new LoginPojo();
ch.setImage("image");
ch.setFullName( u.getFirst_name()+" "+u.getLast_name());
ch.setLogin(u.getLogin);
ObjectMapper objectMapper=new ObjectMapper();
String jsonInString = objectMapper.writeValueAsString(ch);
Cookie c=new Cookie("VISITOR",jsonInString);
// c.setSecure(true);
response.addCookie(c);
request.getRequestDispatcher(rootURL).forward(request, response);
}
But somebody says : "The HTTP State Management Mechanism specification (which deals with Cookies) states that you can't have the double quote character in the value of the cookie unless it wraps the entire thing.
Don't (try to) put JSON in cookies."