1. 程式人生 > >Json Web Token與spring boot-actuator結合

Json Web Token與spring boot-actuator結合

使用者身份認證一般有5種方式

1.HTTP Basic authentication
在傳送請求時在HTTP頭中加入authentication欄位,將用Base64編碼的使用者名稱和密碼作為值,每次傳送請求的時候都要傳送使用者名稱和密碼,實現比較簡單。
2.Cookies
向後臺傳送使用者名稱和密碼,在使用者名稱和密碼通過驗證後,儲存返回的Cookie作為使用者已經登入的憑證,每次請求時附帶這個Cookie。
3.Signatures
使用者拿到伺服器給的私鑰,在傳送請求前,將整個請求使用私鑰來加密,傳送的將是一串加密資訊,此方式只適用於API。
4.One-Time Passwords
一次一密,每次登入時使用不同的密碼,一般由服務端通過郵件將密碼發給使用者,這種登入方式比較繁瑣。
5.JSON Web Token
使用者傳送按照約定,向服務端傳送Header、Payload和Signature,幷包含認證資訊(密碼),驗證通過後服務端返回一個token,之後使用者使用該token作為登入憑證,適合於移動端和api。

什麼是Json Web Token?
JSON Web Token(JWT)是一個非常輕巧的規範。這個規範允許我們使用JWT在使用者和伺服器之間傳遞安全可靠的資訊。
本文將介紹jwt的具體使用過程,本文將介紹基於jwt的專案最後打成jar,供其他專案引用的過程。
首先pom檔案的介紹,如下:

<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version
>
0.7.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency
>
<groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.9</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.1_3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.10.RELEASE</version> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.10.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot</artifactId> <version>1.5.6.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.10.RELEASE</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.31</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-actuator</artifactId> <version>1.5.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <version>1.5.6.RELEASE</version> </dependency>
編寫一個自定義的註解類
/**
 * Created by shieh on 2017/10/25.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessVerify {

}

通過aop實現該註解類

@Around("@annotation(com.mob.annotation.AccessVerify)")
public Object doAccessCheck(ProceedingJoinPoint pjp) throws Throwable{

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("Authorization");

        if (StringUtils.isEmpty(token))
            return new ExceptionEntity(401, "Authorization is empty" +
                    ServerName.message(request.getServerName(), request.getServerPort())).toString();
        // parse the token.
        try {
            String user = Jwts.parser()
                    .setSigningKey("eyJhbGciOiJIUzUxMiJ9")
                    .parseClaimsJws(token.replace("jwt ", ""))
                    .getBody()
                    .getSubject();
            if (StringUtils.isEmpty(user)) {
                return new ExceptionEntity(401, "Authorization is empty" +
                        ServerName.message(request.getServerName(), request.getServerPort())).toString();
            }
            String[] strings = user.split("\\|");
            if (strings.length < 1 || StringUtils.isEmpty(strings[0]))
                return new ExceptionEntity(401, "Authorization is empty" +
                        ServerName.message(request.getServerName(), request.getServerPort())).toString();
            List<String> permissionList = new LinkedList<String>();
            for (int i = 1;i < strings.length; i++) {
                permissionList.add(strings[i]);
            }
            if (!permissionList.contains(request.getRequestURI()))
                return new ExceptionEntity(403, "you don't have this authority of " + request.getRequestURI()).toString();
            return pjp.proceed();
        } catch (MalformedJwtException e) {
            return new ExceptionEntity(402,"Authorization is wrong" +
                    ServerName.message(request.getServerName(), request.getServerPort())).toString();
        } catch (ExpiredJwtException e) {
            return new ExceptionEntity(403,"Authorization is expired" +
                    ServerName.message(request.getServerName(), request.getServerPort())).toString();
        }
    }

該類的實現就是對客戶端過來的請求進行解析,判斷使用者的請求是否合法。如果客戶端的請求中header沒有Authorization值則驗證不通過,否則將進一步解析jwt,該jwt中包含使用者的資訊以及具有的許可權的資訊。
以上就是基於jwt對客戶端的請求進行鑑權。
接下來可能你會有疑問,jwt是如何生成的呢?這是接下來將要描述的。
以下就是jwt的具體生成程式碼

/**
 * Created by shieh on 2017/10/26.
 */
public class TokenEndpoint extends AbstractEndpoint{

    UserDao userDao;

    public TokenEndpoint(UserDao userDao){
        super(ServerName.SERVER_NAME, false);
        this.userDao = userDao;
    }

    public TokenDetail invoke() {
        TokenDetail tokenDetail = new TokenDetail();
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String account = request.getParameter("account");
            if (StringUtils.isEmpty(account)) throw new AccountNullPointException("account is empty");
            List<UserPermission> urlList = userDao.queryUrlByAccount(account);
            StringBuffer sb = new StringBuffer();
            if (!CollectionUtils.isEmpty(urlList)) {
                for (UserPermission userPermission : urlList) {
                    sb.append("|");
                    sb.append(userPermission.getUrl());
                }
            }
            Date expiredDate = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
            String token = Jwts.builder()
                    .setSubject(account + sb.toString())
                    .setExpiration(expiredDate)
                    .signWith(SignatureAlgorithm.HS512, "eyJhbGciOiJIUzUxMiJ9")
                    .compact();
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("account", account);
            detail.put("expiration", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(expiredDate));
            detail.put("authorization", "jwt " + token);
            tokenDetail.setDetails(detail);
            tokenDetail.setStatus(new Status(200, "success"));
        } catch (AccountNullPointException e) {
            tokenDetail.setStatus(new Status(100, "account is empty"));
        } catch (Exception e) {
            tokenDetail.setStatus(new Status(100, e.getMessage()));
        }
        return tokenDetail;
    }

通過依賴注入的方式注入到容器中,以下是具體的程式碼實現

/**
 * Created by shieh on 2017/10/26.
 */
@Configuration
public class EndPointConfig {
    @Autowired
    UserDao userDao;

    @Bean
    @ConditionalOnMissingBean
    public TokenEndpoint EndPointConfig() {
        return new TokenEndpoint(userDao);
    }
}
/**
 * Created by shieh on 2017/10/27.
 */
public class ServerName {
    public static final String SERVER_NAME = "generateToken";

    public static String message(String server, int port) {
        return " ,please visit http://" + server + ":" + port + "/" + SERVER_NAME;
    }
}

通過actuator在jar包中設定endpoint,從而實現,專案引入該jar後將自動對外提供相對應的endpoint服務,從而實現jwt的生成。只需訪問http://ip:port/generateToken即可實現jwt的生成。
以上就是對於jwt+actuator的簡單應用。如有不妥之處,望大神指點一二,小弟在此感激不盡。