Compare commits
5
Commits
5d7be9d883
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f3f2f987c | ||
|
|
d9f709de3d | ||
|
|
94d72c5f46 | ||
|
|
55143e9d8d | ||
|
|
49c4604f5e |
@@ -31,9 +31,61 @@
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>2.3.1</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!--mysql 数据库驱动依赖-->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- mybatis plus 依赖-->
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
<version>3.5.7</version>
|
||||
</dependency>
|
||||
|
||||
<!--hutool工具包-->
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-all</artifactId>
|
||||
<version>5.8.11</version>
|
||||
</dependency>
|
||||
|
||||
<!-- spring security-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
<version>2.5.5</version>
|
||||
</dependency>
|
||||
<!-- jwt-->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
<version>0.9.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.xiaoymin</groupId>
|
||||
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
|
||||
<version>4.5.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>io.swagger</groupId>-->
|
||||
<!-- <artifactId>swagger-annotations</artifactId>-->
|
||||
<!-- <version>1.6.6</version>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.springframework.boot</groupId>-->
|
||||
<!-- <artifactId>spring-boot-starter-jdbc</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
@@ -49,6 +101,11 @@
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.annotation</groupId>
|
||||
<artifactId>jakarta.annotation-api</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package com.gw.test;
|
||||
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@MapperScan("com.gw.test.mapper")
|
||||
public class TestApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
// 设置允许跨域请求的域名
|
||||
.allowedOriginPatterns("*")
|
||||
// 是否允许cookie
|
||||
.allowCredentials(true)
|
||||
// 设置允许的请求方式
|
||||
.allowedMethods("GET", "POST", "DELETE", "PUT")
|
||||
// 设置允许的header属性
|
||||
.allowedHeaders("*")
|
||||
// 跨域允许时间
|
||||
.maxAge(3600);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* SpringSecurity白名单资源路径配置
|
||||
* Created by macro on 2018/11/5.
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "secure.ignored")
|
||||
public class IgnoreUrlsConfig {
|
||||
|
||||
private List<String> urls = new ArrayList<>();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
|
||||
@Configuration
|
||||
public class OpenApiConfig {
|
||||
@Bean
|
||||
public OpenAPI api() {
|
||||
return new OpenAPI().info(new Info().title("Test").version("v1.0.0").description( "接口测试"))
|
||||
.addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION))
|
||||
.components(new Components().addSecuritySchemes(HttpHeaders.AUTHORIZATION,new SecurityScheme()
|
||||
.name(HttpHeaders.AUTHORIZATION).type(SecurityScheme.Type.HTTP).scheme("Bearer ")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import com.gw.test.filters.*;
|
||||
import com.gw.test.utils.JWTUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Slf4j
|
||||
@Configuration
|
||||
public class SecurityBeanConfig {
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
// @Bean
|
||||
// public IgnoreUrlsConfig ignoreUrlsConfig() {
|
||||
// return new IgnoreUrlsConfig();
|
||||
// }
|
||||
|
||||
@Bean
|
||||
public JWTUtil jWTUtil() {
|
||||
return new JWTUtil();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
|
||||
return new RestfulAccessDeniedHandler();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
|
||||
return new RestAuthenticationEntryPoint();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(UserDetailsService userDetailsService, JWTUtil jwtTokenUtil){
|
||||
return new JwtAuthenticationTokenFilter(userDetailsService,jwtTokenUtil);
|
||||
}
|
||||
|
||||
// @ConditionalOnBean(name = "dynamicSecurityService")
|
||||
@Bean
|
||||
@Autowired
|
||||
public DynamicAccessDecisionManager dynamicAccessDecisionManager() {
|
||||
return new DynamicAccessDecisionManager();
|
||||
}
|
||||
|
||||
// @ConditionalOnBean(name = "dynamicSecurityService")
|
||||
@Bean
|
||||
// @Lazy
|
||||
public DynamicSecurityMetadataSource dynamicSecurityMetadataSource(DynamicSecurityService dynamicSecurityService) {
|
||||
// log.error("=============={}",dynamicSecurityService.loadDataSource());
|
||||
return new DynamicSecurityMetadataSource(dynamicSecurityService);
|
||||
}
|
||||
|
||||
// @ConditionalOnBean(name = "dynamicSecurityService")
|
||||
@Bean
|
||||
// @Lazy
|
||||
public DynamicSecurityFilter dynamicSecurityFilter(DynamicSecurityMetadataSource dynamicSecurityMetadataSource,IgnoreUrlsConfig ignoreUrlsConfig){
|
||||
// log.error("======动态权限注解支持启动========{}",dynamicSecurityMetadataSource);
|
||||
return new DynamicSecurityFilter(dynamicSecurityMetadataSource,ignoreUrlsConfig);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import com.gw.test.filters.*;
|
||||
import com.gw.test.utils.JWTUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@RequiredArgsConstructor
|
||||
public class SecurityConfig {
|
||||
// private final JWTUtil jwtUtil;
|
||||
|
||||
private final IgnoreUrlsConfig ignoreUrlsConfig;
|
||||
|
||||
private final RestfulAccessDeniedHandler restfulAccessDeniedHandler;
|
||||
|
||||
private final RestAuthenticationEntryPoint restAuthenticationEntryPoint;
|
||||
|
||||
private final JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
|
||||
|
||||
@Autowired(required = false)
|
||||
private DynamicSecurityService dynamicSecurityService;
|
||||
|
||||
@Autowired(required = false)
|
||||
private DynamicSecurityFilter dynamicSecurityFilter;
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
|
||||
|
||||
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.authorizeRequests();
|
||||
//不需要保护的资源路径允许访问
|
||||
for (String url : ignoreUrlsConfig.getUrls()) {
|
||||
log.error("[{}] [{}]", "白名单路径", url);
|
||||
registry.requestMatchers(url).permitAll();
|
||||
}
|
||||
//允许跨域请求的OPTIONS请求
|
||||
registry.requestMatchers(HttpMethod.OPTIONS)
|
||||
.permitAll();
|
||||
|
||||
// 任何请求需要身份认证
|
||||
registry.anyRequest()
|
||||
.authenticated()
|
||||
// 关闭跨站请求防护及不使用session
|
||||
.and()
|
||||
.exceptionHandling(exception -> exception
|
||||
.accessDeniedHandler(restfulAccessDeniedHandler)
|
||||
.authenticationEntryPoint(restAuthenticationEntryPoint))
|
||||
// 自定义JWT认证过滤器
|
||||
.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(dynamicSecurityFilter, FilterSecurityInterceptor.class);
|
||||
return httpSecurity.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import com.gw.test.filters.DynamicSecurityService;
|
||||
import com.gw.test.service.IGuoWeiService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
import org.springframework.security.access.SecurityConfig;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 后台用户安全配置
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Configuration
|
||||
public class UserSecurityConfig {
|
||||
|
||||
private final IGuoWeiService service;
|
||||
|
||||
// private final IApiService apiService;
|
||||
|
||||
@Bean
|
||||
public UserDetailsService userDetailsService() {
|
||||
//获取登录用户信息
|
||||
return service::loadUserByUsername;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DynamicSecurityService dynamicSecurityService() {
|
||||
log.error("========动态权限配置加载========");
|
||||
return () -> {
|
||||
Map<String, ConfigAttribute> map = new ConcurrentHashMap<>();
|
||||
Map<String,String> apis = new HashMap<>();
|
||||
apis.put("/guowei/list","查询所有");
|
||||
apis.put("/guowei/update","修改");
|
||||
apis.put("/guowei/delete","删除");
|
||||
apis.put("/guowei/add","添加");
|
||||
for (String api : apis.keySet()) {
|
||||
// map.put(api,new SecurityConfig(apis.get(api)));
|
||||
map.put(api,new SecurityConfig(api));
|
||||
}
|
||||
return map;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.gw.test.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
|
||||
//@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
@Autowired
|
||||
// LoginInterceptor loginInterceptor;
|
||||
/**
|
||||
* 跨域配置
|
||||
*/
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")//
|
||||
.allowedOriginPatterns("*")//
|
||||
.allowedMethods("POST", "GET", "OPTIONS")//
|
||||
.maxAge(3600)//
|
||||
.allowCredentials(true);//
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
|
||||
// 对所有访问路径,都通过MyInterceptor类型的拦截器进行拦截
|
||||
// registry.addInterceptor(loginInterceptor)//
|
||||
// .addPathPatterns("/**")//
|
||||
// // 放行登陆接口
|
||||
// .excludePathPatterns("/**/login/**")//
|
||||
// .excludePathPatterns("/**/ip/**")
|
||||
// // swagger需要放行的资源
|
||||
// .excludePathPatterns("/favicon.ico")//
|
||||
// .excludePathPatterns("/error")//
|
||||
// .excludePathPatterns("/doc.html")//
|
||||
// .excludePathPatterns("/webjars/**")//
|
||||
// .excludePathPatterns("/swagger/**")//
|
||||
// .excludePathPatterns("/v3/api-docs/**")//
|
||||
// .excludePathPatterns("/swagger-resources/**")//
|
||||
// .excludePathPatterns("/swagger-ui/**")
|
||||
// .excludePathPatterns("/IpCheck/**")//
|
||||
// ;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.gw.test.controller;
|
||||
|
||||
|
||||
import com.gw.test.domain.Result;
|
||||
import com.gw.test.domain.vo.LoginVo;
|
||||
import com.gw.test.entity.GuoWei;
|
||||
import com.gw.test.service.IGuoWeiService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 前端控制器
|
||||
* </p>
|
||||
*
|
||||
* @author gw
|
||||
* @since 2024-09-04
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/guowei")
|
||||
@Tag(name = "用户管理",description = "用户管理接口")
|
||||
public class GuoWeiController {
|
||||
|
||||
private final IGuoWeiService service;
|
||||
|
||||
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
|
||||
@Operation(summary = "用户列表",description = "用户列表接口",security = { @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) })
|
||||
@GetMapping("/list")
|
||||
public Result<List<GuoWei>> list(){
|
||||
return Result.ok(service.list());
|
||||
}
|
||||
|
||||
// @SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
|
||||
// @Operation(summary = "添加用户",description = "添加用户接口")
|
||||
// @PostMapping("/add")
|
||||
// public Result<Void> save(@RequestBody GuoWei guoWei) {
|
||||
// service.save(guoWei);
|
||||
// return Result.ok();
|
||||
// }
|
||||
|
||||
|
||||
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
|
||||
@Operation(summary = "删除用户",description = "删除用户接口")
|
||||
@DeleteMapping("/delete")
|
||||
public Result<Void> delete(@RequestParam("id") Integer id) {
|
||||
service.removeById(id);
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
|
||||
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
|
||||
@Operation(summary = "用户修改",description = "用户列修改口")
|
||||
@PostMapping("/update")
|
||||
public Result<Void> update(@RequestBody GuoWei guoWei) {
|
||||
service.updateById(guoWei);
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
@Operation(summary = "用户登录",description = "用户登录接口")
|
||||
@PostMapping("/login")
|
||||
public Result<LoginVo> login(String username, String password) {
|
||||
log.error("========>username:{},password:{}",username,password);
|
||||
LoginVo login = service.login(username, password);
|
||||
if (login != null) return Result.ok(login);
|
||||
return Result.error("用户名或密码错误");
|
||||
}
|
||||
|
||||
@Operation(summary = "用户注册",description = "用户注册接口")
|
||||
@PostMapping("/register")
|
||||
public Result<Void> register(GuoWei guoWei) {
|
||||
boolean re = service.register(guoWei);
|
||||
if (re)
|
||||
return Result.ok();
|
||||
else
|
||||
return Result.error("注册失败");
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.gw.test.domain;
|
||||
|
||||
import com.gw.test.enums.ResultCode;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 定义一个R类,用于封装响应数据
|
||||
* @since 2021-09-04
|
||||
*/
|
||||
@Data
|
||||
public class Result<T> {
|
||||
/**
|
||||
* 响应码
|
||||
*/
|
||||
private int code;
|
||||
/**
|
||||
* 响应消息
|
||||
*/
|
||||
private String msg;
|
||||
/**
|
||||
* 响应数据
|
||||
*/
|
||||
private T data;
|
||||
|
||||
/**
|
||||
* 返回一个成功的响应
|
||||
*/
|
||||
public static Result<Void> ok() {
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回一个成功的响应,带有消息和数据
|
||||
* @param msg 消息内容
|
||||
* @param data 数据
|
||||
* @return 成功响应
|
||||
*/
|
||||
public static <T> Result<T> ok(String msg,T data){
|
||||
return new Result<>(200, msg, data);
|
||||
}
|
||||
|
||||
public static <T> Result<T> unauthorized(T data){
|
||||
return new Result<>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
|
||||
}
|
||||
|
||||
public static <T> Result<T> forbidden(T data){
|
||||
return new Result<>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 返回一个成功的响应,仅带有数据
|
||||
* @param data 数据
|
||||
* @return 成功响应
|
||||
*/
|
||||
public static <T> Result<T> ok(T data) {
|
||||
return new Result<>(200, "OK", data);
|
||||
}
|
||||
|
||||
// public static <T> R<T> ok(T data,String msg) {
|
||||
// return new R<>(200, msg, data);
|
||||
// }
|
||||
|
||||
/**
|
||||
* 返回一个错误的响应
|
||||
* @param msg 消息内容
|
||||
* @return 错误响应
|
||||
*/
|
||||
public static <T> Result<T> error(String msg) {
|
||||
return new Result<>(500, msg, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回一个错误的响应,带有错误码和消息
|
||||
* @param code 错误码
|
||||
* @param msg 消息内容
|
||||
* @return 错误响应
|
||||
*/
|
||||
public static <T> Result<T> error(int code, String msg) {
|
||||
return new Result<>(code, msg, null);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
*/
|
||||
public Result() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数,带有参数
|
||||
* @param code 响应码
|
||||
* @param msg 响应消息
|
||||
* @param data 响应数据
|
||||
*/
|
||||
public Result(int code, String msg, T data) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断响应是否成功
|
||||
* @return true-成功,false-失败
|
||||
*/
|
||||
public boolean success(){
|
||||
return code == 200;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.gw.test.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LoginVo {
|
||||
private int id;
|
||||
|
||||
private String username;
|
||||
|
||||
private String token;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.gw.test.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
*
|
||||
* </p>
|
||||
*
|
||||
* @author gw
|
||||
* @since 2024-09-04
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Accessors(chain = true)
|
||||
@TableName("guo_wei")
|
||||
@Schema($schema = "GuoWei对象",description = "")
|
||||
public class GuoWei implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema($schema = "主键")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@Schema($schema = "用户名")
|
||||
private String username;
|
||||
|
||||
@Schema($schema = "密码")
|
||||
private String password;
|
||||
|
||||
@Schema($schema = "创建时间")
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private String createTime;
|
||||
|
||||
@Schema($schema = "手机号")
|
||||
private String phoneNumber;
|
||||
|
||||
@Schema($schema = "权限")
|
||||
private String permissions;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.gw.test.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class User implements UserDetails {
|
||||
private GuoWei entity;
|
||||
|
||||
private List<String> authorities;
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return this.authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return entity.getPassword();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return entity.getUsername();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.gw.test.enums;
|
||||
|
||||
/**
|
||||
* API返回码接口
|
||||
* Created by macro on 2019/4/19.
|
||||
*/
|
||||
public interface IErrorCode {
|
||||
/**
|
||||
* 返回码
|
||||
*/
|
||||
int getCode();
|
||||
|
||||
/**
|
||||
* 返回信息
|
||||
*/
|
||||
String getMessage();
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.gw.test.enums;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* API返回码封装类
|
||||
* Created by macro on 2019/4/19.
|
||||
*/
|
||||
//@Data
|
||||
public enum ResultCode implements IErrorCode {
|
||||
SUCCESS(200, "操作成功"),
|
||||
FAILED(500, "操作失败"),
|
||||
VALIDATE_FAILED(404, "参数检验失败"),
|
||||
UNAUTHORIZED(401, "暂未登录或token已经过期"),
|
||||
FORBIDDEN(403, "没有相关权限");
|
||||
private final int code;
|
||||
private final String message;
|
||||
|
||||
private ResultCode(int code, String message) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.access.AccessDecisionManager;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
import org.springframework.security.authentication.InsufficientAuthenticationException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* 判断用户是否有访问权限
|
||||
*/
|
||||
@Slf4j
|
||||
public class DynamicAccessDecisionManager implements AccessDecisionManager {
|
||||
|
||||
@Override
|
||||
public void decide(Authentication authentication, Object object,
|
||||
Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
|
||||
// 当接口未被配置资源时直接放行
|
||||
// if (CollUtil.isEmpty(configAttributes)) {
|
||||
// return;
|
||||
// }
|
||||
if (configAttributes== null || configAttributes.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (ConfigAttribute configAttribute : configAttributes) {
|
||||
//将访问所需资源或用户拥有资源进行比对
|
||||
String needAuthority = configAttribute.getAttribute();
|
||||
for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
|
||||
log.error("needAuthority:{},grantedAuthority:{}", needAuthority, grantedAuthority.getAuthority());
|
||||
if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AccessDeniedException("抱歉,您没有访问权限");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(ConfigAttribute configAttribute) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> aClass) {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import com.gw.test.config.IgnoreUrlsConfig;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.access.SecurityMetadataSource;
|
||||
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
|
||||
import org.springframework.security.access.intercept.InterceptorStatusToken;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.PathMatcher;
|
||||
|
||||
import jakarta.servlet.*;
|
||||
//import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 权限过滤器,实现基于路径的动态权限过滤
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class DynamicSecurityFilter extends AbstractSecurityInterceptor implements Filter {
|
||||
|
||||
|
||||
private final DynamicSecurityMetadataSource dynamicSecurityMetadataSource;
|
||||
|
||||
|
||||
private final IgnoreUrlsConfig ignoreUrlsConfig;
|
||||
|
||||
@Autowired
|
||||
public void setMyAccessDecisionManager(DynamicAccessDecisionManager dynamicAccessDecisionManager) {
|
||||
super.setAccessDecisionManager(dynamicAccessDecisionManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
|
||||
// log.error("进入动态权限过滤器");
|
||||
HttpServletRequest request = (HttpServletRequest) servletRequest;
|
||||
FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
|
||||
//OPTIONS请求直接放行
|
||||
if(request.getMethod().equals(HttpMethod.OPTIONS.toString())){
|
||||
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
|
||||
return;
|
||||
}
|
||||
//白名单请求直接放行
|
||||
PathMatcher pathMatcher = new AntPathMatcher();
|
||||
for (String path : ignoreUrlsConfig.getUrls()) {
|
||||
// log.error("=============>ignor:{},{}",path,request.getRequestURI());
|
||||
if(pathMatcher.match(path,request.getRequestURI())){
|
||||
log.error("=============>白名单请求直接放行{},{}",request.getRequestURI(),path);
|
||||
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
|
||||
return;
|
||||
}
|
||||
}
|
||||
//此处会调用AccessDecisionManager中的decide方法进行鉴权操作
|
||||
InterceptorStatusToken token = super.beforeInvocation(fi);
|
||||
try {
|
||||
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
|
||||
} finally {
|
||||
super.afterInvocation(token, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getSecureObjectClass() {
|
||||
return FilterInvocation.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SecurityMetadataSource obtainSecurityMetadataSource() {
|
||||
return dynamicSecurityMetadataSource;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import cn.hutool.core.util.URLUtil;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.PathMatcher;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 动态权限数据源,获取动态权限规则
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
|
||||
|
||||
private static Map<String, ConfigAttribute> configAttributeMap = null;
|
||||
// @Autowired
|
||||
private final DynamicSecurityService dynamicSecurityService;
|
||||
|
||||
@PostConstruct
|
||||
public void loadDataSource() {
|
||||
configAttributeMap = dynamicSecurityService.loadDataSource();
|
||||
}
|
||||
|
||||
public void clearDataSource() {
|
||||
configAttributeMap.clear();
|
||||
configAttributeMap = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
|
||||
if (configAttributeMap == null) this.loadDataSource();
|
||||
List<ConfigAttribute> configAttributes = new ArrayList<>();
|
||||
//获取当前访问的路径
|
||||
String url = ((FilterInvocation) o).getRequestUrl();
|
||||
String path = URLUtil.getPath(url);
|
||||
// log.error("------DynamicSecurityMetadataSource:请求url:{}",url);
|
||||
PathMatcher pathMatcher = new AntPathMatcher();
|
||||
//获取访问该路径所需资源
|
||||
for (String pattern : configAttributeMap.keySet()) {
|
||||
if (pathMatcher.match(pattern, path)) {
|
||||
log.error("------DynamicSecurityMetadataSource:匹配到url:{}:{}",pattern,configAttributeMap.get(pattern));
|
||||
configAttributes.add(configAttributeMap.get(pattern));
|
||||
}
|
||||
}
|
||||
// 未设置操作请求权限,返回空集合
|
||||
return configAttributes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<ConfigAttribute> getAllConfigAttributes() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> aClass) {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 动态权限相关业务接口
|
||||
*/
|
||||
public interface DynamicSecurityService {
|
||||
/**
|
||||
* 加载资源ANT通配符和资源对应MAP
|
||||
*/
|
||||
Map<String, ConfigAttribute> loadDataSource();
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import com.gw.test.utils.JWTUtil;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* JWT登录授权过滤器
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
|
||||
// private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
|
||||
|
||||
private final UserDetailsService userDetailsService;
|
||||
|
||||
private final JWTUtil jwtTokenUtil;
|
||||
|
||||
@Value("${jwt.tokenHeader}")
|
||||
private String tokenHeader;
|
||||
|
||||
@Value("${jwt.tokenHead}")
|
||||
private String tokenHead;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain chain) throws ServletException, IOException {
|
||||
// log.error("================JWT过滤器执行=================");
|
||||
// log.error(request.getRequestURI());
|
||||
String authHeader = request.getHeader(this.tokenHeader);
|
||||
if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
|
||||
String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
|
||||
String username = jwtTokenUtil.getUserNameFromToken(authToken);
|
||||
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
|
||||
if (jwtTokenUtil.validateToken(authToken, userDetails)) {
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
|
||||
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.gw.test.domain.Result;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 未登录或者token失效时的返回结果
|
||||
*/
|
||||
@Slf4j
|
||||
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Cache-Control","no-cache");
|
||||
// response.setHeader("authorization", authException.getMessage());
|
||||
// log.error("code{},msg:{}", ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage());
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setContentType("application/json");
|
||||
response.getWriter().println(JSONUtil.parse(Result.unauthorized(authException.getMessage())));
|
||||
response.getWriter().flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.gw.test.filters;
|
||||
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.gw.test.domain.Result;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 自定义无权限访问的返回结果
|
||||
*/
|
||||
public class RestfulAccessDeniedHandler implements AccessDeniedHandler{
|
||||
@Override
|
||||
public void handle(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
AccessDeniedException e) throws IOException, ServletException {
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Cache-Control","no-cache");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setContentType("application/json");
|
||||
response.getWriter().println(JSONUtil.parse(Result.forbidden(e.getMessage()+"没有权限访问该资源....")));
|
||||
response.getWriter().flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.gw.test.mapper;
|
||||
|
||||
import com.gw.test.entity.GuoWei;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Mapper 接口
|
||||
* </p>
|
||||
*
|
||||
* @author gw
|
||||
* @since 2024-09-04
|
||||
*/
|
||||
//@Mapper
|
||||
public interface GuoWeiMapper extends BaseMapper<GuoWei> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.gw.test.service;
|
||||
|
||||
import com.gw.test.domain.vo.LoginVo;
|
||||
import com.gw.test.entity.GuoWei;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 服务类
|
||||
* </p>
|
||||
*
|
||||
* @author gw
|
||||
* @since 2024-09-04
|
||||
*/
|
||||
public interface IGuoWeiService extends IService<GuoWei> {
|
||||
|
||||
UserDetails loadUserByUsername(String s);
|
||||
|
||||
LoginVo login(String username, String password);
|
||||
|
||||
boolean register(GuoWei guoWei);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.gw.test.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.gw.test.domain.vo.LoginVo;
|
||||
import com.gw.test.entity.GuoWei;
|
||||
import com.gw.test.entity.User;
|
||||
import com.gw.test.mapper.GuoWeiMapper;
|
||||
import com.gw.test.service.IGuoWeiService;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.gw.test.utils.JWTUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 服务实现类
|
||||
* </p>
|
||||
*
|
||||
* @author gw
|
||||
* @since 2024-09-04
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class GuoWeiServiceImpl extends ServiceImpl<GuoWeiMapper, GuoWei> implements IGuoWeiService {
|
||||
private final JWTUtil JWTUtil;
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String s) {
|
||||
QueryWrapper<GuoWei> wrapper = new QueryWrapper<>();
|
||||
wrapper.eq("username", s);
|
||||
List<GuoWei> list = list(wrapper);
|
||||
if (list.isEmpty()) return null;
|
||||
GuoWei guoWei = list.getFirst();
|
||||
return new User(guoWei, Arrays.stream(guoWei.getPermissions().split(",")).toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginVo login(String username, String password) {
|
||||
User user = (User) loadUserByUsername(username);
|
||||
if (user == null) return null;
|
||||
|
||||
if (!passwordEncoder.matches(password, user.getPassword())) return null;
|
||||
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
|
||||
LoginVo re = new LoginVo();
|
||||
|
||||
re.setId(user.getEntity().getId());
|
||||
re.setUsername(user.getUsername());
|
||||
re.setToken(JWTUtil.generateToken(user));
|
||||
|
||||
return re;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean register(GuoWei guoWei) {
|
||||
Long count = lambdaQuery()
|
||||
.eq(GuoWei::getUsername, guoWei.getUsername())
|
||||
.count();
|
||||
|
||||
if (count > 0) return false;
|
||||
|
||||
guoWei.setPassword(passwordEncoder.encode(guoWei.getPassword()));
|
||||
return save(guoWei);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.gw.test.utils;
|
||||
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
public class JWTUtil {
|
||||
// private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
|
||||
private static final String CLAIM_KEY_USERNAME = "sub";
|
||||
private static final String CLAIM_KEY_CREATED = "created";
|
||||
@Value("${jwt.secret}")
|
||||
private String secret;
|
||||
@Value("${jwt.expiration}")
|
||||
private Long expiration;
|
||||
@Value("${jwt.tokenHead}")
|
||||
private String tokenHead;
|
||||
|
||||
/**
|
||||
* 根据负责生成JWT的token
|
||||
*/
|
||||
private String generateToken(Map<String, Object> claims) {
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setExpiration(generateExpirationDate())
|
||||
.signWith(SignatureAlgorithm.HS512, secret)
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从token中获取JWT中的负载
|
||||
*/
|
||||
private Claims getClaimsFromToken(String token) {
|
||||
Claims claims = null;
|
||||
try {
|
||||
claims = Jwts.parser()
|
||||
.setSigningKey(secret)
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
} catch (Exception e) {
|
||||
log.info("JWT格式验证失败:{}", token);
|
||||
}
|
||||
return claims;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成token的过期时间
|
||||
*/
|
||||
private Date generateExpirationDate() {
|
||||
return new Date(System.currentTimeMillis() + expiration * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从token中获取登录用户名
|
||||
*/
|
||||
public String getUserNameFromToken(String token) {
|
||||
String username;
|
||||
try {
|
||||
Claims claims = getClaimsFromToken(token);
|
||||
username = claims.getSubject();
|
||||
} catch (Exception e) {
|
||||
username = null;
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证token是否还有效
|
||||
*
|
||||
* @param token 客户端传入的token
|
||||
* @param userDetails 从数据库中查询出来的用户信息
|
||||
*/
|
||||
public boolean validateToken(String token, UserDetails userDetails) {
|
||||
if (userDetails == null || token == null)
|
||||
return false;
|
||||
String username = getUserNameFromToken(token);
|
||||
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断token是否已经失效
|
||||
*/
|
||||
private boolean isTokenExpired(String token) {
|
||||
Date expiredDate = getExpiredDateFromToken(token);
|
||||
return expiredDate.before(new Date());
|
||||
}
|
||||
|
||||
/**
|
||||
* 从token中获取过期时间
|
||||
*/
|
||||
private Date getExpiredDateFromToken(String token) {
|
||||
Claims claims = getClaimsFromToken(token);
|
||||
return claims.getExpiration();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据用户信息生成token
|
||||
*/
|
||||
public String generateToken(UserDetails userDetails) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
|
||||
claims.put(CLAIM_KEY_CREATED, new Date());
|
||||
return generateToken(claims);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当原来的token没过期时是可以刷新的
|
||||
*
|
||||
* @param oldToken 带tokenHead的token
|
||||
*/
|
||||
public String refreshHeadToken(String oldToken) {
|
||||
// if(StrUtil.isEmpty(oldToken)){
|
||||
// return null;
|
||||
// }
|
||||
if(oldToken == null || oldToken.isEmpty()) return null;
|
||||
String token = oldToken.substring(tokenHead.length());
|
||||
// if(StrUtil.isEmpty(token)){
|
||||
// return null;
|
||||
// }
|
||||
if(token.isEmpty()) return null;
|
||||
//token校验不通过
|
||||
Claims claims = getClaimsFromToken(token);
|
||||
if(claims==null){
|
||||
return null;
|
||||
}
|
||||
//如果token已经过期,不支持刷新
|
||||
if(isTokenExpired(token)){
|
||||
return null;
|
||||
}
|
||||
//如果token在30分钟之内刚刷新过,返回原token
|
||||
if(tokenRefreshJustBefore(token,30*60)){
|
||||
return token;
|
||||
}else{
|
||||
claims.put(CLAIM_KEY_CREATED, new Date());
|
||||
return generateToken(claims);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断token在指定时间内是否刚刚刷新过
|
||||
* @param token 原token
|
||||
* @param time 指定时间(秒)
|
||||
*/
|
||||
private boolean tokenRefreshJustBefore(String token, int time) {
|
||||
Claims claims = getClaimsFromToken(token);
|
||||
Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
|
||||
Date refreshDate = new Date();
|
||||
//刷新时间在创建时间的指定时间内
|
||||
return refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, time));
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
spring.application.name=test
|
||||
@@ -0,0 +1,60 @@
|
||||
spring:
|
||||
application:
|
||||
name: test
|
||||
|
||||
datasource:
|
||||
url: jdbc:mysql://222.186.15.41:3306/testapi
|
||||
username: testapi
|
||||
password: BYGAxwj4PZi4GZsA
|
||||
|
||||
server:
|
||||
port: 8080
|
||||
|
||||
|
||||
mybatis-plus:
|
||||
global-config:
|
||||
db-config:
|
||||
column-format: "`%s`"
|
||||
configuration:
|
||||
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
map-underscore-to-camel-case: true
|
||||
|
||||
knife4j:
|
||||
enable: true #开启增强模式
|
||||
setting:
|
||||
language: zh_cn
|
||||
|
||||
springdoc:
|
||||
group-configs:
|
||||
- group: 'test'
|
||||
packages-to-scan: com.gw.test.controller
|
||||
# 配置Swagger UI的访问路径和排序方式
|
||||
swagger-ui:
|
||||
path: /doc.html # Swagger UI的访问路径
|
||||
# tags-sorter: alpha # 按字母顺序排序标签
|
||||
# operations-sorter: alpha # 按字母顺序排序操作
|
||||
# 配置API文档的访问路径
|
||||
api-docs:
|
||||
path: /docs # API文档的访问路径
|
||||
|
||||
jwt:
|
||||
tokenHeader: Authorization #JWT存储的请求头
|
||||
secret: guowei #JWT加解密使用的密钥
|
||||
expiration: 604800 #JWT的超期限时间(60*60*24*7)
|
||||
tokenHead: 'Bearer ' #JWT负载中拿到开头
|
||||
|
||||
secure:
|
||||
ignored:
|
||||
urls:
|
||||
- /webjars/**
|
||||
- /favicon.ico
|
||||
- /swagger/**
|
||||
- /swagger-resources/**
|
||||
- /docs/**
|
||||
- /error
|
||||
- /v3/api-docs/**
|
||||
- /swagger-ui/**
|
||||
- /swagger-ui.html
|
||||
- /doc.html
|
||||
- /guowei/login
|
||||
- /guowei/register
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.gw.test.mapper.GuoWeiMapper">
|
||||
|
||||
<!-- 通用查询映射结果 -->
|
||||
<resultMap id="BaseResultMap" type="com.gw.test.entity.GuoWei">
|
||||
<id column="id" property="id" />
|
||||
<result column="username" property="username" />
|
||||
<result column="password" property="password" />
|
||||
<result column="create_time" property="createTime" />
|
||||
<result column="phone_number" property="phoneNumber" />
|
||||
<result column="permissions" property="permissions" />
|
||||
</resultMap>
|
||||
|
||||
</mapper>
|
||||
Reference in New Issue
Block a user