本文使用SpringBoot結合Redis進行簡單的token鑑權。html
剛剛換了公司,因此最近有些忙碌,因此一直沒有什麼產出,最近朋友問我登陸相關的,因此這裏先寫一篇簡單使用token鑑權的文章,後續會補充一些高階的,因此若是感受這篇文章簡單,能夠直接繞行,言歸正傳,如今通常系統都進行了先後端分離,爲了保證必定的安全性,如今很流行使用token來進行會話的驗證,通常流程以下:前端
固然,如上的說法只是簡單的實現,實質上還有不少須要優化的地方。java
本文工程結構以下:git
其中:web
本文使用redis存儲token信息,用戶只是建立了一個固定的用戶,在pom中加入相關依賴,完整內容以下:redis
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dalaoyang</groupId>
<artifactId>springboot2_redis_login</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot2_redis_login</name>
<description>springboot2_redis_login</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
複製代碼
配置文件中配置對應的redis信息,以下:spring
server.port=8888
##redis配置
spring.redis.host=localhost
spring.redis.port=6379
複製代碼
接下來編寫redis相關操做,本文示例只須要使用到get,set和delete操做,都是簡單的使用RedisTemplate,RedisService內容以下:數據庫
package com.dalaoyang.service;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class RedisService {
@Resource
private RedisTemplate<String,Object> redisTemplate;
public void set(String key, Object value) {
//更改在redis裏面查看key編碼問題
RedisSerializer redisSerializer =new StringRedisSerializer();
redisTemplate.setKeySerializer(redisSerializer);
ValueOperations<String,Object> vo = redisTemplate.opsForValue();
vo.set(key, value);
}
public Object get(String key) {
ValueOperations<String,Object> vo = redisTemplate.opsForValue();
return vo.get(key);
}
public Boolean delete(String key) {
return redisTemplate.delete(key);
}
}
複製代碼
LoginService只是進行登陸和註銷操做,其中登陸就是先判斷用戶名密碼是否正確,若是正確,那麼會生成一個字符串作爲token(本文中使用uuid),而且作爲返回值,密碼錯誤則提示錯誤。註銷實質就是刪除redis中token的緩存,完整內容以下:apache
package com.dalaoyang.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.UUID;
@Service
public class LoginService {
@Autowired
private RedisService redisService;
public String login(String username, String password) {
if (Objects.equals("dalaoyang", username) &&
Objects.equals("123", password)) {
String token = UUID.randomUUID().toString();
redisService.set(token, username);
return "用戶:" + username + "登陸成功,token是:" + token;
} else {
return "用戶名或密碼錯誤,登陸失敗!";
}
}
public String logout(HttpServletRequest request) {
String token = request.getHeader("token");
Boolean delete = redisService.delete(token);
if (!delete) {
return "註銷失敗,請檢查是否登陸!";
}
return "註銷成功!";
}
}
複製代碼
LoginController內容很簡單,只是對LoginService的簡單調用,以下:後端
package com.dalaoyang.controller;
import com.dalaoyang.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/login")
public class LoginController {
@Autowired
private LoginService loginService;
@GetMapping({"/", ""})
public String login(String username, String password) {
return loginService.login(username, password);
}
@GetMapping("/logout")
public String logout(HttpServletRequest request) {
return loginService.logout(request);
}
}
複製代碼
TestController中只是寫了一個簡單返回字符串的接口,以下:
package com.dalaoyang.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping({"/", ""})
public String dosomething() {
return "dosomething";
}
}
複製代碼
接下來是攔截器,攔截器中須要取出header中的token,而後去redis中進行判斷,若是存在,則容許操做,則返回提示信息,內容以下:
package com.dalaoyang.interceptor;
import com.dalaoyang.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
public class AuthInterceptor implements HandlerInterceptor {
@Autowired
private RedisService redisService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String token = request.getHeader("token");
if (StringUtils.isEmpty(token)) {
response.getWriter().print("用戶未登陸,請登陸後操做!");
return false;
}
Object loginStatus = redisService.get(token);
if( Objects.isNull(loginStatus)){
response.getWriter().print("token錯誤,請查看!");
return false;
}
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 {
}
}
複製代碼
最後配置一下攔截器,因爲攔截器中使用了RedisService,因此這裏須要使用以下方式注入攔截器,內容以下:
package com.dalaoyang.config;
import com.dalaoyang.interceptor.AuthInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class AuthConfig implements WebMvcConfigurer {
@Bean
public AuthInterceptor initAuthInterceptor(){
return new AuthInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(initAuthInterceptor()).addPathPatterns("/test/**").excludePathPatterns("/login/**");
}
}
複製代碼
內容到這裏就已經完成了。
可使用以下步驟進行簡單測試:
用戶未登陸,請登陸後操做!
用戶名或密碼錯誤,登陸失敗!
用戶:dalaoyang登陸成功,token是:02fdd2bd-1669-48b9-b51b-1e724f97688f
dosomething
本文只是簡單對token使用作了一個樣例,並不適用於生產環境,有不少地方是能夠擴展的,好比: