785834757 1 год назад
Родитель
Сommit
dfec3848c8

+ 4 - 3
authentication/src/main/java/com/jzg/config/JzgAuthenticationProvider.java

@@ -31,10 +31,11 @@ public class JzgAuthenticationProvider implements AuthenticationProvider {
 
 
     private RedissonClient redissonClient;
     private RedissonClient redissonClient;
 
 
-    public JzgAuthenticationProvider(UserDetailsService userDetailsService,SysUserService sysUserService, SysUserRoleService sysUserRoleService) {
+    public JzgAuthenticationProvider(UserDetailsService userDetailsService,SysUserService sysUserService, SysUserRoleService sysUserRoleService,RedissonClient redissonClient) {
         this.userDetailsService = userDetailsService;
         this.userDetailsService = userDetailsService;
         this.sysUserService = sysUserService;
         this.sysUserService = sysUserService;
         this.sysUserRoleService = sysUserRoleService;
         this.sysUserRoleService = sysUserRoleService;
+        this.redissonClient = redissonClient;
     }
     }
 
 
 
 
@@ -48,11 +49,11 @@ public class JzgAuthenticationProvider implements AuthenticationProvider {
         String captchaId = ((JzgUsernamePasswordAuthenticationToken)authentication).getCaptchaId();
         String captchaId = ((JzgUsernamePasswordAuthenticationToken)authentication).getCaptchaId();
         String captcha = ((JzgUsernamePasswordAuthenticationToken)authentication).getCaptcha();
         String captcha = ((JzgUsernamePasswordAuthenticationToken)authentication).getCaptcha();
 
 
-        if(Objects.isNull(redissonClient.getBucket(RedisKeyConstants.VERIFICATION_CODE + captchaId))){
+        if(Objects.isNull(redissonClient.getBucket(RedisKeyConstants.VERIFICATION_CODE + captchaId).get())){
             throw new SystemException("验证码已过期");
             throw new SystemException("验证码已过期");
         }
         }
         String systemCaptcha = redissonClient.getBucket(RedisKeyConstants.VERIFICATION_CODE + captchaId).get().toString();
         String systemCaptcha = redissonClient.getBucket(RedisKeyConstants.VERIFICATION_CODE + captchaId).get().toString();
-        if(!captcha.equals(systemCaptcha)){
+        if(!captcha.toLowerCase().equals(systemCaptcha.toLowerCase())){
             throw new SystemException("验证码错误,请重新输入");
             throw new SystemException("验证码错误,请重新输入");
         }
         }
 
 

+ 2 - 1
authentication/src/main/java/com/jzg/config/JzgTokenService.java

@@ -7,6 +7,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
+import java.util.Objects;
 import java.util.UUID;
 import java.util.UUID;
 
 
 @Component
 @Component
@@ -36,7 +37,7 @@ public class JzgTokenService {
     public String getToken(String token){
     public String getToken(String token){
         RBucket<Object> bucket = redissonClient.getBucket(token);
         RBucket<Object> bucket = redissonClient.getBucket(token);
         Object o = bucket.get();
         Object o = bucket.get();
-        return o.toString();
+        return !Objects.isNull(o) ? o.toString() : null;
     }
     }
 
 
     //生成token
     //生成token

+ 20 - 17
authentication/src/main/java/com/jzg/config/SecurityConfig.java

@@ -1,9 +1,11 @@
 package com.jzg.config;
 package com.jzg.config;
 
 
+import com.jzg.filter.TokenAuthenticationFilter;
 import com.jzg.handler.JzgAuthenticationFailedHandler;
 import com.jzg.handler.JzgAuthenticationFailedHandler;
 import com.jzg.handler.JzgAuthenticationSuccessHandler;
 import com.jzg.handler.JzgAuthenticationSuccessHandler;
 import com.jzg.service.SysUserRoleService;
 import com.jzg.service.SysUserRoleService;
 import com.jzg.service.SysUserService;
 import com.jzg.service.SysUserService;
+import org.redisson.api.RedissonClient;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.context.annotation.Configuration;
@@ -15,6 +17,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
 import org.springframework.security.web.SecurityFilterChain;
 import org.springframework.security.web.SecurityFilterChain;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
 
 
 
 
 @Configuration
 @Configuration
@@ -31,6 +34,9 @@ public class SecurityConfig {
     @Autowired
     @Autowired
     SysUserRoleService sysRoleService;
     SysUserRoleService sysRoleService;
 
 
+    @Autowired
+    RedissonClient redissonClient;
+
     @Bean
     @Bean
     public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
     public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
         return authenticationConfiguration.getAuthenticationManager();
         return authenticationConfiguration.getAuthenticationManager();
@@ -38,7 +44,7 @@ public class SecurityConfig {
 
 
     @Bean
     @Bean
     public AuthenticationProvider authenticationProvider(UserDetailsService userDetailsService) {
     public AuthenticationProvider authenticationProvider(UserDetailsService userDetailsService) {
-        return new JzgAuthenticationProvider(userDetailsService,sysUserService,sysRoleService);
+        return new JzgAuthenticationProvider(userDetailsService,sysUserService,sysRoleService,redissonClient);
     }
     }
 
 
     @Bean
     @Bean
@@ -46,28 +52,25 @@ public class SecurityConfig {
         return new JzgAuthenticationSuccessHandler(tokenService);
         return new JzgAuthenticationSuccessHandler(tokenService);
     }
     }
 
 
+    @Bean
+    public TokenAuthenticationFilter tokenAuthenticationFilter(AuthenticationManager authenticationManager){
+        return new TokenAuthenticationFilter(authenticationManager,tokenService);
+    }
 
 
     @Bean
     @Bean
     public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
     public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
-
+        http.csrf().disable();
         http.authorizeHttpRequests(auth -> auth
         http.authorizeHttpRequests(auth -> auth
-                        .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**", "/favicon.ico").permitAll()
-                        .requestMatchers("/auth/login").permitAll()
-                        .requestMatchers("/auth/getToken").permitAll()
-                        .requestMatchers("/auth/*").permitAll()
-                        .requestMatchers("/auth1/getUser").permitAll()
-                        .requestMatchers("favicon.ico").permitAll()
+                        .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**", "/favicon.ico","/auth/login","/auth/captchaById").permitAll()
                         .anyRequest().authenticated()  // 其他接口需认证
                         .anyRequest().authenticated()  // 其他接口需认证
                 )
                 )
-//                .formLogin().disable()
-                .formLogin((form) -> form
-                        .loginPage("/login")
-                        .successHandler(new JzgAuthenticationSuccessHandler(tokenService))
-                        .failureHandler(new JzgAuthenticationFailedHandler())
-                        .permitAll()
-                        )
-                ;
-
+//                .formLogin((form) -> form
+//                    .loginPage("/login")
+//                    .successHandler(new JzgAuthenticationSuccessHandler(tokenService))
+//                    .failureHandler(new JzgAuthenticationFailedHandler())
+//                    .permitAll()
+//                )
+                .addFilterAfter(tokenAuthenticationFilter(authenticationManager(http.getSharedObject(AuthenticationConfiguration.class))),UsernamePasswordAuthenticationFilter.class);
         return http.build();
         return http.build();
     }
     }
 
 

+ 12 - 39
authentication/src/main/java/com/jzg/controller/AuthController.java

@@ -7,11 +7,15 @@ import com.jzg.config.JzgUserDetailsService;
 import com.jzg.config.JzgUsernamePasswordAuthenticationToken;
 import com.jzg.config.JzgUsernamePasswordAuthenticationToken;
 import com.jzg.config.RedissonConfig;
 import com.jzg.config.RedissonConfig;
 import com.jzg.constants.RedisKeyConstants;
 import com.jzg.constants.RedisKeyConstants;
+import com.jzg.core.base.BaseController;
+import com.jzg.core.page.HttpResult;
 import com.jzg.entity.SysUser;
 import com.jzg.entity.SysUser;
 import com.jzg.entity.vo.LoginFormVo;
 import com.jzg.entity.vo.LoginFormVo;
+import com.jzg.entity.vo.ModifyPassWordFormVo;
 import com.jzg.exception.SystemException;
 import com.jzg.exception.SystemException;
 import com.jzg.handler.JzgAuthenticationSuccessHandler;
 import com.jzg.handler.JzgAuthenticationSuccessHandler;
 import com.jzg.service.SysUserService;
 import com.jzg.service.SysUserService;
+import com.jzg.utils.ImageUtil;
 import com.wf.captcha.SpecCaptcha;
 import com.wf.captcha.SpecCaptcha;
 import com.wf.captcha.base.Captcha;
 import com.wf.captcha.base.Captcha;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.Operation;
@@ -45,7 +49,7 @@ import java.util.concurrent.TimeUnit;
 
 
 @RestController
 @RestController
 @RequestMapping("/auth")
 @RequestMapping("/auth")
-public class AuthController {
+public class AuthController extends BaseController {
 
 
     @Autowired
     @Autowired
     AuthenticationManager authenticationManager;
     AuthenticationManager authenticationManager;
@@ -61,7 +65,6 @@ public class AuthController {
 
 
     @Autowired
     @Autowired
     RedissonClient redissonClient;
     RedissonClient redissonClient;
-    private final Logger logger = LoggerFactory.getLogger(AuthController.class);
     /**
     /**
      * 登录接口
      * 登录接口
      * @param loginFormVo
      * @param loginFormVo
@@ -109,52 +112,22 @@ public class AuthController {
             text = captcha.text();
             text = captcha.text();
         }
         }
         // 生成图片验证码
         // 生成图片验证码
-        BufferedImage image = base64ToBufferedImage(captcha.toBase64());
+        BufferedImage image = ImageUtil.base64ToBufferedImage(captcha.toBase64());
         if (StringUtils.isEmpty(captchaId)) {
         if (StringUtils.isEmpty(captchaId)) {
             throw new SystemException("captchaId  必传");
             throw new SystemException("captchaId  必传");
         }
         }
 
 
         // 保存到验证码到 redis
         // 保存到验证码到 redis
-        redissonClient.getBucket(captchaId).set(RedisKeyConstants.VERIFICATION_CODE + text, 120, TimeUnit.SECONDS);
+        redissonClient.getBucket(RedisKeyConstants.VERIFICATION_CODE + captchaId).set(text, 120, TimeUnit.SECONDS);
         ServletOutputStream out = response.getOutputStream();
         ServletOutputStream out = response.getOutputStream();
         ImageIO.write(image, "jpg", out);
         ImageIO.write(image, "jpg", out);
         IOUtils.closeQuietly(out);
         IOUtils.closeQuietly(out);
     }
     }
 
 
-    public static BufferedImage base64ToBufferedImage(String base64String) {
-        try {
-            // 去除 Base64 编码字符串中的数据前缀,如 "data:image/png;base64,"
-            String base64Image = base64String.split(",")[1];
-            // 解码 Base64 字符串为字节数组
-            byte[] imageBytes = Base64.getDecoder().decode(base64Image);
-            // 将字节数组转换为 ByteArrayInputStream
-            ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
-            // 使用 ImageIO 读取输入流并创建 BufferedImage
-            BufferedImage image = ImageIO.read(bis);
-            return image;
-        } catch (IOException e) {
-            e.printStackTrace();
-            return null;
-        }
-    }
-
-
-    /**
-     * 获取token数据
-     * @param token
-     * @return
-     */
-    @PremissionCheck(value = "authGetToken")
-    @GetMapping("/getToken")
-    public String getToken(String token){
-        String token1 = tokenStore.getToken(token);
-        return token1;
-    }
-
-
-    @GetMapping(value = "getUser")
-    public String getUser() {
-        SysUser admin = sysUserService.getById("admin");
-        return admin.getId().toString();
+    @PostMapping("modifyPass")
+    @Operation(summary = "修改密码")
+    public HttpResult modifyPass(@RequestBody ModifyPassWordFormVo modifyPassWordFormVo){
+        String userName = getUserName();
+        return HttpResult.ok("");
     }
     }
 }
 }

+ 15 - 0
authentication/src/main/java/com/jzg/entity/vo/ModifyPassWordFormVo.java

@@ -0,0 +1,15 @@
+package com.jzg.entity.vo;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+@Data
+@Schema(description = "修改密码表单Vo")
+public class ModifyPassWordFormVo {
+    @Schema(description = "旧密码")
+    private String oldPassWord;
+
+    @Schema(description = "新密码")
+    private String newPassWord;
+
+}

+ 53 - 0
authentication/src/main/java/com/jzg/filter/TokenAuthenticationFilter.java

@@ -0,0 +1,53 @@
+package com.jzg.filter;
+
+import com.alibaba.fastjson.JSONObject;
+import com.jzg.config.JzgTokenService;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.redisson.api.RedissonClient;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+public class TokenAuthenticationFilter extends OncePerRequestFilter {
+
+    private AuthenticationManager authenticationManager;
+
+    private JzgTokenService jzgTokenService;
+
+    public TokenAuthenticationFilter(AuthenticationManager authenticationManager,JzgTokenService jzgTokenService) {
+        this.authenticationManager = authenticationManager;
+        this.jzgTokenService = jzgTokenService;
+    }
+
+    @Override
+    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
+        List<String> doList = new ArrayList<>();
+        doList.add("/auth/login");
+        doList.add("/auth/captchaById");
+        String path = request.getRequestURI();
+        if(doList.contains(path)){
+            filterChain.doFilter(request, response);
+            return;
+        }
+        String authorization = jzgTokenService.getToken(request.getHeader("Authorization"));
+        if(!Objects.isNull(authorization)){
+            JSONObject jsonObject = JSONObject.parseObject(authorization);
+            // 设置用户认证信息
+            Authentication authentication = new UsernamePasswordAuthenticationToken(jsonObject.getString("username"), null, null);
+            SecurityContextHolder.getContext().setAuthentication(authentication);
+            filterChain.doFilter(request,response);
+            return;
+        }
+    }
+}

+ 33 - 0
commons/src/main/java/com/jzg/core/base/BaseController.java

@@ -0,0 +1,33 @@
+package com.jzg.core.base;
+
+
+import com.alibaba.fastjson.JSONObject;
+import com.jzg.exception.SystemException;
+import jakarta.servlet.http.HttpServletRequest;
+import org.redisson.api.RedissonClient;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+import java.util.Objects;
+
+@Component
+public class BaseController {
+
+    @Autowired
+    RedissonClient redissonClient;
+
+    public String getUserName(){
+        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+        HttpServletRequest request = attributes.getRequest();
+        String authorizationHeader = request.getHeader("Authorization");
+        if(Objects.isNull(redissonClient.getBucket(authorizationHeader))){
+            throw new SystemException("用户登录信息过期");
+        }
+        String userJsonStr = redissonClient.getBucket(authorizationHeader).get().toString();
+        JSONObject userInfo = JSONObject.parseObject(userJsonStr);
+        return userInfo.getString("username");
+    }
+
+}

+ 36 - 0
commons/src/main/java/com/jzg/utils/ImageUtil.java

@@ -0,0 +1,36 @@
+package com.jzg.utils;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.Base64;
+
+/**
+ * 图片工具类
+ */
+public class ImageUtil {
+
+    /**
+     * base64转BufferedImage对象
+     * @param base64String
+     * @return
+     */
+    public static BufferedImage base64ToBufferedImage(String base64String) {
+        try {
+            // 去除 Base64 编码字符串中的数据前缀,如 "data:image/png;base64,"
+            String base64Image = base64String.split(",")[1];
+            // 解码 Base64 字符串为字节数组
+            byte[] imageBytes = Base64.getDecoder().decode(base64Image);
+            // 将字节数组转换为 ByteArrayInputStream
+            ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
+            // 使用 ImageIO 读取输入流并创建 BufferedImage
+            BufferedImage image = ImageIO.read(bis);
+            return image;
+        } catch (IOException e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+}