【问题标题】:JAVA Code generate a HS512 secret key to use with JWTJAVA 代码生成与 JWT 一起使用的 HS512 密钥
【发布时间】:2019-01-22 23:57:03
【问题描述】:

我编写代码来生成与 JWT 一起使用的 HS512 密钥,我将使用此代码在 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);

    }

如果我使用 Header 它在使用 API 时给我它是有效的

这样

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

如果使用 genartion JWT 它会给我错误

 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)

【问题讨论】:

    标签: java jwt token jhipster


    【解决方案1】:

    你使用

    private static String key = "random_secret_key";
    

    从中生成secretBytes。当您将 JWT 发送到服务器时,他可能会尝试验证 JWT。这包括验证作为 JWT 一部分的签名。为此,服务器需要知道共享秘密random_secret_key,以便他可以从它们生成相同的secreteBytes。否则,服务器无法验证 JWT 的签名并将拒绝它。

    【讨论】:

    • 怎么样?你做了什么?
    • i 但是 jhipster 在 application-dev.yml 文件中给出的密钥
    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    相关资源
    最近更新 更多