How to Integrate JWT in JAVA WebServices?



Image result for jwt



JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
JWT.IO allows you to decode, verify and generate JWT.


Desired information is encoded using specified algorithm and secret phrase. Special information (defined in Registered Claim Names section of standard) may be added, like expiration time. Some of this information, such as exp, is handled automatically by specific implementations. The output is a token of the following type aaaaa.bbbbb.ccccccc.
The generated token is passed to a client. There is a few choices of where to store tokens in the client. For web-application it can be a local storage or cookies. There is the discussion on the internet on this topic, such as [1].
On requests, token is attached to headers or passed in cookies, depending on chosen storage. Server app is responsible for decoding and validation of data encoded, as well as for resolving permissions.
The key concept of JWT is that data stores in token itself. It allows to decentralize storage and avoid explicit storing data on server side.

JWT String

Header

{
 "typ": "JWT",
 "alg": "HS256"
}

Payload

{
 "sub": "1234567890",
 "name": "John Doe",
 "admin": true,
 "jti": "4ffcb230-d538-4566-a26e-76bbc3f32aed",
 "iat": 1496054316,
 "exp": 1496057916
}

Signing Key    Verified







































public static String secretKey = "silenthacker";




Create JWT (Java Web Tokens)





public static String createJWT(String id,  String roles) {

try {

Claims claims = Jwts.claims().setSubject("www.silenthacker.in");
claims.put("userId", id);
claims.put("role", roles);


Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date()); // sets calendar time/date
cal.add(Calendar.HOUR, 2); // adds one hour
Date date = cal.getTime(); // returns new date object, one hour in
// the future
String jwt = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secretKey)
.setExpiration(date).compact();

return jwt;

} catch (Exception e) {
return null;

}

}




Authentic JWT






public static boolean authenticateJWT(String token) {
try {

Claims body = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();

String subject = body.getSubject();
String id = (String) body.get("userId");
String role = (String) body.get("role");
if (id != null) {
return true;
}
return false;
} catch (Exception e) {

return false;
}

}





Main Method to call




public static void main(String[] args) {
try {

String jwt=createJWT("1", "admin");
boolean authResult=authenticateJWT(jwt);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


Latest
Next Post

post written by:

0 comments: