Jwt Token And How To Encode Jwt Token In Spring Boot
Posted By : Sahil Dwivedi | 31-May-2018
Before we Start I want to give you Overview about Jwt token what is Jwt token? what is the Structure of it
Jwt Stand for 'JSON Web Tokens' which contain three parts separated by dots (.), which are:
"aaaa.bbbb.cccc"
where aaaa-->Header
bbbb-->PayLoad
cccc-->Signature
Let's have discussions these three parts
1)Header:-it contains two parts such as the first one are the type of the token, which is 'JWT', and the second one is the hashing algorithm which is used to encrypt, such like HMAC SHA256 or RSA.we can see as
example:
{
"type": "JWT"
"algorith": "HS512",
}
2)Payload:-payload contains Claims. Claims stand as statements about an entity like(typically, the user) and additional metadata information. There are three kinds of claims: 1)reserved 2)public 3)private claims.
example :
{
"name": "ABC",
"sub": "1234567890",
"admin": true
}
3)Signature:-this part required to take the header, payload, a secret key and An algorithm describe the header, and sign.
example if you are using HMAC SHA512 algorithm for encryption, the signature will be created in this way:
HMACSHA512(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
Let's have discussions about how we can encode Jwt Token in Spring Boot
For Parsing jwt token we need to require to know what is secret key because the Secret key is the encoded Signature of Jwt Token which is done by algorithms.
Jwt Token is a container of header, payload, and signature.we use a secret key to encrypt signature part
private String secret = "*******";
for encryption, you have to take same secret key which is used while creating Jwt Token in your other application or from where you are getting token.
the following class is used to Claims is used to get the body(payload) which contain our data by using secret key encrypt it and get the payload
public JwtUser validate(String token) {
JwtUser jwtUser = null;
try {
Claims body = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
jwtUser = new JwtUser();
jwtUser.setUserName(body.getSubject());
jwtUser.setId(Long.parseLong((String) body.get("userId")));
jwtUser.setRole((String) body.get("role"));
}
catch (Exception e) {
System.out.println(e);
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sahil Dwivedi
Sahil Dwivedi is an associate consultant developer,he has knowledge of core Java and AngularJS. His hobbies are watching movies,playing football and Listening music.He is creative person.