面試過不少Java開發,能把權限這塊說的清楚的實在是很少,不少人由於公司項目職責問題,很難學到這類相關的流程和技術,本文梳理一個簡單的場景,實現一個基於jwt先後端分離的權限框架。前端
image-20200709160301317vue
image-20200709160427929java
本文技術選型爲SpringBoot+JWT+Redis, 實現上圖的登陸流程和鑑權流程,並提供完整項目代碼。react
「本項目已實現以下功能」:git
使用Docker一行命令構建啓動Redis,命令以下github
docker run -itd --name redis-test -p 6379:6379 redis --requirepass "123456redis"
指定端口:6379
web
指定密碼:123456redis
面試
客戶端鏈接測試,問題不大~redis
建立SpringBoot項目並引入JWT依賴spring
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
其實主要是引了這個包,其餘的就不貼出來了。主要有redis以及json相關的,完整代碼都在項目能夠本身看
UserController
@PostMapping("/login")
public UserVO login(@RequestBody LoginDTO loginDTO) {
return userService.login(loginDTO);
}
UserService
用戶信息就模擬的了,都看的懂。登陸成功後根據uid生產jwt,而後緩存到redis,封裝結果給到前端
package com.lzp.auth.service;
@Service
public class UserService {
@Value("${server.session.timeout:3000}")
private Long timeout;
@Autowired
private RedisUtils redisUtils;
final static String USER_NAME = "admin";
//密碼 演示用就不作加密處理了
final static String PWD = "admin";
public UserVO login(LoginDTO loginDTO){
User user = getByName(loginDTO.getUserName());
//用戶信息校驗和查詢
if (user == null){
throw new ServiceException(ResultCodeEnum.LOGIN_FAIL);
}
//密碼校驗
if(!PWD.equals(loginDTO.getPwd())){
throw new ServiceException(ResultCodeEnum.LOGIN_FAIL);
}
//緩存用戶信息並設置過時時間
UserVO userVO = new UserVO();
userVO.setName(user.getName());
userVO.setUid(user.getUid());
userVO.setToken(JWTUtils.generate(user.getUid()));
//信息入庫redis
redisUtils.set(RedisKeyEnum.OAUTH_APP_TOKEN.keyBuilder(userVO.getUid()), JSONObject.toJSONString(userVO), timeout);
return userVO;
}
/**
* 經過用戶名獲取用戶
* @param name
* @return
*/
public User getByName(String name){
User user = null;
if(USER_NAME.equals(name)){
user = new User("1","張三","Aa123456");
}
return user;
}
}
LoginInterceptor
package com.lzp.auth.config;
import com.lzp.auth.exception.ServiceException;
import com.lzp.auth.utils.JWTUtils;
import com.lzp.auth.utils.ResultCodeEnum;
import com.lzp.auth.utils.SessionContext;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Autowired
StringRedisTemplate redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
String requestURI = request.getRequestURI().replaceAll("/+", "/");
log.info("requestURI:{}",requestURI);
if (StringUtils.isEmpty(token)) {
throw new ServiceException(ResultCodeEnum.AUTH_FAIL);
}
Claims claim = JWTUtils.getClaim(token);
if(claim == null){
throw new ServiceException(ResultCodeEnum.AUTH_FAIL);
}
String uid = null;
try {
uid = JWTUtils.getOpenId(token);
} catch (Exception e) {
throw new ServiceException(ResultCodeEnum.AUTH_FAIL);
}
//用戶id放到上下文 能夠當前請求進行傳遞
request.setAttribute(SessionContext.USER_ID_KEY, uid);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
package com.lzp.auth.config;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.util.pattern.PathPatternParser;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
private ApplicationContext applicationContext;
public WebMvcConfig() {
super();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
@Bean
LoginInterceptor loginInterceptor() {
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//攔截規則:除了login,其餘都攔截判斷
registry.addInterceptor(loginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/user/login");
super.addInterceptors(registry);
}
}
「postMan調試」
模擬成功和失敗場景
成功如上圖,返回用戶信息和Token
測試非白名單接口失敗如上圖
「使用token再來訪問當前接口」
至此本項目就完美結束了哦完美~
https://github.com/pengziliu/GitHub-code-practice
這個倉庫除了這個還有更多精彩代碼喲
已擼完部分開源輪子,更多精彩正在路上
模塊 | 所屬開源項目 | 項目介紹 |
---|---|---|
springboot_api_encryption |
rsa-encrypt-body-spring-boot | Spring Boot接口加密,能夠對返回值、參數值經過註解的方式自動加解密 。 |
simpleimage-demo |
simpleimage | 圖片處理工具類,具備加水印、壓縮、裁切等功能 |
xxl-job-demo |
xxl-job | 分佈式定時任務使用場景 |
xxl-sso-demo |
xxl-sso | 單點登陸功能 |
vuepress-demo |
vuepress | 創建本身的知識檔案庫 |
xxl-conf-demo |
xxl-conf | 分佈式配置中心 |
Shardingsphere-demo |
Shardingsphere | 分庫分表 |
easyexcel-demo |
easyexcel | excel操做工具類 |
kaptcha-demo | kaptcha | 先後端分離驗證碼方案 |
https://mp.weixin.qq.com/s/aWfEWH_3qy-YLa0IUA1FeA