ログインしてtokenを生成し、暗号化アルゴリズムでtokenを生成する

7437 ワード

1.パッケージtokenのパラメータ(tokenParam)
 
public class TokenParam {

    @NotBlank(message = "identity-server_token_get_0001::username can not be null")
    private String username;
    @NotNull(message = "identity-server_token_get_0002::password can not be null")
    private String password;
    private Integer userType;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getUserType() {
        return userType;
    }

    public void setUserType(Integer userType) {
        this.userType = userType;
    }
}

2.認証情報のカプセル化(IdentityUser)
 
public class IdentityUser {

    private String userId;
    private String username;
    private Integer userType;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getUserType() {
        return userType;
    }

    public void setUserType(Integer userType) {
        this.userType = userType;
    }
}

3.JwtUtilツールクラスの作成
 
private static final String KEY_DECODE_ALGORITHM = "AES";
private static final String RSA_ALGORITHM = "RSA";
private static final String DEFAULT_USER_KEY = "userId";
private static SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256; //  RSA246

3つのパラメータ(ビジネス・レイヤ呼び出し用)
 
 // @Desccription   jwt token
public static String createJWT(String key, IdentityUser user, long expireTime) throws GCloudException{
    if(signatureAlgorithm == null){
        throw new GCloudException("identity_token_jwt_0001::this algorithm is not supported");
    }
    return createJWT(signatureAlgorithm, key, user, expireTime);
}

4つのパラメータ(内部呼び出し)
 
 
public static String createJWT(SignatureAlgorithm signatureAlgorithm, String key, IdentityUser user, long expireTime) throws GCloudException{

    String token = null;
    Key secretKey = null;
    Map paramMap = null;

    try{
        secretKey = getCreateKey(signatureAlgorithm, key);
    }catch(GCloudException sex){
        throw sex;
    }catch(Exception ex){
        throw new GCloudException("identity_token_jwt_0003::get secret key failed");
    }

    Date expDate = new Date(expireTime);

    Date nowDate = new Date();
    String jwtId = KeyUtil.getUuid();
    JwtBuilder builder = Jwts.builder().setId(jwtId)
            .setIssuedAt(nowDate)
            .setSubject(user.getUserId())
            .setExpiration(expDate)
            .signWith(signatureAlgorithm, secretKey);
    try{
        paramMap = ObjectUtil.objectToMap(user);
        if(paramMap != null){
            paramMap.remove(DEFAULT_USER_KEY);
            if(paramMap.size() > 0){
                builder.addClaims(paramMap);
            }
        }
    }catch(Exception ex){
        throw new GCloudException("identity_token_jwt_0004::get user info faied");
    }

    try{
        token = builder.compact();
    }catch(Exception ex){
        throw new GCloudException("identity_token_jwt_0005::generate token failed");
    }


    return token;
}

 
/*
 * @Desccription          key
 */
private static Key getCreateKey(SignatureAlgorithm signatureAlgorithm, String key) throws Exception {

    Key result = null;
    if(SignatureAlgorithm.RS256.equals(signatureAlgorithm) || SignatureAlgorithm.RS384.equals(signatureAlgorithm) || SignatureAlgorithm.RS512.equals(signatureAlgorithm)){
        result = generalRSPublicKey(key);
    }else if(SignatureAlgorithm.HS256.equals(signatureAlgorithm) || SignatureAlgorithm.HS384.equals(signatureAlgorithm) || SignatureAlgorithm.HS512.equals(signatureAlgorithm)){
        result = generalHSKey(key);
    }else{
        throw new GCloudException("identity_token_jwt_0008::this algorithm is not supported");
    }

    return result;

}
/*
 * @Desccription
 */
private static Key generalHSKey(String key) throws Exception{
    byte[] encodedKey = new Base64().decode(key);
    Key secretKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, KEY_DECODE_ALGORITHM);
    return secretKey;
}
/*
 * @Desccription     
 */
private static Key generalRSPrivateKey(String key) throws Exception {
    byte[] publicKeyBytes = new Base64().decode(key);
    byte[] publicKeyRealBytes = new Base64().decode(publicKeyBytes);

    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyRealBytes);
    KeyFactory keyFac = KeyFactory.getInstance(RSA_ALGORITHM);

    return keyFac.generatePublic(keySpec);
}

 
 
4.ツールクラスのcreatJWTメソッドを呼び出すtokenマネージャクラス(TokenManager)を作成します.
 
 
public Token generateToken(IdentityUser user) throws GCloudException {

    Long expireTime = System.currentTimeMillis() + identityServerTokenProp.getVaildTime(UserType.getByValue(user.getUserType()));
    String tokenId = JwtUtil.createJWT(identityServerTokenProp.getEncryptKey(), user, expireTime);

    Token token = new Token();
    token.setUser(user);
    token.setTokenId(tokenId);
    token.setExpireTime(expireTime);

    return token;
}

5.コントローラマッピングの方法
 
@RequestMapping("token.do")
public RequestResult token(@Validated TokenParam param){

    TokenResponse response = userService.token(param);

    return new RequestResult(response);
}

6.業務層(TokenService)に対応するtoken(TokenParam param)方法
 
@Override
public TokenResponse token(@Validated TokenParam param) throws GCloudException {

    Integer userType = param.getUserType();
    if(userType == null || UserType.getByValue(param.getUserType()) == null){
        userType = UserType.USER.getValue();
    }
    User user = userDao.getUserByNameAndType(param.getUsername(), userType);
    if(user == null){
        throw new GCloudException("identity-server_token_get_0003::user does not exist");
    }

    String md5Pwd = "";
    try{
        md5Pwd = MD5Util.encrypt(param.getPassword());
    }catch (Exception ex){
        log.error("mgr_user_save_0005,  md5    ", ex);
        throw new GCloudException("server_token_get_0004::password encrypt error");
    }

    if(md5Pwd == null || !md5Pwd.equals(user.getPassword())){
        throw new GCloudException("server_token_get_0005::password is not correct");
    }
    //        
    IdentityUser idUser = new IdentityUser();
    idUser.setUsername(user.getUsername());
    idUser.setUserId(user.getId());
    idUser.setUserType(user.getUserType());
    //  TokenManager generateToken(IdentityUser idUser)  
    Token token = tokenManager.generateToken(idUser);

    TokenResponse response = new TokenResponse();
    response.setToken(token);
    response.setUserId(user.getId());

    return response;
}