From 7e7a275c0c4a07f5d27ec082538c25b838505998 Mon Sep 17 00:00:00 2001
From: lyfO_o <764716047@qq.com>
Date: 星期一, 27 六月 2022 18:24:48 +0800
Subject: [PATCH] up

---
 safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/accountController/LoginController.java         |   27 +++
 safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenAuthenticationFilter.java |  302 ++++++++++++++++++-------------------
 safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/WebSecurityConfig.java         |   20 +-
 safePlatfrom-out-web/src/main/resources/config/application-dev.yaml                                     |   13 +
 emergency/emergency-service/src/main/java/com/gkhy/safePlatform/emergency/controller/Test.java          |    6 
 safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenConfig.java               |   76 +++++++++
 6 files changed, 271 insertions(+), 173 deletions(-)

diff --git a/emergency/emergency-service/src/main/java/com/gkhy/safePlatform/emergency/controller/Test.java b/emergency/emergency-service/src/main/java/com/gkhy/safePlatform/emergency/controller/Test.java
index 821dc7c..9cc6852 100644
--- a/emergency/emergency-service/src/main/java/com/gkhy/safePlatform/emergency/controller/Test.java
+++ b/emergency/emergency-service/src/main/java/com/gkhy/safePlatform/emergency/controller/Test.java
@@ -1,6 +1,6 @@
 package com.gkhy.safePlatform.emergency.controller;
 
-import com.gkhy.safePlatform.account.rpc.apimodel.NameService;
+import com.gkhy.safePlatform.account.rpc.apimodel.UserAccountService;
 import org.apache.dubbo.config.annotation.DubboReference;
 import org.apache.log4j.LogManager;
 import org.apache.log4j.Logger;
@@ -13,14 +13,14 @@
 public class Test {
 
     @DubboReference(check = false)
-    private NameService nameService;
+    private UserAccountService userAccountService;
 
 //    private Logger logger = LogManager.getLogger(Test.class);
 
 
     @RequestMapping(value = "/t/rpc",method = RequestMethod.GET)
     public Object testRpc(String id){
-        String resp = nameService.sayName(id);
+        String resp = userAccountService.sayName(id);
         return resp;
     }
 }
diff --git a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/accountController/LoginController.java b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/accountController/LoginController.java
new file mode 100644
index 0000000..e257ec2
--- /dev/null
+++ b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/accountController/LoginController.java
@@ -0,0 +1,27 @@
+package com.gkhy.safePlatform.accountController;
+
+import com.alibaba.fastjson.JSONObject;
+import com.gkhy.safePlatform.account.rpc.apimodel.UserAccountService;
+import com.gkhy.safePlatform.account.rpc.apimodel.model.UserLoginRespDTO;
+import com.gkhy.safePlatform.commons.vo.ResultVO;
+import org.apache.dubbo.config.annotation.DubboReference;
+import org.apache.dubbo.config.annotation.DubboService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/auth")
+public class LoginController {
+
+    @DubboReference(check = false)
+    private UserAccountService userAccountService;
+
+    @RequestMapping("/login")
+    public ResultVO<UserLoginRespDTO> authLogin(@RequestBody JSONObject loginForm){
+        String username = loginForm.getString("username");
+        String password = loginForm.getString("password");
+        return userAccountService.authLogin(username, password);
+    }
+}
diff --git a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenAuthenticationFilter.java b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenAuthenticationFilter.java
index c9bd858..874b46f 100644
--- a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenAuthenticationFilter.java
+++ b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenAuthenticationFilter.java
@@ -1,155 +1,147 @@
-//package com.gkhy.safePlatform.config.security;
-//
-//import com.alibaba.fastjson.JSONArray;
-//import com.alibaba.fastjson.JSONObject;
-//import com.gkhy.safePlatform.account.model.cache.CacheUser;
-//import com.gkhy.safePlatform.account.rpc.apimodel.NameService;
-//import com.gkhy.safePlatform.commons.config.token.TokenConfig;
-//import com.gkhy.safePlatform.commons.enums.RedisKeyEnum;
-//import com.gkhy.safePlatform.commons.enums.ResultCodes;
-//import com.gkhy.safePlatform.commons.exception.BusinessException;
-//import com.gkhy.safePlatform.commons.utils.RedisUtils;
-//import com.gkhy.safePlatform.commons.utils.StringUtils;
-//import com.gkhy.safePlatform.commons.vo.ResultVO;
-//import org.apache.dubbo.config.annotation.DubboReference;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-//import org.springframework.security.core.GrantedAuthority;
-//import org.springframework.security.core.authority.SimpleGrantedAuthority;
-//import org.springframework.security.core.context.SecurityContextHolder;
-//import org.springframework.stereotype.Component;
-//import org.springframework.web.filter.OncePerRequestFilter;
-//
-//import javax.servlet.FilterChain;
-//import javax.servlet.ServletException;
-//import javax.servlet.http.HttpServletRequest;
-//import javax.servlet.http.HttpServletResponse;
-//import java.io.IOException;
-//import java.io.PrintWriter;
-//import java.util.ArrayList;
-//import java.util.List;
-//
-///**
-//* @Description: token登录过滤器
-//*/
-//@Component
-//public class TokenAuthenticationFilter extends OncePerRequestFilter  {
-//
-//    @Autowired
-//    private TokenConfig tokenConfig;
-//    @Autowired
-//    private RedisUtils redisUtil;
-//    @DubboReference(check = false)
-//    private NameService nameService;
-//
-//
-//
-//    @Override
-//    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
-//
-//        try {
-//            //获取当前认证成功用户权限信息
-//            UsernamePasswordAuthenticationToken authRequest = getAuthentication(req, resp);
-//            if (authRequest != null) {
-//                SecurityContextHolder.getContext().setAuthentication(authRequest);
-//            }
-//            // 执行下一个 filter 过滤器链
-//            chain.doFilter(req, resp);
-//        } catch (BusinessException e) {
-//            // 返回异常
-//            this.writeJSON(req, resp, new ResultVO<>(e.getError()));
-//        } catch (Exception e) {
-//            e.printStackTrace();
-//            this.writeJSON(req, resp, new ResultVO<>(ResultCodes.SERVER_ERROR));
-//        }
-//
-//
-//    }
-//
-//
-//    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest req,HttpServletResponse resp) {
-//        // header获取token
-//        String authToken = req.getHeader(tokenConfig.getHeader());
-//        String loginUserId = req.getHeader(tokenConfig.getLoginUserHeader());
-//
-//        if(authToken != null) {
-//            // header 传入 userId
-//            if (StringUtils.isBlank(loginUserId)) {
-//                throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_LACK);
-//            }
-//            // 登录成功时,会将权限数据存入redis
-//            // 这里是验证获取权限信息
-//            // 1.从redis中获取对应该用户的权限信息
-//            String accessTokenKey = RedisKeyEnum.authKey(RedisKeyEnum.AUTH_TOKEN, loginUserId);
-//            Object o = redisUtil.get(accessTokenKey);
-//            // 2.token是否存在
-//            if (o == null) {
-//                // 是否存在
-//                throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_SIGN_INVALID);
-//            }else{
-//                Long userId = Long.valueOf(loginUserId);
-//                CacheUser cacheUser = JSONObject.parseObject(o.toString(), CacheUser.class);
-//                assert userId.equals(cacheUser.getUserId());
-//                if ( !authToken.equals(cacheUser.getAccessToken())) {
-//                    throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_TOKEN_INVALID);
-//                }
-//
-//                // 3.redis获取权限
-//                String authoritiesKey = RedisKeyEnum.authKey(RedisKeyEnum.AUTH_AUTHORITIES, userId);
-//                Object oo = redisUtil.get(authoritiesKey);
-//                List<GrantedAuthority> authorities;
-//                // 4.redis中是否存在
-//                if (oo != null) {
-//                    // 5.存在
-//                    String json = oo.toString();
-//                    authorities = JSONArray.parseArray(json, GrantedAuthority.class);
-//                }else {
-//                    authorities = new ArrayList<>();
-//                    // 6.不存在=>数据库查询
-//                    List<String> roleCodes = nameService.getUserRoleCodeByUserId(userId);
-//                    // role
-//                    for (String roleCode : roleCodes) {
-//                        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_" + roleCode);
-//                        authorities.add(simpleGrantedAuthority);
-//                    }
-//
-//                    // permission
-//                    List<String> permissions = nameService.getUserPermissionByUserId(userId);
-//                    for (String permission : permissions) {
-//                        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission);
-//                        authorities.add(simpleGrantedAuthority);
-//                    }
-//                }
-//
-//                // security对象中存入登陆者信息
-//                return new UsernamePasswordAuthenticationToken(userId,authToken,authorities);
-//
-//            }
-//
-//
-//
-//
-//
-//
-//        }
-//        return null;
-//    }
-//
-//
-//
-//    protected void writeJSON(HttpServletRequest req,
-//                             HttpServletResponse resp,
-//                             ResultVO resultVO) throws IOException {
-//        // 设置编码格式
-//        resp.setContentType("text/json;charset=utf-8");
-//        // 处理跨域问题
-//        resp.setHeader("Access-Control-Allow-Origin", "*");
-//        resp.setHeader("Access-Control-Allow-Methods", "POST, GET");
-//
-//        //输出JSON
-//        PrintWriter out = resp.getWriter();
-//        out.write(JSONObject.toJSONString(resultVO));
-//        out.flush();
-//        out.close();
-//    }
-//}
+package com.gkhy.safePlatform.config.security;
+
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.gkhy.safePlatform.account.rpc.apimodel.UserAccountService;
+import com.gkhy.safePlatform.commons.co.CacheUser;
+import com.gkhy.safePlatform.commons.enums.RedisKeyEnum;
+import com.gkhy.safePlatform.commons.enums.ResultCodes;
+import com.gkhy.safePlatform.commons.exception.BusinessException;
+import com.gkhy.safePlatform.commons.utils.StringUtils;
+import com.gkhy.safePlatform.commons.vo.ResultVO;
+import org.apache.dubbo.config.annotation.DubboReference;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+* @Description: token登录过滤器
+*/
+@Component
+public class TokenAuthenticationFilter extends OncePerRequestFilter  {
+
+    @Autowired
+    private TokenConfig tokenConfig;
+    @DubboReference(check = false)
+    private UserAccountService userAccountService;
+
+
+
+    @Override
+    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
+
+        try {
+            //获取当前认证成功用户权限信息
+            UsernamePasswordAuthenticationToken authRequest = getAuthentication(req, resp);
+            if (authRequest != null) {
+                SecurityContextHolder.getContext().setAuthentication(authRequest);
+            }
+            // 执行下一个 filter 过滤器链
+            chain.doFilter(req, resp);
+        } catch (BusinessException e) {
+            // 返回异常
+            this.writeJSON(req, resp, new ResultVO<>(e.getError()));
+        } catch (Exception e) {
+            e.printStackTrace();
+            this.writeJSON(req, resp, new ResultVO<>(ResultCodes.SERVER_ERROR));
+        }
+
+
+    }
+
+
+    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest req,HttpServletResponse resp) {
+        // header获取token
+        String authToken = req.getHeader(tokenConfig.getHeader());
+        String loginUserId = req.getHeader(tokenConfig.getLoginUserHeader());
+
+        if(authToken != null) {
+            // header 传入 userId
+            if (StringUtils.isBlank(loginUserId)) {
+                throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_LACK);
+            }
+            // 登录成功时,会将权限数据存入redis
+            // 这里是验证获取权限信息
+            // 1.从redis中获取对应该用户的权限信息
+            String accessTokenKey = RedisKeyEnum.authKey(RedisKeyEnum.AUTH_TOKEN, loginUserId);
+            String o = userAccountService.getValueByKeyFromRedis(accessTokenKey);
+            // 2.token是否存在
+            if (o == null) {
+                // 是否存在
+                throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_SIGN_INVALID);
+            }else{
+                Long userId = Long.valueOf(loginUserId);
+                CacheUser cacheUser = JSONObject.parseObject(o, CacheUser.class);
+                assert userId.equals(cacheUser.getUserId());
+                if ( !authToken.equals(cacheUser.getAccessToken())) {
+                    throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_TOKEN_INVALID);
+                }
+
+                // 3.redis获取权限
+                String authoritiesKey = RedisKeyEnum.authKey(RedisKeyEnum.AUTH_AUTHORITIES, userId);
+                String oo = userAccountService.getValueByKeyFromRedis(authoritiesKey);
+                List<GrantedAuthority> authorities;
+                // 4.redis中是否存在
+                if (oo != null) {
+                    // 5.存在
+                    authorities = JSONArray.parseArray(oo, GrantedAuthority.class);
+                }else {
+                    authorities = new ArrayList<>();
+                    // 6.不存在=>数据库查询
+                    String roleCode = userAccountService.getUserRoleCodeByUserId(userId);
+                    // role
+                    authorities.add(new SimpleGrantedAuthority("ROLE_" + roleCode));
+
+                    // permission
+                    List<String> permissions = userAccountService.getUserPermissionByUserId(userId);
+                    for (String permission : permissions) {
+                        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission);
+                        authorities.add(simpleGrantedAuthority);
+                    }
+                }
+
+                // security对象中存入登陆者信息
+                return new UsernamePasswordAuthenticationToken(userId,authToken,authorities);
+
+            }
+
+
+
+
+
+
+        }
+        return null;
+    }
+
+
+
+    protected void writeJSON(HttpServletRequest req,
+                             HttpServletResponse resp,
+                             ResultVO resultVO) throws IOException {
+        // 设置编码格式
+        resp.setContentType("text/json;charset=utf-8");
+        // 处理跨域问题
+        resp.setHeader("Access-Control-Allow-Origin", "*");
+        resp.setHeader("Access-Control-Allow-Methods", "POST, GET");
+
+        //输出JSON
+        PrintWriter out = resp.getWriter();
+        out.write(JSONObject.toJSONString(resultVO));
+        out.flush();
+        out.close();
+    }
+}
diff --git a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenConfig.java b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenConfig.java
new file mode 100644
index 0000000..f443806
--- /dev/null
+++ b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/TokenConfig.java
@@ -0,0 +1,76 @@
+package com.gkhy.safePlatform.config.security;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+
+/**
+* @Description: jwt工具类
+* @date 2022/6/14 10:34
+*/
+@Component
+public class TokenConfig {
+
+
+    @Value("${token.secret}")
+    private String secret;
+    @Value("${token.expiration}")
+    private Long expiration;
+    @Value("${token.refreshExpiration}")
+    private Long refreshExpiration;
+    @Value("${token.header}")
+    private String header;
+    @Value("${token.tokenHead}")
+    private String tokenHead;
+    @Value("${token.loginUserHeader}")
+    private String loginUserHeader;
+
+
+    public String getSecret() {
+        return secret;
+    }
+
+    public void setSecret(String secret) {
+        this.secret = secret;
+    }
+
+    public Long getExpiration() {
+        return expiration;
+    }
+
+    public void setExpiration(Long expiration) {
+        this.expiration = expiration;
+    }
+
+    public Long getRefreshExpiration() {
+        return refreshExpiration;
+    }
+
+    public void setRefreshExpiration(Long refreshExpiration) {
+        this.refreshExpiration = refreshExpiration;
+    }
+
+    public String getHeader() {
+        return header;
+    }
+
+    public void setHeader(String header) {
+        this.header = header;
+    }
+
+    public String getTokenHead() {
+        return tokenHead;
+    }
+
+    public void setTokenHead(String tokenHead) {
+        this.tokenHead = tokenHead;
+    }
+
+    public String getLoginUserHeader() {
+        return loginUserHeader;
+    }
+
+    public void setLoginUserHeader(String loginUserHeader) {
+        this.loginUserHeader = loginUserHeader;
+    }
+}
diff --git a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/WebSecurityConfig.java b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/WebSecurityConfig.java
index 10a7a72..3c6ef70 100644
--- a/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/WebSecurityConfig.java
+++ b/safePlatfrom-out-web/src/main/java/com/gkhy/safePlatform/config/security/WebSecurityConfig.java
@@ -1,6 +1,6 @@
 package com.gkhy.safePlatform.config.security;
 
-import com.gkhy.safePlatform.account.rpc.apimodel.NameService;
+import com.gkhy.safePlatform.account.rpc.apimodel.UserAccountService;
 import com.gkhy.safePlatform.config.security.customzie.CustomizeAccessDeniedHandler;
 import com.gkhy.safePlatform.config.security.customzie.CustomizeAuthenticationEntryPoint;
 import org.apache.dubbo.config.annotation.DubboReference;
@@ -14,6 +14,7 @@
 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
 import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
 
@@ -30,12 +31,8 @@
     @Resource
     private CustomizeAuthenticationEntryPoint authenticationEntryPoint;
 
-//    @Resource
-//    private TokenAuthenticationFilter tokenAuthenticationFilter;
-
-    @DubboReference(check = false)
-    private NameService nameService;
-
+    @Resource
+    private TokenAuthenticationFilter tokenAuthenticationFilter;
 
 
 
@@ -48,15 +45,15 @@
         // 关闭session
         http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
         // 登录json放行
-        http.authorizeRequests().anyRequest().permitAll();
+        http.authorizeRequests().antMatchers("/auth/login").permitAll();
         // 关闭
         http.headers().cacheControl();
         // jwt过滤器
-//        http.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
+        http.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
         // 没有登录,没有权限 => 自定义返回
         http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(accessDeniedHandler);
         // 请求认证访问
-//        http.authorizeRequests().anyRequest().authenticated();
+        http.authorizeRequests().anyRequest().authenticated();
         // 允许跨域访问
         http.cors();
 
@@ -80,8 +77,7 @@
     @Bean
     @Qualifier("myUserDetailService")
     protected UserDetailsService userDetailsService(){
-//        return username -> nameService.getUserDetailsByUsername(username);
-        return null;
+        return (username)-> (UserDetails) new Object();
     }
 
 
diff --git a/safePlatfrom-out-web/src/main/resources/config/application-dev.yaml b/safePlatfrom-out-web/src/main/resources/config/application-dev.yaml
index 643f67d..4279034 100644
--- a/safePlatfrom-out-web/src/main/resources/config/application-dev.yaml
+++ b/safePlatfrom-out-web/src/main/resources/config/application-dev.yaml
@@ -24,7 +24,7 @@
 dubbo:
   registry:
     protocol: nacos
-    address: nacos://192.168.0.62:18848?namespace=e07a2454-136b-4498-99eb-09dae3336ebe&username=gkhy_safeplatform_out&password=9485uyJHISes09t
+    address: nacos://192.168.0.52:8848?namespace=e07a2454-136b-4498-99eb-09dae3336ebe&username=gkhy_safeplatform_out&password=9485uyJHISes09t
   application:
     name: gkhy-safeplatform-account-provider
   scan:
@@ -41,13 +41,20 @@
     check: false
 
 minio:
-  endPoint: 192.168.0.62
+  endPoint: 192.168.0.52
   port: 9001
   accessKey: kH6eiQtNrWqGNb1r
   secretKey: ff5ykVUJJn0hi5PghsitdGNSsrW0Xrju
   secure: false
   bucketName: szh-stu
-  urlPrefix: http://192.168.0.62/file
+  urlPrefix: http://192.168.0.52/file
 
 
+token:
+  header: Authorization
+  secret: safe666
+  expiration: 7200
+  refreshExpiration: 14400
+  tokenHead: Bearer
+  loginUserHeader: uid
 

--
Gitblit v1.9.2