Conflicts:
	xymanager_admin/src/main/java/com/shxy/xymanager_admin/controller/TestController.java
master
liuguijing 2 years ago
commit 4134ba9ef0

@ -31,6 +31,10 @@
<artifactId>jjwt</artifactId> <artifactId>jjwt</artifactId>
<version>0.9.0</version> <version>0.9.0</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies> </dependencies>
<!-- <build>--> <!-- <build>-->
<!-- <plugins>--> <!-- <plugins>-->

@ -1,113 +1,47 @@
package com.shxy.xymanager_service.service.security; 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.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod; 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.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
@EnableWebSecurity// 这个注解必须加开启Security public class CustomSecurityConfig implements WebMvcConfigurer {
@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;
private final JwtInterceptor jwtInterceptor;
public CustomSecurityConfig(JwtInterceptor jwtInterceptor) {
//先来这里认证一下 this.jwtInterceptor = jwtInterceptor;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
log.info("213123123");
auth.userDetailsService(customUserDetailsServiceImpl).passwordEncoder(passwordEncoderBean());
} }
//拦截在这配
@Override @Override
protected void configure(HttpSecurity httpSecurity) throws Exception { public void addInterceptors(InterceptorRegistry registry) {
log.info("123566"); registry.addInterceptor(this.jwtInterceptor).addPathPatterns("/getXcxMainInfo").addPathPatterns("/authorizeXcxLogin")
httpSecurity .addPathPatterns("/bindXcxDevice")
// 认证失败处理类 .excludePathPatterns("/login")
.exceptionHandling().authenticationEntryPoint(customAuthExceptionEntryPoint).and() .excludePathPatterns("/api/addUser")
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and() .excludePathPatterns("/swagger-ui.html")
// 过滤请求 .excludePathPatterns("/swagger-resources/**")
.authorizeRequests() .excludePathPatterns("/*/api-docs")
// 对于登录login 验证码captchaImage 允许匿名访问 .excludePathPatterns("/error")
.antMatchers("/login", "/captchaImage").anonymous() .excludePathPatterns("/test/**")
.antMatchers("*/api/addUser").anonymous() .excludePathPatterns("/loginXcxuser")
.antMatchers("**/addUser").anonymous() .excludePathPatterns("/loginXcxuser")
.antMatchers("/addUser").anonymous() .excludePathPatterns("/addUser");
.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();
} }
@Bean
@Override @Override
public AuthenticationManager authenticationManagerBean() throws Exception { public void addCorsMappings(CorsRegistry registry) {
return super.authenticationManagerBean(); registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(false);
} }
} }

@ -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;
/**
* @ClassNameJwtAuthenticationTokenFilter
* @Description token token.
* @Author Arno_Fu
* @CreatTime11/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);
}
}

@ -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;
/**
* @ClassNameJwtAuthenticationTokenFilter
* @Description token token.
* @Author Arno_Fu
* @CreatTime11/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);
}*/
}
Loading…
Cancel
Save