28 changed files with 758 additions and 29 deletions
-
39demo/admin/src/main/java/com/example/admin/controller/AdminController.java
-
57demo/admin/src/main/java/com/example/admin/mapper/AdminMapper.java
-
12demo/admin/src/main/java/com/example/admin/mian/qwe.java
-
82demo/admin/src/main/java/com/example/admin/service/AdminServiceImpl.java
-
26demo/admin/src/main/java/com/example/admin/service/UserDetailServiceImpl.java
-
16demo/admin/src/main/resources/application.yml
-
7demo/audit/pom.xml
-
3demo/audit/src/main/java/com/example/audit/AuditApplication.java
-
1demo/audit/src/main/java/com/example/audit/controller/AuditController.java
-
190demo/commons/src/main/java/com/example/commons/Util/JWTUtil.java
-
48demo/commons/src/main/java/com/example/commons/domain/entity/Admin.java
-
1demo/commons/src/main/java/com/example/commons/domain/entity/Detail.java
-
1demo/commons/src/main/java/com/example/commons/domain/vo/Result.java
-
144demo/commons/src/main/java/com/example/commons/security/SecurityConfig.java
-
52demo/commons/src/main/java/com/example/commons/security/TokenFilter.java
-
16demo/commons/src/main/java/com/example/commons/sevice/AdminService.java
-
2demo/commons/src/main/java/com/example/commons/sevice/RechargeService.java
-
2demo/consume/src/main/java/com/example/consume/ConsumeApplication.java
-
61demo/pom.xml
-
1demo/recharge/pom.xml
-
3demo/recharge/src/main/java/com/example/recharge/RechargeApplication.java
-
1demo/recharge/src/main/java/com/example/recharge/controller/RechargeController.java
-
4demo/recharge/src/main/java/com/example/recharge/mapper/RechargeMapper.java
-
6demo/recharge/src/main/java/com/example/recharge/service/RechargeServiceImpl.java
-
2demo/refund/src/main/java/com/example/fefund/FefundApplication.java
-
4demo/statistics/src/main/java/com/example/statistics/StatisticsApplication.java
-
2demo/user/src/main/java/com/example/user/UserApplication.java
-
4demo/user/src/main/java/com/example/user/mapper/UserMapper.java
@ -0,0 +1,39 @@ |
|||
package com.example.admin.controller; |
|||
|
|||
|
|||
import com.example.commons.Util.JWTUtil; |
|||
import com.example.commons.domain.entity.Admin; |
|||
import com.example.commons.domain.vo.Result; |
|||
import com.example.commons.sevice.AdminService; |
|||
import lombok.RequiredArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.web.bind.annotation.*; |
|||
|
|||
import java.util.Arrays; |
|||
|
|||
@RestController |
|||
@RequestMapping("/admin") |
|||
@RequiredArgsConstructor |
|||
@Slf4j |
|||
@CrossOrigin |
|||
public class AdminController { |
|||
|
|||
|
|||
private final AdminService adminService; |
|||
|
|||
@PostMapping("/login") |
|||
public Result login(@RequestBody Admin admin){ |
|||
|
|||
try { |
|||
admin = adminService.login(admin); |
|||
String token = JWTUtil.createJWT(admin); |
|||
admin.setPassword(null); |
|||
return Result.success(token,admin); |
|||
} catch (Exception e) { |
|||
e.printStackTrace(); |
|||
log.error(e.getMessage()); |
|||
return Result.error(e.getMessage()); |
|||
} |
|||
|
|||
} |
|||
} |
@ -0,0 +1,57 @@ |
|||
package com.example.admin.mapper; |
|||
|
|||
import com.example.commons.domain.entity.Admin; |
|||
import org.apache.ibatis.annotations.*; |
|||
|
|||
|
|||
import java.util.List; |
|||
|
|||
@Mapper |
|||
public interface AdminMapper { |
|||
@Insert({ |
|||
"insert into admin", |
|||
"(name,username,password,permission,area,admin_flag,create_time)", |
|||
"values", |
|||
"(#{name},#{username},,#{password},#{permission},#{area},#{admin_flag},now())" |
|||
}) |
|||
@Options(useGeneratedKeys = true,keyColumn = "admin_id",keyProperty = "adminId") |
|||
int insert(Admin admin); |
|||
|
|||
@Update({ |
|||
"<script>", |
|||
"UPDATE admin", |
|||
"<set>", |
|||
"<if test='name!=null and name.length()>0'>name =#{name},</if>", |
|||
"<if test='username!=null and username.length()>0'>username =#{username},</if>", |
|||
"<if test='password!=null and password.length()>0'>password =#{password},</if>", |
|||
"<if test='permission!=null and permission.length()>0'>permission =#{permission},</if>", |
|||
"<if test='area!=null and area.length()>0'>area =#{area},</if>", |
|||
"<if test='adminFlag!=null and adminFlag.length()>0'>admin_flag =#{adminFlag},</if>", |
|||
"</set>", |
|||
"</script>" |
|||
}) |
|||
int update(Admin admin); |
|||
@Select({ |
|||
"select * from admin", |
|||
"where admin_id=#{adminId}" |
|||
}) |
|||
Admin selectById(Integer adminId); |
|||
@Select({ |
|||
"select * from admin", |
|||
"where username=#{username}" |
|||
}) |
|||
Admin selectByName(String username); |
|||
@Select({ |
|||
"<script>", |
|||
"SELECT * from admin", |
|||
"<where>", |
|||
"<if test='name!=null and name.length()>0'> and `name` like concat('%',#{name},'%'),</if>", |
|||
"<if test='username!=null and username.length()>0'> and `username` like concat('%',#{username},'%'),</if>", |
|||
"<if test='permission!=null'> and permission=#{permission},</if>", |
|||
"<if test='area!=null and area.length()>0'> and `area` like concat('%',#{area},'%'),</if>", |
|||
"<if test='adminFlag!=null'> and admin_flag =#{adminFlag},</if>", |
|||
"</where>", |
|||
"</script>" |
|||
}) |
|||
List<Admin> select(Admin admin); |
|||
} |
@ -0,0 +1,12 @@ |
|||
package com.example.admin.mian; |
|||
|
|||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; |
|||
|
|||
public class qwe { |
|||
public static void main(String[] args) { |
|||
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); |
|||
String rawPassword = "123"; |
|||
String encodedPassword = encoder.encode(rawPassword); |
|||
System.out.println("Encoded password: " + encodedPassword); |
|||
} |
|||
} |
@ -0,0 +1,82 @@ |
|||
package com.example.admin.service; |
|||
|
|||
import com.example.admin.mapper.AdminMapper; |
|||
import com.example.commons.domain.entity.Admin; |
|||
import com.example.commons.security.SecurityConfig; |
|||
import com.example.commons.security.TokenFilter; |
|||
import com.example.commons.sevice.AdminService; |
|||
import com.github.pagehelper.PageHelper; |
|||
import com.github.pagehelper.PageInfo; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
|
|||
|
|||
import org.springframework.security.authentication.AuthenticationManager; |
|||
import org.springframework.security.authentication.BadCredentialsException; |
|||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
|||
import org.springframework.security.core.Authentication; |
|||
import org.springframework.security.crypto.password.PasswordEncoder; |
|||
import org.springframework.stereotype.Service; |
|||
|
|||
|
|||
import java.util.List; |
|||
|
|||
@Service |
|||
@RequiredArgsConstructor |
|||
public class AdminServiceImpl implements AdminService { |
|||
@Autowired |
|||
private SecurityConfig securityConfig; |
|||
private final AdminMapper adminMapper; |
|||
@Autowired |
|||
private AuthenticationManager authenticationManager; |
|||
@Autowired |
|||
private PasswordEncoder passwordEncoder; |
|||
|
|||
@Override |
|||
public int add(Admin admin) { |
|||
return adminMapper.insert(admin); |
|||
} |
|||
|
|||
@Override |
|||
public int edit(Admin admin) { |
|||
return adminMapper.update(admin); |
|||
} |
|||
|
|||
@Override |
|||
public Admin findById(Integer adminId) { |
|||
return adminMapper.selectById(adminId); |
|||
} |
|||
|
|||
@Override |
|||
public Admin findByUsername(String username) { |
|||
return adminMapper.selectByName(username); |
|||
} |
|||
|
|||
@Override |
|||
public List<Admin> search(Admin admin) { |
|||
return adminMapper.select(admin); |
|||
} |
|||
|
|||
@Override |
|||
public PageInfo<Admin> searchForPage(Integer pageNum, Integer pageSize, Admin admin) { |
|||
PageHelper.startPage(pageNum, pageSize); |
|||
List<Admin> list = adminMapper.select(admin); |
|||
return new PageInfo<>(list); |
|||
|
|||
} |
|||
|
|||
@Override |
|||
public Admin login(Admin admin) throws Exception { |
|||
UsernamePasswordAuthenticationToken token = |
|||
new UsernamePasswordAuthenticationToken(admin.getUsername(),admin.getPassword()); |
|||
try { |
|||
Authentication authentication = authenticationManager.authenticate(token); |
|||
Admin loginAdmin = (Admin) authentication.getPrincipal(); |
|||
|
|||
return loginAdmin; |
|||
}catch (BadCredentialsException exception){ |
|||
throw new BadCredentialsException("用户或密码错误"); |
|||
|
|||
} |
|||
} |
|||
} |
@ -0,0 +1,26 @@ |
|||
package com.example.admin.service; |
|||
|
|||
import com.example.admin.mapper.AdminMapper; |
|||
import com.example.commons.domain.entity.Admin; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.security.core.userdetails.UserDetails; |
|||
import org.springframework.security.core.userdetails.UserDetailsService; |
|||
import org.springframework.security.core.userdetails.UsernameNotFoundException; |
|||
import org.springframework.stereotype.Service; |
|||
import org.springframework.util.ObjectUtils; |
|||
|
|||
@Service |
|||
@RequiredArgsConstructor |
|||
public class UserDetailServiceImpl implements UserDetailsService { |
|||
@Autowired |
|||
private AdminMapper adminMapper; |
|||
@Override |
|||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { |
|||
Admin admin=adminMapper.selectByName(username); |
|||
if(ObjectUtils.isEmpty(admin)){ |
|||
throw new UsernameNotFoundException("用户名不存在"); |
|||
} |
|||
return admin; |
|||
} |
|||
} |
@ -0,0 +1,16 @@ |
|||
server: |
|||
port: 10070 |
|||
|
|||
spring: |
|||
datasource: |
|||
driver-class-name: com.mysql.cj.jdbc.Driver |
|||
url: jdbc:mysql://39.101.133.168/hwgold?serverTimezone=GMT%2b8 |
|||
username: hwgold |
|||
password: 'AGX4Z3YMxiCG3GR2' |
|||
application: |
|||
name: recharge |
|||
mybatis: |
|||
configuration: |
|||
map-underscore-to-camel-case: true |
|||
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl |
|||
|
@ -0,0 +1,190 @@ |
|||
package com.example.commons.Util; |
|||
|
|||
import com.fasterxml.jackson.core.JsonProcessingException; |
|||
import com.fasterxml.jackson.databind.ObjectMapper; |
|||
import io.jsonwebtoken.Claims; |
|||
import io.jsonwebtoken.JwtBuilder; |
|||
import io.jsonwebtoken.Jwts; |
|||
import io.jsonwebtoken.SignatureAlgorithm; |
|||
import org.springframework.security.core.userdetails.UserDetails; |
|||
|
|||
import javax.crypto.SecretKey; |
|||
import javax.crypto.spec.SecretKeySpec; |
|||
import java.util.Base64; |
|||
import java.util.Date; |
|||
import java.util.UUID; |
|||
|
|||
/** |
|||
* JWT的工具类 |
|||
*/ |
|||
public class JWTUtil { |
|||
|
|||
//有效期为 |
|||
public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000 一个小时 |
|||
|
|||
//设置 密钥 |
|||
public static final String JWT_KEY = "bobzyh"; |
|||
|
|||
public static String getUUID(){ |
|||
String token = UUID.randomUUID().toString().replaceAll("-", ""); |
|||
return token; |
|||
} |
|||
|
|||
/** |
|||
* 用户信息创建JWT,默认有效期30分钟 |
|||
* @param user |
|||
* @return |
|||
*/ |
|||
public static String createJWT(UserDetails user) { |
|||
ObjectMapper mapper = new ObjectMapper(); |
|||
try { |
|||
String json = mapper.writeValueAsString(user); |
|||
System.out.println("用户的JSON"); |
|||
System.out.println(json); |
|||
return createJWT(json, JWT_TTL); |
|||
} catch (JsonProcessingException e) { |
|||
throw new RuntimeException(e); |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* 用户信息创建JWT, 指定有效期,单位秒 |
|||
* @param user |
|||
* @param ttlMillis |
|||
* @return |
|||
*/ |
|||
public static String createJWT(UserDetails user, Long ttlMillis) { |
|||
ObjectMapper mapper = new ObjectMapper(); |
|||
try { |
|||
String json = mapper.writeValueAsString(user); |
|||
return createJWT(json, ttlMillis); |
|||
} catch (JsonProcessingException e) { |
|||
throw new RuntimeException(e); |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* 生成jtw |
|||
* @param subject token中要存放的数据(json格式) |
|||
* @return |
|||
*/ |
|||
public static String createJWT(String subject) { |
|||
JwtBuilder builder = getJwtBuilder(subject, 30*60*1000L, getUUID());// 设置过期时间 |
|||
return builder.compact(); |
|||
} |
|||
|
|||
/** |
|||
* 生成jtw |
|||
* @param subject token中要存放的数据(json格式) |
|||
* @param ttlMillis token超时时间 |
|||
* @return |
|||
*/ |
|||
public static String createJWT(String subject, Long ttlMillis) { |
|||
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间 |
|||
return builder.compact(); |
|||
} |
|||
|
|||
private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) { |
|||
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //加密算法 |
|||
SecretKey secretKey = generalKey(); //密钥 |
|||
long nowMillis = System.currentTimeMillis(); //当前时间 |
|||
Date now = new Date(nowMillis); |
|||
if(ttlMillis==null){ |
|||
ttlMillis= JWTUtil.JWT_TTL; |
|||
} |
|||
long expMillis = nowMillis + ttlMillis; |
|||
Date expDate = new Date(expMillis); //过期时间 |
|||
return Jwts.builder() |
|||
.setId(uuid) //唯一的ID |
|||
.setSubject(subject) // 主题 可以是JSON数据 |
|||
.setIssuer("sg") // 签发者 |
|||
.setIssuedAt(now) // 签发时间 |
|||
.signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥 |
|||
.setExpiration(expDate); |
|||
} |
|||
|
|||
/** |
|||
* 创建token |
|||
* @param id |
|||
* @param subject |
|||
* @param ttlMillis |
|||
* @return |
|||
*/ |
|||
public static String createJWT(String id, String subject, Long ttlMillis) { |
|||
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间 |
|||
return builder.compact(); |
|||
} |
|||
|
|||
/** |
|||
* 生成加密后的秘钥 secretKey |
|||
* @return |
|||
*/ |
|||
public static SecretKey generalKey() { |
|||
byte[] encodedKey = Base64.getDecoder().decode(JWTUtil.JWT_KEY); |
|||
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES"); |
|||
return key; |
|||
} |
|||
|
|||
/** |
|||
* 解析 |
|||
* |
|||
* @param jwt |
|||
* @return |
|||
* @throws Exception |
|||
*/ |
|||
public static Claims parseJWT(String jwt) throws Exception { |
|||
SecretKey secretKey = generalKey(); |
|||
return Jwts.parser() |
|||
.setSigningKey(secretKey) |
|||
.parseClaimsJws(jwt) |
|||
.getBody(); |
|||
} |
|||
|
|||
/** |
|||
* 解析为用户 |
|||
* @param jwt |
|||
* @return |
|||
* @throws Exception |
|||
*/ |
|||
public static UserDetails getUserDetails(String jwt, Class<? extends UserDetails> cls) throws Exception { |
|||
Claims claims = JWTUtil.parseJWT(jwt); |
|||
String json = claims.getSubject(); |
|||
ObjectMapper mapper = new ObjectMapper(); |
|||
UserDetails user = null; |
|||
user = mapper.readValue(json, cls); |
|||
|
|||
return user; |
|||
} |
|||
|
|||
public static UserDetails getUserDetailsList(String jwt, Class<? extends UserDetails> ...cls) throws Exception { |
|||
Claims claims = JWTUtil.parseJWT(jwt); |
|||
String json = claims.getSubject(); |
|||
ObjectMapper mapper = new ObjectMapper(); |
|||
if (cls != null && cls.length > 0) { |
|||
for (Class<? extends UserDetails> cl : cls) { |
|||
try { |
|||
UserDetails user = mapper.readValue(json, cl); |
|||
return user; |
|||
} catch (JsonProcessingException e) { |
|||
e.printStackTrace(); |
|||
} |
|||
} |
|||
} |
|||
return null; |
|||
} |
|||
|
|||
|
|||
// public static void main(String[] args) throws Exception { |
|||
// |
|||
// // 加密 |
|||
// String jwt = createJWT("2123"); |
|||
// System.out.println(jwt); |
|||
// |
|||
// // 解密 |
|||
// Claims claims = parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2Y2QzZGU0NWRiN2I0MjVlOWJlZTAzYzUyNjY2ODhhYiIsInN1YiI6IjIxMjMiLCJpc3MiOiJzZyIsImlhdCI6MTcxMDgzMTc4NCwiZXhwIjoxNzEwODM1Mzg0fQ.k6RPyIvKX-mrS26YbyaDNVLlihGqTQDeLj2gsrNokCk"); |
|||
// String subject = claims.getSubject(); |
|||
// System.out.println(subject); |
|||
// |
|||
// } |
|||
|
|||
} |
@ -1,23 +1,65 @@ |
|||
package com.example.commons.domain.entity; |
|||
|
|||
import com.fasterxml.jackson.annotation.JsonFormat; |
|||
import com.fasterxml.jackson.annotation.JsonIgnore; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.springframework.format.annotation.DateTimeFormat; |
|||
import org.springframework.security.core.GrantedAuthority; |
|||
import org.springframework.security.core.authority.SimpleGrantedAuthority; |
|||
import org.springframework.security.core.userdetails.UserDetails; |
|||
|
|||
import java.util.Date; |
|||
import java.io.Serializable; |
|||
import java.util.*; |
|||
|
|||
@Data |
|||
@NoArgsConstructor |
|||
public class Admin { |
|||
public class Admin implements UserDetails, Serializable { |
|||
private Integer adminId; |
|||
private String name; |
|||
private String username; |
|||
private String password; |
|||
private String permission; |
|||
private Integer permission; |
|||
private String area; |
|||
private String adminFlag; |
|||
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") |
|||
@DateTimeFormat(pattern = "yyyy-MM-dd") |
|||
private Date createTime; |
|||
|
|||
@Override |
|||
@JsonIgnore |
|||
public Collection<? extends GrantedAuthority> getAuthorities() { |
|||
Set<GrantedAuthority>authorities = new HashSet<>(); |
|||
if(permission == 1){ |
|||
|
|||
authorities.add(new SimpleGrantedAuthority("ROLE_SUPER_ADMIN")); |
|||
}else if(permission == 2){ |
|||
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN")); |
|||
} |
|||
return authorities; |
|||
} |
|||
@Override |
|||
@JsonIgnore |
|||
public boolean isAccountNonExpired() { |
|||
return UserDetails.super.isAccountNonExpired(); |
|||
} |
|||
|
|||
@Override |
|||
@JsonIgnore |
|||
public boolean isAccountNonLocked() { |
|||
return UserDetails.super.isAccountNonLocked(); |
|||
} |
|||
|
|||
@Override |
|||
@JsonIgnore |
|||
public boolean isCredentialsNonExpired() { |
|||
return UserDetails.super.isCredentialsNonExpired(); |
|||
} |
|||
|
|||
@Override |
|||
@JsonIgnore |
|||
public boolean isEnabled() { |
|||
return UserDetails.super.isEnabled(); |
|||
} |
|||
} |
|||
|
@ -0,0 +1,144 @@ |
|||
package com.example.commons.security; |
|||
|
|||
|
|||
import com.example.commons.domain.vo.Result; |
|||
import jakarta.servlet.http.HttpServletResponse; |
|||
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.authentication.AuthenticationManager; |
|||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; |
|||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; |
|||
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.http.SessionCreationPolicy; |
|||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; |
|||
import org.springframework.security.crypto.password.PasswordEncoder; |
|||
import org.springframework.security.web.AuthenticationEntryPoint; |
|||
import org.springframework.security.web.SecurityFilterChain; |
|||
import org.springframework.security.web.access.AccessDeniedHandler; |
|||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; |
|||
import org.springframework.web.cors.CorsConfiguration; |
|||
import org.springframework.web.cors.CorsConfigurationSource; |
|||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource; |
|||
|
|||
/** |
|||
* SpringSecurity的配置文件 |
|||
*/ |
|||
@Configuration |
|||
|
|||
@EnableWebSecurity // 开启Security的支持 |
|||
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法注解 |
|||
|
|||
public class SecurityConfig { |
|||
|
|||
|
|||
@Autowired |
|||
TokenFilter tokenFilter; |
|||
|
|||
// 核心配置 配置一个过滤器链 |
|||
@Bean |
|||
public SecurityFilterChain configure(HttpSecurity http) throws Exception { |
|||
// 这里可以对httpSecurity进行详细的配置 链式调用的配置方式 |
|||
http.formLogin(AbstractHttpConfigurer::disable) // 方法引用,禁用表单登录 |
|||
.logout(AbstractHttpConfigurer::disable) // 禁用默认退出 |
|||
.csrf(AbstractHttpConfigurer::disable) // 禁用csrf的保护,分布式的前后端分离的项目 |
|||
// 设定CORS |
|||
.cors(cors -> cors.configurationSource(corsConfigurationSource())) |
|||
// 禁用Session, |
|||
.sessionManagement( session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) |
|||
// 用户未登录的处理 |
|||
.exceptionHandling( exception -> exception.authenticationEntryPoint(authenticationEntryPoint())) |
|||
// 用户权限不足的处理 |
|||
.exceptionHandling( exception -> exception.accessDeniedHandler(accessDeniedHandler())) |
|||
// 配置路径拦截 |
|||
.authorizeHttpRequests( request -> |
|||
request.requestMatchers( HttpMethod.GET, |
|||
// 用户不登录可以访问的路径 |
|||
"/captcha", |
|||
"/category", |
|||
"/product/**", |
|||
"/upload/**").permitAll() |
|||
.requestMatchers( HttpMethod.POST, |
|||
// 用户不登录就可以访问的路径 |
|||
"/user/login", "/user", |
|||
"/admin/login","/upload/**").permitAll() |
|||
.requestMatchers( |
|||
"/error","alipay/**" |
|||
).permitAll() |
|||
.anyRequest().authenticated() // 其它路径,必须要登录后才能访问 |
|||
); |
|||
// 配置Token过滤器, 将过滤器加入到执行链中 |
|||
http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class); |
|||
|
|||
return http.build(); |
|||
} |
|||
|
|||
/** |
|||
* 1. 配置认证管理器 |
|||
* @param config |
|||
* @return |
|||
* @throws Exception |
|||
*/ |
|||
@Bean |
|||
protected AuthenticationManager authenticationManager( |
|||
AuthenticationConfiguration config ) throws Exception { |
|||
return config.getAuthenticationManager(); |
|||
} |
|||
|
|||
/** |
|||
* 2. 密码编码器 |
|||
* @return |
|||
*/ |
|||
@Bean |
|||
public PasswordEncoder passwordEncoder() { |
|||
return new BCryptPasswordEncoder(); |
|||
} |
|||
|
|||
/** |
|||
* 3. 用户未登录时的错误处理 |
|||
* @return |
|||
*/ |
|||
@Bean |
|||
public AuthenticationEntryPoint authenticationEntryPoint() { |
|||
return ( request, response, authException) -> { |
|||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 |
|||
response.setContentType("application/json; charset=utf-8"); |
|||
response.getWriter().write(Result.error("用户未登录").toJson()); |
|||
}; |
|||
} |
|||
|
|||
/** |
|||
* 4. 权限不足时的处理 |
|||
* @return |
|||
*/ |
|||
@Bean |
|||
public AccessDeniedHandler accessDeniedHandler() { |
|||
return ( request, response, authException) -> { |
|||
response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403 |
|||
response.setContentType("application/json; charset=utf-8"); |
|||
response.getWriter().write(Result.error("当前用户权限不足!").toJson()); |
|||
}; |
|||
} |
|||
|
|||
/** |
|||
* 5. 配置跨域请求 |
|||
* @return |
|||
*/ |
|||
@Bean |
|||
public CorsConfigurationSource corsConfigurationSource() { |
|||
CorsConfiguration config = new CorsConfiguration(); |
|||
config.addAllowedOriginPattern("*"); // 允许任何的源 |
|||
config.addAllowedMethod("*"); // 允许任何的HTTP请求方式 |
|||
config.addAllowedHeader("*"); // 允许任何的HTTP头 |
|||
config.setAllowCredentials(true); // 允许证书 |
|||
config.setMaxAge(3600L); // 设置浏览器预检的时间 |
|||
|
|||
// 生成源 |
|||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); |
|||
source.registerCorsConfiguration("/**", config); |
|||
return source; |
|||
} |
|||
} |
@ -0,0 +1,52 @@ |
|||
package com.example.commons.security; |
|||
|
|||
|
|||
import com.example.commons.Util.JWTUtil; |
|||
import com.example.commons.domain.entity.Admin; |
|||
import jakarta.servlet.FilterChain; |
|||
import jakarta.servlet.ServletException; |
|||
import jakarta.servlet.http.HttpServletRequest; |
|||
import jakarta.servlet.http.HttpServletResponse; |
|||
|
|||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
|||
import org.springframework.security.core.context.SecurityContextHolder; |
|||
import org.springframework.security.core.userdetails.UserDetails; |
|||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; |
|||
|
|||
import org.springframework.stereotype.Component; |
|||
import org.springframework.util.ObjectUtils; |
|||
import org.springframework.util.StringUtils; |
|||
import org.springframework.web.filter.OncePerRequestFilter; |
|||
|
|||
import java.io.IOException; |
|||
|
|||
@Component |
|||
public class TokenFilter extends OncePerRequestFilter { |
|||
@Override |
|||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { |
|||
// 取Token 生成登录信息 |
|||
String token = request.getHeader("token"); |
|||
// token不为空 |
|||
if (StringUtils.hasText(token)){ |
|||
// jwt解密 |
|||
try { |
|||
UserDetails userDetails = JWTUtil.getUserDetailsList(token,Admin.class); |
|||
if ( ! ObjectUtils.isEmpty(userDetails)) { |
|||
// 将这个用户注册到Security中 |
|||
UsernamePasswordAuthenticationToken authenticationToken |
|||
|
|||
= new UsernamePasswordAuthenticationToken( |
|||
userDetails, null, |
|||
userDetails.getAuthorities()); |
|||
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); |
|||
SecurityContextHolder.getContext().setAuthentication(authenticationToken); |
|||
} |
|||
} catch (Exception e) { |
|||
e.printStackTrace(); |
|||
// Token无效, |
|||
} |
|||
} |
|||
// 过滤器放行 |
|||
filterChain.doFilter(request, response); |
|||
} |
|||
} |
@ -0,0 +1,16 @@ |
|||
package com.example.commons.sevice; |
|||
|
|||
import com.example.commons.domain.entity.Admin; |
|||
import com.github.pagehelper.PageInfo; |
|||
|
|||
import java.util.List; |
|||
|
|||
public interface AdminService { |
|||
int add(Admin admin); |
|||
int edit(Admin admin); |
|||
Admin findById(Integer adminId); |
|||
Admin findByUsername(String username); |
|||
List<Admin> search(Admin admin); |
|||
PageInfo<Admin> searchForPage(Integer pageNum, Integer pageSize,Admin admin); |
|||
Admin login(Admin admin)throws Exception; |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue