1、概述
网站系统出于安全性的考虑会对用户进行两个层面的校验:身份认证以及权限认证。这两个认证可以保证只有特定的用户才能访问特定的数据的需求。
本文先实现一个基于jwt+拦截器+redis+注解实现的简单登录验证功能。
2、设计思路
- jwt用于签发token。
- 拦截器用于拦截不合法的请求(未登录的请求)。
- redis用于存放签发好的token并设置过期时间,以及在注销的时候清空token。
- 注解用于设置哪些接口需要登录验证。
3、实现代码
代码地址:Atlantide/TestAopAuth
LoginRequired.java
package com.mytest.annotation;
import java.lang.annotation.*;
/**
* @author Wulc
* @date 2024/4/7 17:55
* @description
*/
//可用在方法名上
@Target({ElementType.METHOD})
//运行时有效
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginRequired {
}
RedisConfig.java
package com.mytest.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.time.Duration;
/**
* @author Wulc
* @date 2024/4/8 11:39
* @description
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisTemplate redisTemplate) {
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setStringSerializer(stringSerializer);
redisTemplate.setValueSerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(stringSerializer);
return redisTemplate;
}
}
WebConfiguration.java
package com.mytest.config;
import com.mytest.interceptor.AuthorityInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.*;
import java.util.List;
/**
* @author Wulc
* @date 2024/4/7 17:39
* @description
*/
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer pathMatchConfigurer) {
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer) {
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer asyncSupportConfigurer) {
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer defaultServletHandlerConfigurer) {
}
@Override
public void addFormatters(FormatterRegistry formatterRegistry) {
}
// @Bean
// TestInterceptor getTestInterceptor() {
// return new TestInterceptor();
// }
@Bean
AuthorityInterceptor getAuthorityInterceptor() {
return new AuthorityInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
//interceptorRegistry.addInterceptor(getTestInterceptor()).addPathPatterns("/**");
//interceptorRegistry.addInterceptor(getTestInterceptor()).addPathPatterns("/test1");
interceptorRegistry.addInterceptor(getAuthorityInterceptor()).addPathPatterns("/**");
//this.addInterceptors(interceptorRegistry);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {
}
@Override
public void addCorsMappings(CorsRegistry corsRegistry) {
}
@Override
public void addViewControllers(ViewControllerRegistry viewControllerRegistry) {
}
@Override
public void configureViewResolvers(ViewResolverRegistry viewResolverRegistry) {
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {
}
@Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> list) {
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> list) {
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> list) {
}
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {
}
@Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {
}
@Override
public Validator getValidator() {
return null;
}
@Override
public MessageCodesResolver getMessageCodesResolver() {
return null;
}
}
LoginController.java
package com.mytest.controller;
import com.mytest.jwtentity.JWTResponseData;
import com.mytest.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author Wulc
* @date 2024/4/8 10:50
* @description
*/
@RestController
@RequestMapping("/jwt")
public class LoginController {
@Autowired
private LoginService loginService;
@GetMapping("/login")
@ResponseBody
public JWTResponseData login(@RequestParam("username") String username, @RequestParam("password") String password) {
return loginService.login(username, password);
}
@GetMapping("/loginout")
@ResponseBody
@LoginRequired
public JWTResponseData loginout(@RequestParam("username") String username) {
return loginService.loginout(username);
}
}
OperationController.java
package com.mytest.controller;
import com.mytest.annotation.LoginRequired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Wulc
* @date 2024/4/8 11:06
* @description
*/
@RestController
@RequestMapping("/operate")
public class OperationController {
@GetMapping("/operate1")
@LoginRequired
public String operate1() {
return "操作1";
}
}
AuthorityInterceptor.java
package com.mytest.interceptor;
import com.alibaba.fastjson2.JSONObject;
import com.mytest.annotation.LoginRequired;
import com.mytest.jwtentity.JWTResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
/**
* @author Wulc
* @date 2024/4/7 17:56
* @description
*/
public class AuthorityInterceptor extends HandlerInterceptorAdapter {
@Autowired
@Qualifier("redisTemplate")
private RedisTemplate<String, Object> redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getServletPath();
// 如果不是映射到方法直接通过
if (!(handler instanceof HandlerMethod)) {
return true;
}
// ①:START 方法注解级拦截器
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
// 判断接口是否需要登录
LoginRequired methodmethodAnnotation = method.getAnnotation(LoginRequired.class);
// 有 @LoginRequired 注解,需要认证
if (methodmethodAnnotation != null) {
// 这写你拦截需要干的事儿,比如取缓存,SESSION,权限判断等
System.out.println("触发了注解拦截器:" + path);
String username = request.getParameter("username");
String bearToken = request.getHeader("Authorization");
String token = bearToken.substring(7, bearToken.length());
String loginToken = "";
if (redisTemplate.opsForValue().get(username) == null) {
System.out.println("用户未登录");
returnJson(response, JSONObject.toJSONString(new JWTResponseData(401, "未登录", "用户未登录", "")));
return false;
}
loginToken = redisTemplate.opsForValue().get(username).toString();
if (token.equals(loginToken)) {
return true;
} else {
System.out.println("用户未登录");
returnJson(response, JSONObject.toJSONString(new JWTResponseData(401, "未登录", "用户未登录", "")));
return false;
}
}
return true;
}
private void returnJson(HttpServletResponse response, String json) throws Exception {
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
try {
writer = response.getWriter();
writer.print(json);
} catch (IOException e) {
//logger.error("response error", e);
} finally {
if (writer != null) {
writer.close();
}
}
}
}
JWTResponseData.java
package com.mytest.jwtentity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 发送给客户端的数据对象。
* 商业开发中,一般除特殊请求外,大多数的响应数据都是一个统一类型的数据。
* 统一数据有统一的处理方式。便于开发和维护。
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class JWTResponseData {
//返回码,类似HTTP响应码。如:200成功,500服务器错误,404资源不存在等。
private Integer code;
//业务数据
private Object data;
//返回描述
private String msg;
//身份标识, JWT生成的令牌。
private String token;
}
LoginServiceImpl.java
package com.mytest.service.impl;
import com.mytest.jwtentity.JWTResponseData;
import com.mytest.service.LoginService;
import com.mytest.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* @author Wulc
* @date 2024/4/8 10:58
* @description
*/
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
@Qualifier("redisTemplate")
private RedisTemplate<String, Object> redisTemplate;
@Override
public JWTResponseData login(String username, String password) {
JWTResponseData responseData = null;
if (username.equals("wulc") && password.equals("123")) {
String jwtToken = JWTUtils.createJWT(UUID.randomUUID().toString(), "sxt-test-jwt",
username, 1 * 60 * 1000);//设置token过期时间
redisTemplate.opsForValue().set(username, jwtToken, 60, TimeUnit.SECONDS);
responseData = new JWTResponseData();
responseData.setCode(200);
responseData.setData(null);
responseData.setMsg("登录成功");
responseData.setToken(jwtToken);
} else {
responseData = new JWTResponseData();
responseData.setCode(500);
responseData.setData(null);
responseData.setMsg("登录失败");
responseData.setToken(null);
}
return responseData;
}
@Override
public JWTResponseData loginout(String username) {
redisTemplate.opsForValue().set(username, "");
return new JWTResponseData(200, username, "退出登录", "");
}
}
LoginService.java
package com.mytest.service;
import com.mytest.jwtentity.JWTResponseData;
/**
* @author Wulc
* @date 2024/4/8 10:58
* @description
*/
public interface LoginService {
JWTResponseData login(String username, String password);
JWTResponseData loginout(String username);
}
JWTUtils.java
package com.mytest.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
/**
* @author Wulc
* @date 2024/4/8 10:43
* @description
*/
public class JWTUtils {
private static final String JWT_SECERT = "test_jwt_secert";
private static final ObjectMapper MAPPER = new ObjectMapper();
//Token过期
public static final int JWT_ERRCODE_EXPIRE = 1005;
//验证不通过
public static final int JWT_ERRCODE_FAIL = 1006;
public static SecretKey generalKey() {
try {
byte[] encodedKey = JWT_SECERT.getBytes("UTF-8");
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 签发JWT,创建token的方法。
*
* @param id jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。
* @param iss jwt签发者
* @param subject jwt所面向的用户。payload中记录的public claims。当前环境中就是用户的登录名。
* @param ttlMillis 有效期,单位毫秒
* @return token, token是一次性的。是为一个用户的有效登录周期准备的一个token。用户退出或超时,token失效。
* @throws Exception
*/
public static String createJWT(String id, String iss, String subject, long ttlMillis) {
//加密算法
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
//当前时间。
long nowMillis = System.currentTimeMillis();
//当前时间的日期对象。
Date now = new Date(nowMillis);
SecretKey secretKey = generalKey();
//创建JWT的构建器。 就是使用指定的信息和加密算法,生成Token的工具。
JwtBuilder builder = Jwts.builder()
//设置身份标志。就是一个客户端的唯一标记。 如:可以使用用户的主键,客户端的IP,服务器生成的随机数据。
.setId(id)
.setIssuer(iss)
.setSubject(subject)
//token生成的时间(签发时间)。
.setIssuedAt(now)
//设定密匙和算法
.signWith(signatureAlgorithm, secretKey);
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
// token的失效时间。
Date expDate = new Date(expMillis);
builder.setExpiration(expDate);
}
//生成token
return builder.compact();
}
}
ApplicationStarter.java
package com.mytest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author Wulc
* @date 2024/4/7 13:56
* @description
*/
@SpringBootApplication
public class ApplicationStarter {
public static void main(String[] args) {
SpringApplication.run(ApplicationStarter.class, args);
}
}
application.yml
server:
port: 8080
spring:
redis:
port: 6379
database: 0
host: 127.0.0.1
password:
pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>TestAopAuth</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- <springframework.version>1.5.4.RELEASE</springframework.version>-->
<!-- <springframework.version1>2.2.1.RELEASE</springframework.version1>-->
<springframework.version>2.2.1.RELEASE</springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>compile</scope>
</dependency>
<!-- JWT核心依赖 -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
<!-- java开发JWT的依赖jar包。 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!-- <version>2.7.8</version>-->
<version>${springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.47</version>
</dependency>
<!-- spring2.X集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency>
</dependencies>
</project>
4、演示
程序启动后,对于未登录或者登录信息过期的用户如果想访问/operate/operate1接口的话,会因为token校验不通过而被拦截器阻拦。
访问/jwt/login实现用户登录,并获取token。
登录获取到token后,用这个最新的token,访问/operate/operate1接口,则此时token校验通过,拦截器放行,进入了/operate/operate1接口。
访问/jwt/loginout可以实现退出登录,退出登录的前提是必须已经登录。会清空redis里面的token。
5、总结
鉴权系统是一个非常复杂的系统,登录验证只是第一步,也是最简单的一步。因为年前公司有组织过关于鉴权系统的培训,因此就顺便学习整理一下鉴权系统的设计。这里先简单实现一个登录验证的demo。后续还有权限结构的划分与设计,以及鉴权系统的高可用性保证。等后面有空了再写。
6、参考资料
SSO单点登录 - 多系统,单一位置登录,实现多系统同时登录_哔哩哔哩_bilibili
https到底把什么加密了? - 知乎
Windows下如何查看某个端口被谁占用 | 菜鸟教程
Spring自定义注解的使用(实现切面aspect)_spring aspect-CSDN博客
Spring AOP切入点@Pointcut -- execution表达式_pointcut execution-CSDN博客
Spring AOP代码实现:实例演示与注解全解_springaop代码示例-CSDN博客
Spring AOP - 注解方式使用介绍(长文详解) - 掘金
springboot 配置拦截器超详细介绍_springboot设置拦截器-CSDN博客