上篇寫到對JWT的理解,這篇寫一個小的demo來實踐下
簡介
本次的demo是基於SpringCloud微服務來實現的
- 用戶服務
- 授權中心
用戶服務
寫了一個接口,實現用戶名和密碼來查詢用戶的功能,在此展現controller層
UserController
package com.wuhen.jwt.user.controller;
import com.wuhen.jwt.user.entity.User;
import com.wuhen.jwt.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: 王筱哲
* @Date: 2019/6/13
* @Time: 13:34
*/
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("query")
public ResponseEntity<User> queryByUsernameAndPassword(
@RequestParam("username")String username,
@RequestParam("password")String password
){
return ResponseEntity.ok(userService.queryByUsernameAndPassword(username,password));
}
}
授權中心
主要是token的生成以及存儲到cookie的功能
token的生成是利用JWT+RSA非對稱加密來實現的
寫了一個Common(公共類)來實現token的生成(具體可以參考下源碼)
授權服務的實現
業務代碼
AuthController層
package com.wuhen.jwt.auth.controller;
import com.wuhen.jwt.auth.config.JwtProperties;
import com.wuhen.jwt.auth.entity.UserInfo;
import com.wuhen.jwt.auth.service.AuthService;
import com.wuhen.jwt.common.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Author: 王筱哲
* @Date: 2019/6/13
* @Time: 17:32
*/
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
@Autowired
private AuthService authService;
@Autowired
private JwtProperties properties;
@PostMapping("accredit")
public ResponseEntity<Void> authentication(
@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletRequest request,
HttpServletResponse response
) {
//1.登錄校驗
String token = this.authService.authentication(username, password);
//2.將token寫入cookie,並指定httpOnly為true,防止通過js獲取和修改
CookieUtils.setCookie(request, response, properties.getCookieName(), token, properties.getCookieMaxAge(), true);
return ResponseEntity.ok().build();
}
/**
* 用戶驗證
*
* @param token
* @return
*/
@GetMapping("verify")
public ResponseEntity<UserInfo> verifyUser(@CookieValue("j-cookie") String token,
HttpServletRequest request,
HttpServletResponse response) {
String token1 = authService.verifyUser(token).get(2).toString();
//3.更新Cookie中的token
CookieUtils.setCookie(request, response, this.properties.getCookieName(), token1, this.properties.getCookieMaxAge());
return ResponseEntity.ok((UserInfo) authService.verifyUser(token).get(1));
}
}
邏輯實現
- 通過用戶名和密碼來授權中心獲得token
- 將token保存在cookie中,返回到客戶端
- 下次請求攜帶cookie發送到服務器,服務器解析出用戶信息
在授權中心調取用戶查詢服務是通過feignClient實現的,兩個微服務之間的相互調用