jose4j JWT's claims set's attribute type other than string object - jwt

I have been using jose4j version 0.6.0 for Json Web Token(JWT) generation. All is good up-till token generation, token verification . JWT's claims payload can have number of elements like version, tokenId, issuer,permissions etc. I'm passing TokenPermissions object which is standard object in oneM2M release 2 specification i.e.
JwtClaims claims = new JwtClaims();
claims.setIssuer("DAS#ServiceProvider");
claims.setAudience("CSE001"); //
.....
.........
TokenPermissions tokenPerms = new TokenPermissions();
TokenPermission tokenPerm = new TokenPermission();
tokenPerm.getResourceIDs().add("RXYZ");
tokenPerm.setPrivileges(setOfAcr);// setOfACr is another object on oneM2M
tokenPerms.getPermission().add(tokenPerm);
claims.setClaim("permissions",tokenPerms);
Above snippet of code generates following JWT Claim Set
{iss=DAS#ServiceProvider, aud=CSE001, exp=1508999613, jti=H1wm_yaOe61Co-wND7wBAw#DAS#CDOT-SP, iat=1508996013, nbf=1508995953, sub=subject, email=mail#example.com, groups=[group-one, other-group, group-three], version=1.0.0, permissions=cdot.onem2m.resource.xsd.TokenPermissions#7f3b97fd}
Whole to the token passes the signature and claims validation but when is I try of typecast permission attribute to TokenPermissions it through error.
tokenPermsObject = jwtClaims.getClaimValue("permissions",TokenPermissions.class);
It through below error :
org.jose4j.jwt.MalformedClaimException: The value of the 'permissions' claim is not the expected type (xyz.xsd.TokenPermissions#7f3b97fd - Cannot cast java.lang.String to xyz.xsd.TokenPermissions.TokenPermissions)
What type of claims object could be passed in jose4j JWT, does I have to mandatorily pass text in claims set. Any help would be highly appreciated.

jose4j's JSON processing was derived from the JSON.simple toolkit and is fairly basic in how it converts between JSON and Java objects. It will do strings, numbers, booleans, maps and lists.
If you want/need to use a more sophisticated JSON library you can use setPayload(...) on JsonWebSignature when creating the JWT and give it the the JSON string you've produced elsewhere. And when consuming a JWT, String getRawJson() on JwtClaims will give you the JSON string payload that you can hand off to some other lib.

Related

Extract response output from one api and needs to be passed in the 2nd

This is my response:
{"token":"eyJ0eXAiOiJKV1QiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIjoiUlNBMV81In0.ezPR0PlML3xO08dEYnJO2QfW8wLc9Hbju1wSqBGM0MEC_YUmsOzQH9X_KvVAH0si7xUVrH74IcLcOlkqGBB5x1ZWQHzh_Zn3ej1JS_n55iXqK1bcOn2dGYjr-yTbIRzxAtUYy8FoV3aEPHwGHh6Ehc3AgOgSSq69ep4CcAUZ38Ga65cd-Aei7dfXMMqtYpHksj6K2TJ3EpFPqqZTfwmLnSomQiWNBC5u6Adkjra5zcQWNRsE2ghcaNQGtMURwjZzeNo4wMWewt1K7CobzS9JPNscK_taOIIhV3vljAf_mRkU7imujdXhchErXoTLD6-cq15txh7xJeo9o1cIm2RDLQ.UCfbgjMC5WsOf_kJsPnQOg.tfvajQljduDdtzwaWaKVxEjr4iEUeo72nS-vag6J35UIdUxdqrQYBixeKjw3vidLN7md2qNRR3fuhzejpkV05DXfyU-bDLa17wn42Ad9L5mId9mNrF9E5oVOGfnrNuoACtCgUp7ntJFBrlhzfNBXJa6AcTOrMSIX5pkXuU4ULhjFw92DqPShbUKCFQFl8UHCmU5u6263t5sSeZmwhmU65fwUeFNnbrMMePYKvRhAOEqe88djreX2j4ErAhBaDQNWVmijtqh32LFHvm_WVX8BmfY5T5-0rfMmRqZXNgesDNEdQRp1FqnSKe9rk22j4DM3y3UiXiMdS2U6eEVD_aeeQZUAqTfS7Q-cWJAxxWQLkrqeMrbLPFD6tfvac_4NQ1sgOG-CNaszkR-_0cwV1c9udQ.9FtyIM8BlR7sQXnO2ILV0CVuhiOy7oxZ8Aol2niJae9apU5T6ff5pynLqsmf6zx1fACne9vW7eNhKfup2LZWUg", "loggedInUserName": "usadm002", "loggedIndomain": "gisus"}
I need to extract token and use in 2nd API
Use JSON Extractor Postprocessor for this purpose. Add the JSON extractor element to the request which returns the above-mentioned response. Then configure it as below:
Name of the created variables: TOKEN (Any name)
JSON Path Expressions: .token
Default Values: NOT_FOUND (The Custom value you want to see by default)
Then you can use the variable in your subsequent requests as ${TOKEN}

Error: java.lang.IllegalArgumentException: Request must not be null

I am using B4A for calling ASMX service also used httputils2 library.
I use the following code for calling service:
Private httprequest As HttpJop
httprequest.Initialize("Job1", Me)
httprequest.PostString("http://192.168.1.104/service.asmx/query","mysql="&"insert into users (facebook_id) values ('ersdxc')")
When I run my application, I get this error:
java.lang.IllegalArgumentException: Request must not be null.
How can I fix it?
You will have to :
load in your browser the asmx file when it is compiled
click on the method
copy the post soap
copy the headers (content-type and SOAPaction)
generate in B4A a multiline string literal with the soap (f.e. stringliteral = $"..."$)
replace in this string literal the string query with the value "mysql=insert into users (facebook_id) values ('ersdxc')" which you will have to urlencode with stringutils and on the asmx side urldecode.
post the string literal with the headers f.e.
Private httprequest As HttpJop
httprequest.Initialize("Job1", Me)
httprequest.PostString("http://192.168.1.104/service.asmx/query", stringliteral)
httprequest.GetRequest.SetContentType("text/xml; charset=utf-8")
httprequest.GetRequest.SetHeader("SOAPAction", """REPLACE_WITH_YOUR_SOAP_ACTION_HERE""")
Please also note that the HttpUtils2 is deprecated and you will have to use the OkHttp and OkHttpUtils2 libraries. There is no difference in the code when using these two libraries.

What is the proper way to add a map in a REST request

I'm using Google Endpoint and for one of my entities I want to create a POST request that adds a map of properties. What is the right way to do it?
I know Google Endpoint can receive a Collection as a parameter, but I want to add a map (unknown key values).
Should I pass a JSON as a parameter or just add the JSON in the body of the request and extract it from the HttpServletRequest object?
I would avoid passing it as a parameter. You can send it in the body of the request and then use json library to get a python object.
https://docs.python.org/3/library/json.html
Every JSON object is a map, so it looks like the most obvious choice. GSON makes it easy, but you can use other parsers too.
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson("{'k1':'apple','k2':'orange'}", type);

Play Framework & JSON Web Token

Is there a Scala implementation of JWT or at least an example with Play? After having posted this question I searched further on the Internet and found some intros to JWT. Any suggestion would be really appreciated.
I am using Nimbus-JOSE-JWT in a spray.io app and am quite happy with it. The object performing authentication extends HttpAuthenticator and if it finds a correct JWT it returns the token subject and related info, otherwise None (authentication fails). With Play2 you can implement HTTP Basic Auth with something like this. Regarding token setting/getting which I assume is of more interest to you:
First, create a private/public key pair (I used parts of this code). Create the authentication object that loads the keys on initialization from the filesystem.
Create a a com.nimbusds.jose.crypto.MACSigner and a com.nimbusds.jose.crypto.MACVerifier using these keys.
Whenever you want to set a key, FIRST encrypt it, THEN sign it. Encryption:
private def encrypt(subject: String) = {
val header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM)
val jwt = new EncryptedJWT(header, claimSet(subject))
val encrypter = new RSAEncrypter(publicKey.asInstanceOf[java.security.interfaces.RSAPublicKey])
jwt.encrypt(encrypter)
jwt.serialize()
}
The claimSet method predictably returns a set of claims:
def claimSet(subject: String) = {
val jwtClaims = new JWTClaimsSet()
jwtClaims.setIssuer(Config.JWT.issuer)
jwtClaims.setSubject(subject)
jwtClaims.setJWTID(java.util.UUID.randomUUID().toString())
jwtClaims
}
The publicKey property is the value returned from KeyFactory.getInstance("RSA").generatePublic.
Signing:
private def sign(jwt: String) = {
val jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256), new Payload(jwt))
jwsObject.sign(Tokens.signer)
jwsObject.serialize
}
Given the above, when you receive a key you need to verify the signature first, then decrypt it. For verification, first you try to parse it with com.nimbusds.jose.JWSObject.parse(my_token) and as long as it doesn't throw a ParseException you call verify on the JWSObject that parse returns, using as an argument the MACVerifier that you created earlier. If verify returns true, you only need to call getPayload.toString on the same JWSObject to get the verified payload.
To decrypt the verified payload you call com.nimbusds.jwt.EncryptedJWT.parse on it, then something like:
val decrypter = new RSADecrypter(privateKey.asInstanceOf[java.security.interfaces.RSAPrivateKey])
jwt.decrypt(decrypter)
privateKey is the value returned from KeyFactory.getInstance("RSA").generatePrivate.
You can then get the claim set with jwt.getJWTClaimsSet.
Finally, with regard to setting the Authorization header, I'm doing this on my AngularJS client using principles also mentioned in this post.

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."