How to verify that a string is JWT token? - java

In Java How can we verify that i given String is a JWT Token without using Signature?
I am using
try {
return (new JwtConsumerBuilder()).setVerificationKey(SECRET_KEY).build().processToClaims(token);
} catch (InvalidJwtException var4) {
throw new IOException("Failed to parse");
}
This works fine but I want to verify this without SECRET_KEY.
I Just want to verify whether it is a JWT token or not.

Here is an example to check the structure of the JWT. You only need to add the validations of the data that the JWT should carry
boolean isJWT(String jwt) {
String[] jwtSplitted = jwt.split("\\.");
if (jwtSplitted.length != 3) // The JWT is composed of three parts
return false;
try {
String jsonFirstPart = new String(Base64.getDecoder().decode(jwtSplitted[0]));
JSONObject firstPart = new JSONObject(jsonFirstPart); // The first part of the JWT is a JSON
if (!firstPart.has("alg")) // The first part has the attribute "alg"
return false;
String jsonSecondPart = new String(Base64.getDecoder().decode(jwtSplitted[1]));
JSONObject secondPart = new JSONObject(jsonSecondPart); // The first part of the JWT is a JSON
//Put the validations you think are necessary for the data the JWT should take to validate
}catch (JSONException err){
return false;
}
return true;
}

You can decode JWT from base64 and check necessarily field. Or simply check token, why you want verify it, It's not faster then simpy check it.

Try this one.
public static JSONObject getPayload(String jwt) {
try {
Base64.Decoder dec = Base64.getDecoder();
final String payload = jwt.split(SecurityConstants.SPLIT_SLASH)[PAYLOAD];
final byte[] sectionDecoded = dec.decode(payload);
final String jwtSection = new String(sectionDecoded, SecurityConstants.CODE_PAGE);
return new JSONObject(jwtSection);
} catch (final UnsupportedEncodingException e) {
throw new InvalidParameterException(e.getMessage());
} catch (final Exception e) {
throw new InvalidParameterException(SecurityConstants.ERROR_IN_PARSING_JSON);
}
}
Next You need to get from jwt body this part which is important for You eg.
JSONObject body = JWTUtils.getPayload(token);
String username = body.getString("username");

Related

setting "apns-collapse-id" in apns header

I am very new to this concept, and I am trying to create a notification, which can be deleted or modified from server, by looking so I came across "apns-collapse-id". The problem is by setting this using the below code does not change the content of notification, it is just like an extra key added.
I'm trying to understand if i need to make any changes to make it work.
PushNotificationPayload payload = PushNotificationPayload.complex();
payload = new PushNotificationPayload(){
public int getMaximumPayloadSize()
{
return 2048;
}};
payload.addBadge(1);
payload.addSound("default"); //No I18N
payload.addCustomDictionary("rfid","testRfid");
payload.addAlert("test notification2");
JSONObject aps = payload.getPayload().getJSONObject("aps");
JSONObject apsAlert = null;
try
{
apsAlert = aps.getJSONObject("alert");
}
catch(JSONException jse)
{
apsAlert = new JSONObject();
try
{
String apsAlertMsg = aps.getString("alert");
if(apsAlertMsg!=null)
{
apsAlert.put("body",apsAlertMsg);
}
}
catch(JSONException jse1)
{
}
}
aps.put("content-available","1");
aps.put("apns-collapse-id", "12345");

How to throw a parseException in a switch statement?

To increase my projects code coverage, I need to reach the branch ParseException in this method:
public String filterMessage(String actionIn, String messageIn) {
String message = null;
try{
switch (actionIn) {
//EDIT: this calls the other class causing parseexception
case "search":
message = (srvmt.SearchEngine(messageIn));
break;
default:
message = messageIn;
break;
}
}catch (ParseException e) {
System.out.println("Encountered parse exception");
e.printStackTrace();
}catch(IOException ioException){
ioException.printStackTrace();
}
return message;
}
Instincts are that we must put a String that is "illegal", that can't be parsed because it isn't actually a String, but how do you place something like that without causing a compile error (like putting an int to cause faulse parsing). Any ideas how to test this catch "branch"?
EDIT: This is the method the case above calls which uses a parse exception
public String SearchEngine(String removecommand)
{//INCOMING-SEARCH¿Email¿#gmail.com
JSONArray databaseupdated = read(pathdatabase);
ArrayList<String> matchlist = new ArrayList<String>();
JSONObject mainobj = new JSONObject();
JSONArray userinfo = new JSONArray();
JSONObject obj = new JSONObject();
for(int i = 0; i<databaseupdated.size(); i++)
{
String option = "";
String value = "";
try {
JSONObject json = (JSONObject) new JSONParser().parse(removecommand);
option = (String) json.get("option");
value = (String) json.get("value");
mainobj= (JSONObject) new JSONParser().parse(databaseupdated.get(i).toString());
userinfo =(JSONArray) new JSONParser().parse(mainobj.get(mainobj.keySet().toString().substring(1,mainobj.keySet().toString().length()-1)).toString());
obj = (JSONObject) new JSONParser().parse(userinfo.get(0).toString());
} //EDIT, there is a lot of code not explained, but here is the parse EXCEPTION
catch (ParseException e) {
return "false";
}
if(SearchEngineTRUEFALSE1(mainobj.keySet().toString().substring(1,mainobj.keySet().toString().length()-1),option,value))
{
matchlist.add(obj.get("Email").toString());
}
}
return matchlist.toString();
}
Try this :
throw new ParseException("Parse exception description you want");
you could throw an exception as Michaël told and if you are using Junit to test, you could do something like this using the expected annotation to catch it
#Test(expected= ParseException)
public void testFilterMessage() {
filterMessage(illformedString1, illformedString2);
}
Given your updated question:
You want to look into using a mocking framework.
Basically you have to enable your class under test so that you can provide a mocked srvmt object to it. And you configure that mock to simply throw that exception upon calls to the method it owns. Well, one of your test case configures the mock to throw that exception; other testcases would configure the mock to return other results.
In other words: search for terms like "dependency injection" and "mocking"; study and apply.

Using Optional<T> from java SE 8

Hi I want to know how I can use Optional in java SE 8 in the function below.
public URL getAuthenticatedURL() throws MalformedURLException {
if (log != null){
log.writeINFOToLog("Fetching authentication URL...");
}
else{
Log.initLog();
log.writeINFOToLog("Fetching authentication URL...");
}
try{
String url = String.format("%s://%s%s?username=%s&password=%s",getProtocol(), getHost(), getPath(), getUsername(), getPassword());
URL returnURL = new URL(url);
return returnURL;
}
catch (MalformedURLException ex){
log.writeExceptionToLog(ex);
return null;
}
}
I want to be able to handle the scenario where values involved in constructing the URL is null or empty.
After some research, I think its best that I avoid nulls, since it does not make much sense to have a null.
Here is my code snippet of the same function once I have used Optional<URL>
public Optional<URL> getAuthenticatedURL() throws MalformedURLException {
if (log != null){
log.writeINFOToLog("Fetching authentication URL...");
}
else{
Log.initLog();
log.writeINFOToLog("Fetching authentication URL...");
}
String url = String.format("%s://%s%s?username=%s&password=%s",getProtocol(), getHost(), getPath(), getUsername(), getPassword());
return Optional.ofNullable(new URL(url));
}
So when I call the function the code will be something like this.
if(getAuthenticatedURL.isPresent()){
URL val = getAuthenticatedURL.get();
}
I think it is more reasonable to use Supplier than Optional, because getAuthenticatedURL() has no argument and generates an Object(URL).
It looks like:
Supplier<URL> supplier = () -> {
...
try {
return new URL(...);
} catch (MalformedURLException e) {
return null;
}
};
URL url = supplier.get();

Wrong key being set with HashMap in Intellij Idea

Here is my function:
public String uploadImage(URL image,String message) throws Exception{
HashMap<String,String> paramArgs=new HashMap<String,String>();
paramArgs.put("fbImgPostURL","https://graph.facebook.com/me/photos");
paramArgs.put("accessToken",accessGrant.getKey());
paramArgs.put("imageURL",image.toString());
paramArgs.put("message",message);
return HttpPictureUpload.uploadImageViaHttpPost(paramArgs);
}
and while i debug it from intelliJ debugger, strangely in the line
paramArgs.put("accessToken",accessGrant.getKey());
Clearly the key is accessToken. But the debugger shows it as follows:
access_token=CAACKan8suD0BAKUZAyxLinmXw2PZAkmkhIhVZCojG1sE2QsW60CfQjZAJWyMbqc1Lxy1JmVmSyAU4eHOGSkHhqJSQE6tcORuXAkyFbok7WGyysgJYZC6QF6KZBPRwDwbPCE6JUJgKIGyXzZCfzVgnjHHuoZBLZBt2xXgZD
So clearly the problem is that I am setting a different key name but in hash map, a different key name is being set which is actually passed to
HttpPictureUpload.uploadImageViaHttpPost(paramArgs);
Anyone here could guess that what is going on?
Edit:
Here is my uploadImageViaHttpPost() function:
public static String uploadImageViaHttpPost(HashMap<String,String> keyParams){
String in="Image Uploaded Successfully!!";
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(keyParams.get("fbImgPostURL"));
//Add any parameter if u want to send it with Post req.
method.addParameter("accessToken", keyParams.get("accessToken"));
method.addParameter("url",keyParams.get("imageURL"));
method.addParameter("message",keyParams.get("message"));
int statusCode = client.executeMethod(method);
if (statusCode != -1) {
in = method.getResponseBodyAsString();
}
System.out.println(in);
} catch (Exception e) {
e.printStackTrace();
}
return in;
}

make multiple http post in android

hello i want to ask some question
i want to make application that connected with a web services that i made
my app has 2 uniqueID called app_id and token, app_id generate only once when the app first start and token generated by web service
every request, i must check whenever the token already expired or not, if the token already expired it will call separate web service and generate new token
the problem is the app must access 2 different web service: to request new token and to get another desired data
i use asynctask, but the response from web service for request token always same every request and i have no idea why
protected Boolean doInBackground(Void... params) {
int status = 0;
int token_expired=0;
String token_val = token.getToken(getBaseContext());
for(int i=0;i<5 && status==0;i++) {
try {
Thread.sleep(1000);
//function to check if token already expired or not and request new token using http post
token_expired = token.checkToken(getBaseContext());
System.out.println("token expired: " +token_expired);
if (token_expired==1 || token_expired==2) {
//function to call another web service and get a data from it
status = rclient.Execute("POST");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (status==0) {
return false;
}else{
return true;
}
}
thanks before!
oh yeah this is a function of check token from class token handler
public Integer checkToken(Context context) {
int status = 0; //0 = failed to request token , 1 = successfully request new token, 2 = token has not expired yet
String token_id = getToken(context);
System.out.println("token_id: " +token_id);
//if (token_id!=null) {
Long time = getTime(context);
Long curr_time = System.currentTimeMillis()/1000;
System.out.println("time before: " +time);
System.out.println("time current: " +curr_time);
Long interval = curr_time - time;
System.out.println("interval: " +interval);
if (interval>10) {
status = TokenGenerator(context);
}else {
status = 2;
}
//}
return status;
}
}
and this is a function to request new token from the same class
public synchronized Integer TokenGenerator(Context context) {
int status = 0;
SharedPreferences sharedPrefs = context.getSharedPreferences(TOKEN_STORAGE, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
try {
rclient.AddJSON("app_id", uniqueID);
rclient.CompileJSON();
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
status = rclient.Execute("POST");
} catch (Exception e) {
e.printStackTrace();
}
if (status==1) {
String response = rclient.getResponse();
String token = null;
System.out.println("uuid_response: " +response);
try {
JSONObject json = new JSONObject(response);
token = json.getString("result");
} catch (JSONException e) {
e.printStackTrace();
}
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
System.out.println("time: " +ts);
Editor editor = sharedPrefs.edit();
editor.putString(TIMESTAMP, ts);
editor.putString(TOKEN_ID, token);
editor.commit();
}
return status;
}
so basically the rest client class called two times, first at class token handler to request a new token, and second from the activity itself
As per the code posted by you, I think rclient.Execute("POST") is used to get the data. But the below piece of code
if (token_expired==1 || token_expired==2) {
//function to call another web service and get a data from it
status = rclient.Execute("POST");
}
says that if the token is still alive you are trying to get the new token again.
I think the line status = rclient.Execute("POST"); should be replaced with the code to fetch the data from the server.
problem solved after i put constructor of rest client class in function

Categories