From 63a2ea38c95e26f8b754a84290a011a6836a9a8e Mon Sep 17 00:00:00 2001 From: 18616268358 <1440265357@qq.com> Date: Sat, 20 May 2023 18:13:47 +0800 Subject: [PATCH] =?UTF-8?q?#20230510=20=E6=AC=A3=E5=BD=B1=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=B9=B3=E5=8F=B0=E8=A3=85=E7=BD=AE=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/TestController.java | 62 --------- xymanager_service/pom.xml | 4 + .../security/CustomSecurityConfig.java | 118 ++++-------------- .../JwtAuthenticationTokenFilter.java | 64 ---------- .../service/security/JwtInterceptor.java | 94 ++++++++++++++ 5 files changed, 124 insertions(+), 218 deletions(-) delete mode 100644 xymanager_admin/src/main/java/com/shxy/xymanager_admin/controller/TestController.java delete mode 100644 xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/JwtAuthenticationTokenFilter.java create mode 100644 xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/JwtInterceptor.java diff --git a/xymanager_admin/src/main/java/com/shxy/xymanager_admin/controller/TestController.java b/xymanager_admin/src/main/java/com/shxy/xymanager_admin/controller/TestController.java deleted file mode 100644 index 63a1ff7..0000000 --- a/xymanager_admin/src/main/java/com/shxy/xymanager_admin/controller/TestController.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.shxy.xymanager_admin.controller; - -import com.shxy.xymanager_common.annotation.Log; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import lombok.extern.slf4j.Slf4j; -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.authc.IncorrectCredentialsException; -import org.apache.shiro.authc.UnknownAccountException; -import org.apache.shiro.authc.UsernamePasswordToken; -import org.apache.shiro.subject.Subject; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - - -@Api(value = "测试接口", tags = "测试接口tags") -@Controller -@Slf4j -public class TestController { - - @ApiOperation(value = "测试", notes = "测试notes", httpMethod = "POST") - @ApiResponses({@ApiResponse(code = 200, message = "请求成功"), @ApiResponse(code = 400, message = "请求参数没填好"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")}) - @RequestMapping("/user/login") - @Log(title = "测试", type = "查询") - public String gettest() { - log.info("有一个沙雕点了链接"); - return "/api/index2"; - } - - @GetMapping("/user/logins") - @Log(title = "测试", type = "查询") - public String hhtest() { - log.info("有一个沙雕点了链接"); - return "/api/index2.html"; - } - - @ApiOperation(value = "登录", notes = "登录", httpMethod = "POST") -// @ApiResponses({@ApiResponse(code = 200, message = "请求成功"), @ApiResponse(code = 400, message = "请求参数没填好"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")}) - @RequestMapping("/login") - @Log(title = "登录", type = "查询") - public String login(String username, String password) { - //获取主题对象 - Subject subject = SecurityUtils.getSubject(); - try { - subject.login(new UsernamePasswordToken(username,password)); - System.out.println("登录成功!!!"); - return "登录成功"; - } catch (UnknownAccountException e) { - e.printStackTrace(); - System.out.println("用户错误!!!"); - } catch (IncorrectCredentialsException e) { - System.out.println("密码错误!!!"); - } - return "登录失败"; - } - -} diff --git a/xymanager_service/pom.xml b/xymanager_service/pom.xml index 38e1265..be10ed6 100644 --- a/xymanager_service/pom.xml +++ b/xymanager_service/pom.xml @@ -31,6 +31,10 @@ jjwt 0.9.0 + + org.springframework + spring-webmvc + diff --git a/xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/CustomSecurityConfig.java b/xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/CustomSecurityConfig.java index 2ecb87b..6ba37a1 100644 --- a/xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/CustomSecurityConfig.java +++ b/xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/CustomSecurityConfig.java @@ -1,113 +1,47 @@ package com.shxy.xymanager_service.service.security; -import com.shxy.xymanager_common.security.componet.CustomAuthExceptionEntryPoint; - -import com.shxy.xymanager_service.impl.CustomUserDetailsServiceImpl; -import com.shxy.xymanager_service.impl.LogoutSuccessHandlerImpl; -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.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -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.configuration.WebSecurityConfigurerAdapter; 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.authentication.UsernamePasswordAuthenticationFilter; +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 -@EnableWebSecurity// 这个注解必须加,开启Security -@EnableGlobalMethodSecurity(prePostEnabled = true)//保证post之前的注解可以使用 -@Slf4j -public class CustomSecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private CustomAuthExceptionEntryPoint customAuthExceptionEntryPoint; - - @Autowired - private CustomUserDetailsServiceImpl customUserDetailsServiceImpl; - - @Autowired - private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; - /** - * 退出处理类 - */ - @Autowired - private LogoutSuccessHandlerImpl logoutSuccessHandler; +public class CustomSecurityConfig implements WebMvcConfigurer { + private final JwtInterceptor jwtInterceptor; - - //先来这里认证一下 - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - log.info("213123123"); - auth.userDetailsService(customUserDetailsServiceImpl).passwordEncoder(passwordEncoderBean()); + public CustomSecurityConfig(JwtInterceptor jwtInterceptor) { + this.jwtInterceptor = jwtInterceptor; } - //拦截在这配 @Override - protected void configure(HttpSecurity httpSecurity) throws Exception { - log.info("123566"); - httpSecurity - // 认证失败处理类 - .exceptionHandling().authenticationEntryPoint(customAuthExceptionEntryPoint).and() - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and() - // 过滤请求 - .authorizeRequests() - // 对于登录login 验证码captchaImage 允许匿名访问 - .antMatchers("/login", "/captchaImage").anonymous() - .antMatchers("*/api/addUser").anonymous() - .antMatchers("**/addUser").anonymous() - .antMatchers("/addUser").anonymous() - .antMatchers( - HttpMethod.GET, - "/*.html", - "/**/*.html", - "/**/*.css", - "/**/*.js" - ).permitAll() - .antMatchers("/profile/**").anonymous() - .antMatchers("/common/download**").anonymous() - .antMatchers("/swagger-ui.html").anonymous() - .antMatchers("/swagger-resources/**").anonymous() - .antMatchers("/webjars/**").anonymous() - .antMatchers("/*/api-docs").anonymous() - .antMatchers("/druid/**").anonymous() - .antMatchers("/test/**").anonymous() - .antMatchers( "/v3/**").anonymous() - .antMatchers( "/error").anonymous() -// .antMatchers("/**").anonymous() - .antMatchers("/api/**").anonymous() -// .antMatchers("/busiMainDeviceController/**").anonymous() - .antMatchers("/sysLoginRemoteController/**").anonymous() -// .antMatchers("/remote/**").anonymous() - .antMatchers("/userRemote/**").anonymous() - // 除上面外的所有请求全部需要鉴权认证 - .anyRequest().authenticated() - .and() - .headers().frameOptions().disable(); - - httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler); - // 添加JWT filter - httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); - } - - @Bean - public PasswordEncoder passwordEncoderBean() { - return new BCryptPasswordEncoder(); + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(this.jwtInterceptor).addPathPatterns("/getXcxMainInfo").addPathPatterns("/authorizeXcxLogin") + .addPathPatterns("/bindXcxDevice") + .excludePathPatterns("/login") + .excludePathPatterns("/api/addUser") + .excludePathPatterns("/swagger-ui.html") + .excludePathPatterns("/swagger-resources/**") + .excludePathPatterns("/*/api-docs") + .excludePathPatterns("/error") + .excludePathPatterns("/test/**") + .excludePathPatterns("/loginXcxuser") + .excludePathPatterns("/loginXcxuser") + .excludePathPatterns("/addUser"); } - @Bean @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins("*") + .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") + .maxAge(3600) + .allowCredentials(false); } } \ No newline at end of file diff --git a/xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/JwtAuthenticationTokenFilter.java b/xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/JwtAuthenticationTokenFilter.java deleted file mode 100644 index 9bf498b..0000000 --- a/xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/JwtAuthenticationTokenFilter.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.shxy.xymanager_service.service.security; - - -import com.shxy.xymanager_common.entity.UserSession; -import com.shxy.xymanager_common.security.LoginUser; -import com.shxy.xymanager_common.util.MyDateUtils; -import com.shxy.xymanager_common.util.SecurityUtils; -import com.shxy.xymanager_service.service.SysUserService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; -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.math.BigInteger; - -/** - * @ClassName:JwtAuthenticationTokenFilter - * @Description: token过滤器 验证token有效性. - * @Author: Arno_Fu - * @CreatTime:11/26/2019 - 6:34 PM - * @Version V1.0 - */ -@Component -public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { - - @Autowired - private SysUserService sysUserService; - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { - UserSession user = null; - if(null!= request.getSession().getAttribute("sessionId")) { - String sessionId = request.getSession().getAttribute("sessionId").toString(); - user = sysUserService.selectUserById(sessionId); - BigInteger expireTime = user.getExpireTime(); - - BigInteger currentTime = MyDateUtils.TimeSecond2MillSecond(System.currentTimeMillis()); - if (expireTime.subtract(currentTime).compareTo(BigInteger.valueOf(3600L)) > 0) { - user.setExpireTime(user.getExpireTime().add(new BigInteger(String.valueOf(30 * 1800)))); - sysUserService.updateUserSession(user); - } - } - - - - - if (null != user && null == SecurityUtils.getAuthentication()) - { - - UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null,null); - authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); - SecurityContextHolder.getContext().setAuthentication(authenticationToken); - } - - chain.doFilter(request, response); - } -} diff --git a/xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/JwtInterceptor.java b/xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/JwtInterceptor.java new file mode 100644 index 0000000..f323ce7 --- /dev/null +++ b/xymanager_service/src/main/java/com/shxy/xymanager_service/service/security/JwtInterceptor.java @@ -0,0 +1,94 @@ +package com.shxy.xymanager_service.service.security; + + +import cn.hutool.core.util.StrUtil; +import com.shxy.xymanager_common.annotation.JwtIgnore; +import com.shxy.xymanager_common.enums.HttpMethod; +import com.shxy.xymanager_common.exception.Asserts; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @ClassName:JwtAuthenticationTokenFilter + * @Description: token过滤器 验证token有效性. + * @Author: Arno_Fu + * @CreatTime:11/26/2019 - 6:34 PM + * @Version V1.0 + */ +@Component +@Slf4j +public class JwtInterceptor implements HandlerInterceptor { + + + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + // 忽略带JwtIgnore注解的请求, 不做后续token认证校验 + if (handler instanceof HandlerMethod) { + HandlerMethod handlerMethod = (HandlerMethod) handler; + JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class); + if (jwtIgnore != null) { + return true; + } + } + if (HttpMethod.GET.name().equals(request.getMethod())) { + response.setStatus(HttpServletResponse.SC_OK); + return true; + } + // 获取请求头信息authorization信息 + final String token = request.getHeader("token"); + if (StrUtil.isBlank(token)) { + log.info("token为空登录过期"); + Asserts.fail(401, "登录过期"); + } + return true; + } + + + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { + HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + HandlerInterceptor.super.afterCompletion(request, response, handler, ex); + } + + + /* @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { + UserSession user = null; + if(null!= request.getSession().getAttribute("sessionId")) { + String sessionId = request.getSession().getAttribute("sessionId").toString(); + user = sysUserService.selectUserById(sessionId); + BigInteger expireTime = user.getExpireTime(); + + BigInteger currentTime = MyDateUtils.TimeSecond2MillSecond(System.currentTimeMillis()); + if (expireTime.subtract(currentTime).compareTo(BigInteger.valueOf(3600L)) > 0) { + user.setExpireTime(user.getExpireTime().add(new BigInteger(String.valueOf(30 * 1800)))); + sysUserService.updateUserSession(user); + } + }*/ + + + + + /* if (null != user && null == SecurityUtils.getAuthentication()) + { + + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null,null); + authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + } + + chain.doFilter(request, response); + }*/ +}