All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.dennisit.vplus.data.security.jwt.JWTService Maven / Gradle / Ivy

There is a newer version: 2.0.8
Show newest version
package com.github.dennisit.vplus.data.security.jwt;

import com.github.dennisit.vplus.data.utils.JWTUtils;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.spring.boxes.dollar.term.Authority;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtilsBean2;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.util.Map;

@Slf4j
@EnableConfigurationProperties(JWTConfig.class)
public class JWTService {

    private JWTIFace jwtiFace;

    private JWTConfig jjwtConfigure;

    public JWTService() {
    }


    public JWTService(JWTIFace jwtiFace, JWTConfig jjwtConfigure) {
        this.jwtiFace = jwtiFace;
        this.jjwtConfigure = jjwtConfigure;
    }

    /**
     * 生成Token
     *
     * @param username 用户账号
     * @param password 密码
     * @return 加密串
     */
    public String jwtToken(String username, String password) {
        Authority authority = this.jwtiFace.getAuthority(username, password);
        Preconditions.checkArgument(null != authority, "用户名或密码错误");
        try {
            Map beanMap = BeanUtilsBean2.getInstance().describe(authority);
            String token = JWTUtils.jwtToken(ImmutableMap.copyOf(beanMap), jjwtConfigure.getPrivateKey(), jjwtConfigure.getExpire());
            log.info("username:{}, token:{}", username, token);
            //WebUtils.setCookie(WebUtils.getHttpServletResponse(), jjwtConfigure.getDomain(), jjwtConfigure.getCookieName(), token, jjwtConfigure.getCookieMaxAge());
            return token;
        } catch (Exception e) {
            throw new RuntimeException("生成签名失败");
        }
    }

    /**
     * 验证用户信息
     *
     * @param token 授权密钥
     * @return 解密信息体
     */
    public Claims jwtParser(String token) {
        Jws jws = JWTUtils.jwtParser(token, jjwtConfigure.getPublicKey());
        return jws.getBody();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy