How do i generate JWT token from android

10,034

Solution 1

After much digging in the internet for last day I found the solution to this

  String compactJws = Jwts.builder().claim("email",username).claim("password",password)
                .signWith(SignatureAlgorithm.HS256, "secret".getBytes())
                .compact()

this is the correct way to generate the token from the app side. So that the data is not sent in plain header.

Solution 2

To generate JWT token there is the way to generate:

1) add dependency in gradle

implementation 'io.jsonwebtoken:jjwt:0.7.0'

2) add the following code on the basis of the parameters.

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

             String jwt = Jwts.builder().claim("emailId","[email protected]").claim("emailIdOTP", "123456")
                .claim("phoneNo", "1111111111")
                .signWith(SignatureAlgorithm.HS256, "secret".getBytes())
                .compact();
                Log.v("JWT : - ",jwt);
            }
        });
Share:
10,034

Related videos on Youtube

beginner
Author by

beginner

Updated on June 23, 2022

Comments

  • beginner
    beginner almost 2 years

    How do i generate JWT token from android. I tried the following :

     token = JWT.create().withClaim("email",username)
                            .sign(Algorithm.HMAC256("secret"));
                    System.out.println(" JWS token : "+ token);
    

    But i got this exception :

    java.lang.NoSuchMethodError: No static method encodeBase64URLSafeString([B)Ljava/lang/String; in class Lorg/apache/commons/codec/binary/Base64; or its super classes (declaration of 'org.apache.commons.codec.binary.Base64' appears in /system/framework/ext.jar)
                                                              at com.auth0.jwt.JWTCreator.sign(JWTCreator.java:283)
                                                              at com.auth0.jwt.JWTCreator.access$100(JWTCreator.java:23)
                                                              at com.auth0.jwt.JWTCreator$Builder.sign(JWTCreator.java:264)
                                                              at se.stigasoft.netwrapper.NetCom.jwtWork(NetCom.java:321)
    

    I tried other methos from some other library too.

     String compactJws = Jwts.builder()
                .setSubject("Joe")
                .signWith(SignatureAlgorithm.HS256, "secret".getBytes())
                .compact();
    

    this one generates the token. But i dont know how to send my data like name,value pair that i used to send in the post method .

    . Please help

  • Gyan Swaroop Awasthi
    Gyan Swaroop Awasthi almost 4 years
    What is the name/ dependency need to add for the implementation of the above mentioned code?