Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Most of Second PR #2

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ public class TokenExpiredException extends JWTVerificationException {
public TokenExpiredException(String message) {
super(message);
}
}
}
250 changes: 250 additions & 0 deletions lib/src/main/java/com/auth0/msg/AbstractMessage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
package com.auth0.msg;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You haven't refactored for package name?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.util.*;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add sepcific import.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


/**
* This abstract class provides basic processing of messages
*/
public abstract class AbstractMessage implements Message {
private Map<String, Object> claims;
private Map<String, Object> header; // There are only headers when fromJwt/ToJwt is called
private String input;
private Error error = null;
private boolean verified = false;
ObjectMapper mapper = new ObjectMapper();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this need to be protected?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


protected AbstractMessage() {
this(Collections.<String, Object>emptyMap());
}

protected AbstractMessage(Map<String, Object> claims) {
this.claims = claims;
}

/**
* @param input the urlEncoded String representation of a message
*/
public void fromUrlEncoded(String input) throws MalformedURLException, IOException {
this.input = input;
String msgJson = StringUtils.newStringUtf8(Base64.decodeBase64(input));
// Convert JSON string to Object
AbstractMessage msg = mapper.readValue(msgJson, this.getClass());
this.claims = msg.getClaims();
}

/**
* Takes the claims of this instance of the AbstractMessage class and serializes them
* to an urlEncoded string
*
* @return an urlEncoded string
*/
public String toUrlEncoded() throws SerializationException, JsonProcessingException {
String jsonMsg = mapper.writeValueAsString(this);
String urlEncodedMsg = Base64.encodeBase64URLSafeString(jsonMsg.getBytes(StandardCharsets.UTF_8));
return urlEncodedMsg;
}

/**
* Logic to extract from the JSON string the values
* @param input The JSON String representation of a message
*/
public void fromJson(String input) {
this.input = input;
try {
// Convert JSON string to Object
// TypeReference<HashMap<String, String>> typeRef
// = new TypeReference<HashMap<String, String>>() {};
AbstractMessage msg = mapper.readValue(input, this.getClass());
this.claims = msg.getClaims();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* Takes the claims of this instance of the AbstractMessage class and serializes them
* to a json string
*
* @return a JSON String representation in the form of a hashMap mapping string -> string
*/
public String toJson() throws SerializationException, JsonProcessingException {
String jsonMsg = mapper.writeValueAsString(this);
if (this.error != null) {
throw new InvalidClaimsException("Error present cannot serialize message");
}
return jsonMsg;
}

/**
* @param input the jwt String representation of a message
* @param KeyJar that might contain the necessary key
*/
public void fromJwt(String input, KeyJar jar) {
this.input = input;

//This will have logic to parse Jwt to claims
}

/**
* Serialize the content of this instance (the claims map) into a jwt string
* @param KeyJar the signing keyjar
* @param String the algorithm to use in signing the JWT
* @return a jwt String
* @throws InvalidClaimsException
*/
public String toJwt(KeyJar keyjar, Algorithm algorithm) throws
InvalidClaimsException, SerializationException {
header.put("alg", algorithm.getName());
header.put("typ", "JWT");
String signingKeyId = algorithm.getSigningKeyId();
if (signingKeyId != null) {
header.put("kid", signingKeyId);
}
// JWTCreator.Builder newBuilder = JWT.create().withHeader(this.header);
// for (Claim claimKey: claims.keySet()){
// newBuilder.withClaim(claimKey.name, (claimKey.type) claims.get(claimKey));
// }
return null;
}

/**
* Serialize the content of this instance (the claims map) into a jwt string
* @param Key the signing key
* @param String the algorithm to use in signing the JWT
* @return a jwt String
* @throws InvalidClaimsException
*/
public String toJwt(Key key, Algorithm algorithm) throws InvalidClaimsException, SerializationException {
return null;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

implementation?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

noted

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

}

/**
* verify that the required claims are present

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking more - this method should be void that throws an exception in case there is any failure.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

* @return whether the verification passed
*/
protected boolean verify() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method signature should tell that this method can throw InvalidClaimsException so that caller can appropriately handle failed validation.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

//This method will set error if verification fails
List<String> errors = new ArrayList<String>();

List<String> reqClaims = getRequiredClaims();
if (!reqClaims.isEmpty() && this.claims.isEmpty()){
errors.add("The required claims are missing");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't help - you are adding error but not returning it.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Corrected

return false;
}

StringBuilder errorSB = new StringBuilder();
for (String req: reqClaims) {
if (!claims.containsKey(req)) {
errors.add("This message is missing required claim: " + req);
errorSB.append(req);
}
}

if (errorSB.length() != 0) {
errors.add("Message is missing required claims:" + errorSB.toString());
return false;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't help - you are adding errors but not returning.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Modified to put error messages into the InvalidClaimException thrown at the end which should be handled upstream and also update the instance of Error object

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Corrected

}

List<String> customClaims = new ArrayList<String>();
for(String claimName : claims.keySet()) {
// if knownClaim, validate claim
if (ClaimsValidator.isKnownClaim(claimName)) {
Boolean valid = ClaimsValidator.validate(claimName, claims.get(claimName), getMessageType());
if (!valid) {
errors.add(claimName + "is an invalid claim");
}
} else {
customClaims.add(claimName);
}
}
if (!errors.isEmpty()) {
String aggregateError = "";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please reuse errorSB instead of aggregateError.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

for (String err: errors){
aggregateError += err;
}
throw new InvalidClaimsException(aggregateError);
}
return false;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where do you set the class level variable 'verified'? and where do you set the class level Error?

}

public abstract MessageType getMessageType();

/**
* add the claim to this instance of message
* @param String the name of the claim
* @param Object the value of the claim to add to this instance of Message
* @return a Message representation of the Json
*/
public void addString(String name, Object value) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not call it addClaim? addString doesn't mean anything.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see another method as addClaim .. can you confirm and remove this one?

// verify 'name’ is a valid claim and then check the type is valid before adding
}

/**
* @return Error an object representing the error status of claims verification
*/
public Error getError() {
return error;
}

/**
* @return List of the list of claims for this messsage
*/
public Map<String, Object> getClaims(){

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the method signature should have throws invalidclaimsexception

// verify();
return this.claims;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should handle the logic -

if(!verrified){
verify();
}
if(error != null){
throw new invalidclaimsexception();
}
return this.claims;

}

/**
* @return List of the list of standard optional claims for this messsage type
*/
protected List<String> getOptionalClaims(){
return Collections.emptyList();
}

/**
* add the claim to this instance of message
* @param String the name of the claim
* @param Object the value of the claim to add to this instance of Message
* @return a Message representation of the Json
*/
public void addClaim(String name, Object value) {
// verify 'name’ is a valid claim and then check the type is valid before adding
}

/**
* @return List of the list of standard required claims for this messsage type
*/
abstract protected List<String> getRequiredClaims();

protected void reset(){

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where are you using this method?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the deserialization methods

this.input = null;
this.claims = null;
this.error = null;
this.verified = false;
}

@Override
public String toString() {
//Override to return user friendly value

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide a good implementation of toString

return super.toString();
}
}
14 changes: 14 additions & 0 deletions lib/src/main/java/com/auth0/msg/AlgorithmEnum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.auth0.msg;

/**
* This enum specifies the encryption and signing algorithm type
*/
public enum AlgorithmEnum {
RS256,
RS384,
RS512,
HS256,
HS384,
HS512,
ES256;
}
61 changes: 61 additions & 0 deletions lib/src/main/java/com/auth0/msg/Claim.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.auth0.msg;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

package name is a problem everywhere

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO


import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class Claim {
public String name;

@JsonProperty("map")
@JsonDeserialize(keyUsing = ClaimDeserializer.class)
public Map<MessageType, List<Object>> allowedValues;
public ClaimType type;

public Claim(String name) {
this(name, Collections.<MessageType, List<Object>>emptyMap(), null);
}

public Claim(String name, ClaimType type) {
this(name, Collections.<MessageType, List<Object>>emptyMap(), type);
}

@JsonCreator
public Claim(String name, Map<MessageType, List<Object>> allowedValues, ClaimType type) {
this.name = name;
this.allowedValues = allowedValues;
this.type = type;
}

public ClaimType getType() {
return type;
}

public void setType(ClaimType type) {
this.type = type;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Map<MessageType, List<Object>> getAllowedValues() {
return allowedValues;
}

@Override
public String toString() {
return this.name;
}

//hashCode()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please override equals and hashcode as you are going to use this class as key

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO


}
15 changes: 15 additions & 0 deletions lib/src/main/java/com/auth0/msg/ClaimDeserializer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.auth0.msg;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;

import java.io.IOException;

public class ClaimDeserializer extends KeyDeserializer {

@Override
public Claim deserializeKey (String key, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return new Claim(key);
}
}
40 changes: 40 additions & 0 deletions lib/src/main/java/com/auth0/msg/ClaimType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.auth0.msg;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
* This enum specifies the claims and their allowed values to enable validation of messages
*/
public enum ClaimType {
// GRANT_TYPE("grant_type", Arrays.asList("refresh_token")),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please clean up

// ERROR("error", Arrays.asList("invalid_request", "unauthorized_client")),
// ISSUER("issuer", Arrays.asList("*")),
// CLIENT_ID("client_id", Arrays.asList("*")),
// KEY_JAR("key_jar", Arrays.asList("*")),
// SHOULD_VERIFY("should_verify", Arrays.asList("*"));
//
// private final String name;
// private final List<String> allowedValues;
//
// ClaimType(String name, List<String> allowedValues) {
// this.name = name;
// this.allowedValues = allowedValues;
// }
BOOLEAN("Boolean", Boolean.class),
STRING("String", String.class),
INT("Int", Integer.class),
LIST("List", List.class),
ARRAY("Array", Array.class),
DATE("Date", Date.class),
LONG("Long", Long.class);

private final String type;
private final Class classType;
ClaimType(String type, Class classType) {
this.type = type;
this.classType = classType;
}
}
Loading