david hace 2 años
padre
commit
18cabbde75

+ 5 - 0
pom.xml

@@ -55,6 +55,11 @@
 			<artifactId>java-jwt</artifactId>
 			<version>3.4.0</version>
 		</dependency>
+		<!--securityr认证-->
+		<dependency>
+			<groupId>org.springframework.boot</groupId>
+			<artifactId>spring-boot-starter-security</artifactId>
+		</dependency>
 		<dependency>
 			<groupId>org.springframework.boot</groupId>
 			<artifactId>spring-boot-starter-test</artifactId>

+ 24 - 0
src/main/java/com/roma/romaapi/config/WebSecurityConfig.java

@@ -0,0 +1,24 @@
+package com.roma.romaapi.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.web.SecurityFilterChain;
+
+@Configuration
+@EnableWebSecurity
+public class WebSecurityConfig {
+
+    @Bean
+    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
+        http.csrf().disable();
+        http.authorizeHttpRequests((requests) -> requests
+                        .requestMatchers("/**").permitAll()
+                        .anyRequest()
+                        .authenticated())
+                .httpBasic();
+
+        return http.build();
+    }
+}

+ 23 - 9
src/main/java/com/roma/romaapi/service/ApiService.java

@@ -1,9 +1,10 @@
 package com.roma.romaapi.service;
 
 import com.roma.romaapi.dao.ApiDao;
+import com.roma.romaapi.utils.JWTUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.core.ValueOperations;
+import com.roma.romaapi.utils.SecurityUtils;
 import org.springframework.stereotype.Service;
 
 import java.util.HashMap;
@@ -17,6 +18,10 @@ public class ApiService {
     private RedisTemplate<String, String> redisTemplate;
     @Autowired
     private ApiDao apiDao;
+    @Autowired
+    SecurityUtils securityUtils;
+    @Autowired
+    JWTUtil jwtUtil;
     // 登录方法
     public Map<String, Object> login(Map<String, String[]> maps) {
         // 请求参数,获取验证码,验证码token,用户名,密码
@@ -28,23 +33,32 @@ public class ApiService {
         if(!Boolean.TRUE.equals(redisTemplate.hasKey(captchaToken)) || captchaTokenValue!=captcha){
             // 验证码验证失败
         }
+//        String aa = securityUtils.encodePassword(password); // 加密密码
         // 判断是否存在此用户,用户密码是否正确
         Map UserInfo = apiDao.adminInfoQueryForMap(userName);
         if(UserInfo.containsKey("sysErrorCode")) {
             // 如果没查到用户信息,则报错
+            return UserInfo;
         }
-        Object userPassword = UserInfo.get("admin_password");
-        String stringPassword = userPassword.toString();
-
-        if(!password.equals(stringPassword)) {
+        Object adminPassword = UserInfo.get("admin_password");
+        String stringAdminPassword = adminPassword.toString();
+        // 校验密码是否正确
+        if(!securityUtils.matchesPassword(password,stringAdminPassword)) {
             // 校验密码是否正确 密码不正确,返回错误
+            System.out.println("密码校验错误");
         }
 
-//        System.out.println(password);
-        System.out.println(captcha);
-//        System.out.println(captchaToken);
+        // 通过密码,验证码校验,发放token
+        Map<String, Object> jwtInfo = new HashMap<>();
+        Object userId = UserInfo.get("id");
+        String stringUserId = userId.toString();
+        jwtInfo.put("id", stringUserId);
+        jwtInfo.put("loginTime", System.currentTimeMillis()/1000+"");
+        jwtInfo.put("name", userName);
+        String jwtToken = jwtUtil.getToken(jwtInfo);
+        System.out.println("jwt---token==="+jwtToken);
         Map<String, Object> map = new HashMap<>();
-        map.put("token", 1);
+        map.put("loginToken", jwtToken);
 
         return map;
     }

+ 1 - 2
src/main/java/com/roma/romaapi/utils/JWTUtil.java

@@ -42,10 +42,9 @@ public class JWTUtil {
     public String getToken(Map userMapInfo) {
 
         Calendar instance = Calendar.getInstance();
-
-        //默认令牌过期时间30天
         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
+        // 默认令牌过期时间7天
         instance.add(Calendar.DATE, 7);
 
         JWTCreator.Builder builder = JWT.create();

+ 32 - 0
src/main/java/com/roma/romaapi/utils/SecurityUtils.java

@@ -0,0 +1,32 @@
+package com.roma.romaapi.utils;
+
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.stereotype.Component;
+
+@Component
+public class SecurityUtils {
+
+    /**
+     * 生成BCryptPasswordEncoder密码
+     * @param password 密码
+     * @return 加密字符串
+     */
+    public String encodePassword(String password)
+    {
+        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
+        return passwordEncoder.encode(password);
+    }
+
+    /**
+     * 判断密码是否相同
+     * @param rawPassword 真实密码
+     * @param encodedPassword 加密后字符
+     * @return 结果
+     */
+    public boolean matchesPassword(String rawPassword, String encodedPassword)
+    {
+        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
+        return passwordEncoder.matches(rawPassword, encodedPassword);
+    }
+
+}

+ 1 - 1
src/main/resources/application.properties

@@ -1 +1 @@
-#服务
server.port=8081
server.servlet.session.timeout=600

#数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://172.21.85.42:3306/lowcode?serverTimezone=UTC&tinyInt1isBit=false&transformedBitIsBoolean=false
spring.datasource.username = root
spring.datasource.password = mypass

#redis
spring.redis.database=0
spring.redis.password=
#spring.redis.password=name:password
spring.redis.port=6379
spring.redis.host=172.21.85.42
spring.redis.timeout=5000
spring.redis.lettuce.pool.max-active=3
spring.redis.lettuce.pool.min-idle=2
spring.redis.lettuce.pool.max-idle=3
spring.redis.lettuce.pool.max-wait=-1
#spring.redis.lettuce.shutdown-timeout=100
#spring.cache.redis.cache-null-values=false


+#服务
server.port=8081
server.servlet.session.timeout=600

#数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://172.24.48.17:3306/lowcode?serverTimezone=UTC&tinyInt1isBit=false&transformedBitIsBoolean=false
spring.datasource.username = root
spring.datasource.password = mypass

#redis
spring.redis.database=0
spring.redis.password=
#spring.redis.password=name:password
spring.redis.port=6379
spring.redis.host=172.24.48.17
spring.redis.timeout=5000
spring.redis.lettuce.pool.max-active=3
spring.redis.lettuce.pool.min-idle=2
spring.redis.lettuce.pool.max-idle=3
spring.redis.lettuce.pool.max-wait=-1
#spring.redis.lettuce.shutdown-timeout=100
#spring.cache.redis.cache-null-values=false