Wald aldera
Wald aldera

Reputation: 127

JAVA Code generate a HS512 secret key to use with JWT

I write the code to generate an HS512 secret key to use with JWT and this code I will using to POST data in jhipster.

import org.springframework.boot.autoconfigure.SpringBootApplication;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class ProcessApplication {


    private static String key = "random_secret_key";
    private  static String base64Key = DatatypeConverter.printBase64Binary(key.getBytes());
    private static byte[] secretBytes = DatatypeConverter.parseBase64Binary(base64Key);

    private static String generateToken(String subject, String auth) {
        Date exp = new Date(System.currentTimeMillis() + (1000 * 120)); 

        String token = Jwts.builder()
                .setSubject(subject)
                .claim("auth", auth)
                .setExpiration(exp)
                .signWith(SignatureAlgorithm.HS512, secretBytes)
                .compact();


        return token;
    }

    private static void verifyToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(secretBytes)
                .parseClaimsJws(token).getBody();

        System.out.println("----------------------------");
        System.out.println("Issuer: " + claims);
        System.out.println("Expiration : " + claims.getExpiration());

    }


    public static void main(String... args) throws Exception {


          String token = generateToken("admin", "ROLE_ADMIN,ROLE_USER");

            System.out.println("TOKEN :: "+token);
            verifyToken(token);

        ProcessApplication http = new 
 ProcessApplication();

                System.out.println("\nTesting 2 - Send Http POST request");
                http.sendPost(token);
    }
}

// HTTP POST request
    private void sendPost(String token) throws Exception {

        String url = "http://localhost:8080/api/hussains";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        //add request header
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("Authorization", "Bearer "+token);
        con.setRequestProperty("","http://localhost:8080/api/hussains");
        // optional default is POST
        con.setRequestMethod("POST");

         //Create JSONObject here
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("id","");
        jsonParam.put("name",1001);
        OutputStreamWriter out = new   
        OutputStreamWriter(con.getOutputStream());
        out.write(jsonParam.toString());
        out.close();  


        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

    }

IF I use Header Which gives it to me when using the API it is work

like that

con.setRequestProperty("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTUzNDQ4MDc4MX0.WhFTB4CKjkCNJQMVtEpHDXNpXpe3cM9duOZj6QaJ01rWihW4SbfcVGO0vLkbl6w0lyrdoRkYuuHOCaLTaqvz9g");

if use the genartion JWT it give me error

 Send Http POST request

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: http://localhost:8080/api/hussains
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)

Upvotes: 5

Views: 12053

Answers (1)

user9455968
user9455968

Reputation:

You use

private static String key = "random_secret_key";

to generate the secretBytes from. When you send the JWT to the server, he probably tries to validate the JWT. This includes verifying the signature that is part of the JWT. For this, the server needs to know the shared secret random_secret_key so he can generate the same secreteBytes from them. Whithout this, the server can't validate the signature of the JWT and will reject it.

Upvotes: 3

Related Questions