feat:客户端和服务端新增是否鉴权开关

pull/749/head
baymax55 3 years ago
parent c0f0cbd14a
commit 12424fd47f

@ -22,6 +22,7 @@ import cn.hippo4j.auth.filter.JWTAuthenticationFilter;
import cn.hippo4j.auth.filter.JWTAuthorizationFilter; import cn.hippo4j.auth.filter.JWTAuthorizationFilter;
import cn.hippo4j.auth.security.JwtTokenManager; import cn.hippo4j.auth.security.JwtTokenManager;
import cn.hippo4j.auth.service.impl.UserDetailsServiceImpl; import cn.hippo4j.auth.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
@ -50,6 +51,8 @@ import java.util.stream.Stream;
@EnableGlobalMethodSecurity(prePostEnabled = true) @EnableGlobalMethodSecurity(prePostEnabled = true)
public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter { public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${spring.dynamic.thread-pool.enableAuthentication:true}")
private Boolean enableAuthentication;
@Resource @Resource
private UserDetailsService userDetailsService; private UserDetailsService userDetailsService;
@ -93,11 +96,14 @@ public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter {
.authorizeRequests() .authorizeRequests()
.antMatchers("/static/**", "/index.html", "/favicon.ico", "/avatar.jpg").permitAll() .antMatchers("/static/**", "/index.html", "/favicon.ico", "/avatar.jpg").permitAll()
.antMatchers("/doc.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs").anonymous() .antMatchers("/doc.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs").anonymous()
.anyRequest().authenticated() // .anyRequest().authenticated()
.and() .and()
.addFilter(new JWTAuthenticationFilter(authenticationManager())) .addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(tokenManager, authenticationManager())) .addFilter(new JWTAuthorizationFilter(tokenManager, authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
disableAuthenticationIfNeeded(http);
http.authorizeRequests().anyRequest().authenticated();
} }
@Override @Override
@ -105,4 +111,11 @@ public class GlobalSecurityConfig extends WebSecurityConfigurerAdapter {
String[] ignores = Stream.of("/hippo4j/v1/cs/auth/users/apply/token/**").toArray(String[]::new); String[] ignores = Stream.of("/hippo4j/v1/cs/auth/users/apply/token/**").toArray(String[]::new);
web.ignoring().antMatchers(ignores); web.ignoring().antMatchers(ignores);
} }
private void disableAuthenticationIfNeeded(HttpSecurity http) throws Exception {
if (Boolean.FALSE.equals(enableAuthentication)) {
http.authorizeRequests().antMatchers("/hippo4j/v1/cs/**").permitAll();
}
}
} }

@ -34,7 +34,6 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
@ -69,6 +68,7 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte
Authentication authenticate = null; Authentication authenticate = null;
try { try {
LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class); LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
request.setAttribute("loginUser", loginUser);
rememberMe.set(loginUser.getRememberMe()); rememberMe.set(loginUser.getRememberMe());
authenticate = authenticationManager.authenticate( authenticate = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList())); new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList()));

@ -20,14 +20,22 @@ package cn.hippo4j.auth.service.impl;
import cn.hippo4j.auth.mapper.UserMapper; import cn.hippo4j.auth.mapper.UserMapper;
import cn.hippo4j.auth.model.UserInfo; import cn.hippo4j.auth.model.UserInfo;
import cn.hippo4j.auth.model.biz.user.JwtUser; import cn.hippo4j.auth.model.biz.user.JwtUser;
import cn.hippo4j.auth.model.biz.user.LoginUser;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections; import java.util.Collections;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
@ -41,8 +49,16 @@ public class UserDetailsServiceImpl implements UserDetailsService {
@Resource @Resource
private UserMapper userMapper; private UserMapper userMapper;
@Value("${spring.dynamic.thread-pool.enableAuthentication:true}")
private Boolean enableAuthentication;
@Override @Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
JwtUser anonymous = dealWithAnonymous();
if (ObjectUtil.isNotNull(anonymous)) {
return anonymous;
}
UserInfo userInfo = userMapper.selectOne(Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUserName, userName)); UserInfo userInfo = userMapper.selectOne(Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUserName, userName));
if (Objects.isNull(userInfo)) { if (Objects.isNull(userInfo)) {
log.warn("User {} not found", userName); log.warn("User {} not found", userName);
@ -56,4 +72,27 @@ public class UserDetailsServiceImpl implements UserDetailsService {
jwtUser.setAuthorities(authorities); jwtUser.setAuthorities(authorities);
return jwtUser; return jwtUser;
} }
private JwtUser dealWithAnonymous() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return null;
}
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
LoginUser loginUser = (LoginUser) request.getAttribute("loginUser");
if (ObjectUtil.isNull(loginUser)) {
return null;
}
if (Boolean.FALSE.equals(enableAuthentication)) {
JwtUser jwtUser = new JwtUser();
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
jwtUser.setId(1L);
jwtUser.setUsername("anonymous");
jwtUser.setPassword(bCryptPasswordEncoder.encode(loginUser.getPassword()));
Set<SimpleGrantedAuthority> authorities = Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN"));
jwtUser.setAuthorities(authorities);
return jwtUser;
}
return null;
}
} }

@ -31,6 +31,10 @@ public interface BootstrapPropertiesInterface {
return null; return null;
} }
default Boolean getEnableAuthentication() {
return null;
}
/** /**
* Get username. * Get username.
* *

@ -41,7 +41,7 @@ public class BeforeCheckConfiguration {
public BeforeCheckConfiguration.BeforeCheck dynamicThreadPoolBeforeCheckBean(@Autowired(required = false) BootstrapPropertiesInterface properties, public BeforeCheckConfiguration.BeforeCheck dynamicThreadPoolBeforeCheckBean(@Autowired(required = false) BootstrapPropertiesInterface properties,
ConfigurableEnvironment environment) { ConfigurableEnvironment environment) {
boolean checkFlag = properties != null && Objects.equals(bootstrapPropertiesClassName, properties.getClass().getName()) && properties.getEnable(); boolean checkFlag = properties != null && Objects.equals(bootstrapPropertiesClassName, properties.getClass().getName()) && properties.getEnable();
if (checkFlag) { if (checkFlag && Boolean.TRUE.equals(properties.getEnableAuthentication())) {
String username = properties.getUsername(); String username = properties.getUsername();
if (StringUtil.isBlank(username)) { if (StringUtil.isBlank(username)) {
throw new ConfigEmptyException( throw new ConfigEmptyException(

@ -17,6 +17,7 @@ spring.dynamic.thread-pool.namespace=prescription
spring.dynamic.thread-pool.item-id=dynamic-threadpool-example spring.dynamic.thread-pool.item-id=dynamic-threadpool-example
spring.dynamic.thread-pool.username=admin spring.dynamic.thread-pool.username=admin
spring.dynamic.thread-pool.password=123456 spring.dynamic.thread-pool.password=123456
spring.dynamic.thread-pool.enableAuthentication=true
# Enable server and micrometer monitoring at the same time # Enable server and micrometer monitoring at the same time
spring.dynamic.thread-pool.collect-type=server,micrometer spring.dynamic.thread-pool.collect-type=server,micrometer

@ -53,3 +53,5 @@ mybatis-plus.global-config.banner=false
mybatis-plus.global-config.db-config.logic-delete-field=delFlag mybatis-plus.global-config.db-config.logic-delete-field=delFlag
mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0 mybatis-plus.global-config.db-config.logic-not-delete-value=0
spring.dynamic.thread-pool.enableAuthentication=true

@ -103,4 +103,9 @@ public class BootstrapProperties implements BootstrapPropertiesInterface {
* Time interval for client to collect monitoring data. unit: ms * Time interval for client to collect monitoring data. unit: ms
*/ */
private Long collectInterval = 5000L; private Long collectInterval = 5000L;
/**
* Whether to enable authentication
*/
private Boolean enableAuthentication = true;
} }

@ -53,9 +53,12 @@ public class SecurityProxy {
private long tokenRefreshWindow; private long tokenRefreshWindow;
private boolean enableAuthentication;
public SecurityProxy(HttpClientUtil httpClientUtil, BootstrapProperties properties) { public SecurityProxy(HttpClientUtil httpClientUtil, BootstrapProperties properties) {
username = properties.getUsername(); username = properties.getUsername();
password = properties.getPassword(); password = properties.getPassword();
enableAuthentication = properties.getEnableAuthentication();
this.httpClientUtil = httpClientUtil; this.httpClientUtil = httpClientUtil;
} }
@ -65,6 +68,9 @@ public class SecurityProxy {
return true; return true;
} }
for (String server : servers) { for (String server : servers) {
if (!enableAuthentication) {
return true;
}
if (applyToken(server)) { if (applyToken(server)) {
lastRefreshTime = System.currentTimeMillis(); lastRefreshTime = System.currentTimeMillis();
return true; return true;

Loading…
Cancel
Save