OAuth 2.0 构建微服务身份认证(三):采用RSA生成JWT签名验签

来源:互联网 发布:vc6.0连接sql数据库 编辑:程序博客网 时间:2024/06/13 23:28

JAVA整体实现过程转接上一篇


签名、验签类

/** * Created by joy on 2017/8/17. */public class TokenAuthenticationService {    static final long EXPIRATIONTIME = 432_000_000;     // 5天    static final String SECRET = "P@ssw02d";            // JWT密码    static final String TOKEN_PREFIX = "JOY";        // Token前缀    static final String HEADER_STRING = "Authorization";// 存放Token的Header Key       // JWT生成RSA签名方法    public static void addAuthenticationByRSA(HttpServletResponse response, String username) {        //获取签名私钥        KeyPair keyPair = JwtRsaUtil.getInstance().getKeyPair("private");        // 生成JWT        String JWT = Jwts.builder()                // 保存权限(角色)                .claim("authorities", "ROLE_ADMIN,AUTH_WRITE")                // 用户名写入标题                .setSubject(username)                // 有效期设置                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))                // 签名设置                .signWith(SignatureAlgorithm.RS256, keyPair.getPrivate())                .compact();        // 将 JWT 写入 body        try {            response.setContentType("application/json");            response.setStatus(HttpServletResponse.SC_OK);            response.getOutputStream().println(JSONResult.fillResultString(0, "", JWT));        } catch (IOException e) {            e.printStackTrace();        }    }    // JWT验证RSA签名方法    public static Authentication getAuthenticationByRSA(HttpServletRequest request) {        // 从Header中拿到token        String token = request.getHeader(HEADER_STRING);        //获取签名私钥        KeyPair keyPair = JwtRsaUtil.getInstance().getPublicPair("public");        if (token != null) {            // 解析 Token            Claims claims = Jwts.parser()                    // 验签                    //.setSigningKey(SECRET)                    .setSigningKey(keyPair.getPublic())                    // 去掉 Bearer                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))                    .getBody();            // 拿用户名            String user = claims.getSubject();            // 得到 权限(角色)            List<GrantedAuthority> authorities =  AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));            // 返回验证令牌            return user != null ?                    new UsernamePasswordAuthenticationToken(user, null, authorities) :                    null;        }        return null;    }}


从JKS获取公钥、私钥证书工具类,公钥、私钥获取方法独立来写了;

public class JwtRsaUtil {    private String keyStoreFile;    private char[] password;    private KeyStore store;    private Object lock = new Object();    private static JwtRsaUtil instance = null;    public static JwtRsaUtil getInstance() {        synchronized (JwtRsaUtil.class) {            if (instance == null) {                synchronized (JwtRsaUtil.class) {                    instance = new JwtRsaUtil("/jwt_truststore.jks", "joyshebao".toCharArray());                }            }            return instance;        }    }    private JwtRsaUtil(String _jksFilePath, char[] password) {        this.keyStoreFile = _jksFilePath;        this.password = password;    }    public KeyPair getKeyPair(String alias) {        return getKeyPair(alias, this.password);    }    public KeyPair getKeyPair(String alias, char[] password) {        try {            synchronized (this.lock) {                if (this.store == null) {                    synchronized (this.lock) {                        InputStream is = this.getClass().getResourceAsStream(keyStoreFile);                        try {                            this.store = KeyStore.getInstance("JKS");                            this.store.load(is, this.password);                        } finally {                            if (is != null) {                                try {                                    is.close();                                } catch (Exception e) {                                }                            }                        }                    }                }            }            RSAPrivateCrtKey key = (RSAPrivateCrtKey) this.store.getKey(alias, password);            RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());            PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);            return new KeyPair(publicKey, key);        } catch (Exception e) {            throw new IllegalStateException("Cannot load keys from store: " + this.keyStoreFile, e);        }    }    public KeyPair getPublicPair(String alias) {        return getPublicPair(alias, this.password);    }    public KeyPair getPublicPair (String alias, char[] password) {        try {            synchronized (this.lock) {                if (this.store == null) {                    synchronized (this.lock) {                        InputStream is = this.getClass().getResourceAsStream(keyStoreFile);                        try {                            this.store = KeyStore.getInstance("JKS");                            this.store.load(is, this.password);                        } finally {                            if (is != null) {                                try {                                    is.close();                                } catch (Exception e) {                                }                            }                        }                    }                }            }            RSAPrivateCrtKey key = (RSAPrivateCrtKey) this.store.getKey(alias, password);            PublicKey publicKey= this.store.getCertificate(alias).getPublicKey();            return new KeyPair(publicKey, key);        } catch (Exception e) {            throw new IllegalStateException("Cannot load keys from store: " + this.keyStoreFile, e);        }    }}




阅读全文
0 0
原创粉丝点击