This commit is contained in:
LuoYe_MyWork 2020-06-18 17:24:12 +08:00
parent a3b0e2a0e6
commit c6233f66cf
14 changed files with 251 additions and 123 deletions

21
pom.xml
View File

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version> <version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath/> <!-- lookup parent from repository -->
</parent> </parent>
<groupId>io.qyi</groupId> <groupId>io.qyi</groupId>
@ -35,16 +35,23 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<!-- log4j2 --> <!--排除自带的logging-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--log4j2-->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId> <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency> </dependency>
<!-- freemarker 模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--权限管理插件--> <!--权限管理插件-->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>

View File

@ -22,12 +22,13 @@ import java.util.Map;
public class RabbitMQConfig { public class RabbitMQConfig {
@Value("") @Value("")
private String DirectQueueName; private String DirectQueueName;
/** /**
* 处理死信队列的消费队列 * 处理死信队列的消费队列
* */ */
@Bean @Bean
public Queue fanoutQueue1() { public Queue fanoutQueue1() {
return new Queue("delay_queue1", true, false, false); return new Queue("delay_queue3", true, false, false);
} }
/** /**
@ -37,13 +38,14 @@ public class RabbitMQConfig {
* HeadersExchange 通过添加属性key-value匹配 * HeadersExchange 通过添加属性key-value匹配
* DirectExchange:按照routingkey分发到指定队列 * DirectExchange:按照routingkey分发到指定队列
* TopicExchange:多关键字匹配 * TopicExchange:多关键字匹配
*
* @return * @return
*/ */
@Bean @Bean
public CustomExchange customExchangeDelay() { public CustomExchange customExchangeDelay() {
Map<String, Object> arg = new HashMap<>(); Map<String, Object> arg = new HashMap<>();
arg.put("x-delayed-type", "direct"); arg.put("x-delayed-type", "direct");
return new CustomExchange("delay","x-delayed-message",true, false,arg); return new CustomExchange("delay3", "x-delayed-message", true, false, arg);
} }
/*@Bean /*@Bean
@ -54,7 +56,7 @@ public class RabbitMQConfig {
//绑定 将队列和交换机绑定, //绑定 将队列和交换机绑定,
@Bean @Bean
public Binding bindingFanoutQueue1() { public Binding bindingFanoutQueue1() {
return BindingBuilder.bind(fanoutQueue1()).to(customExchangeDelay()).with("delay").noargs(); return BindingBuilder.bind(fanoutQueue1()).to(customExchangeDelay()).with("delay3").noargs();
} }

View File

@ -0,0 +1,65 @@
package io.qyi.e5.config.security;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Iterator;
/**
* 决策管理器
*
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-06-15 16:11
**/
@Slf4j
@Service
public class MyAccessDecisionManager implements AccessDecisionManager {
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
if (collection == null) {
return;
}
System.out.println(o.toString()); // object is a URL.
log.info("object is a URL. {}", o.toString());
//所请求的资源拥有的权限(一个资源对多个权限)
Iterator<ConfigAttribute> iterator = collection.iterator();
while (iterator.hasNext()) {
ConfigAttribute configAttribute = iterator.next();
//访问所请求资源所需要的权限
String needPermission = configAttribute.getAttribute();
log.info("访问 " + o.toString() + " 需要的权限是:" + needPermission);
if (needPermission == null) {
break;
}
//用户所拥有的权限authentication
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority ga : authorities) {
if (needPermission.equals(ga.getAuthority())) {
return;
}
}
}
//没有权限
throw new AccessDeniedException(" 无权限! ");
}
@Override
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}

View File

@ -0,0 +1,68 @@
package io.qyi.e5.config.security;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-06-17 16:25
**/
@Service
public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {
private HashMap<String, Collection<ConfigAttribute>> map =null;
/**
* 加载权限表中所有权限
*/
public void loadResourceDefine(){
map = new HashMap<>();
Collection<ConfigAttribute> array;
ConfigAttribute cfg;
List<Map<String, String>> permissions = new LinkedList<>();
for(Map<String, String> permission : permissions) {
array = new ArrayList<>();
cfg = new SecurityConfig("ADMIN");
//此处只添加了用户的名字其实还可以添加更多权限的信息例如请求方法到ConfigAttribute的集合中去此处添加的信息将会作为MyAccessDecisionManager类的decide的第三个参数
array.add(cfg);
//用权限的getUrl() 作为map的key用ConfigAttribute的集合作为 value
map.put("/admin/test", array);
}
}
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
if(map ==null) loadResourceDefine();
//object 中包含用户请求的request 信息
HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
AntPathRequestMatcher matcher;
String resUrl;
for(Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
resUrl = iter.next();
matcher = new AntPathRequestMatcher(resUrl);
if(matcher.matches(request)) {
return map.get(resUrl);
}
}
return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> aClass) {
return false;
}
}

View File

@ -25,7 +25,7 @@ import java.util.Map;
* @create: 2019-12-27 08:57 * @create: 2019-12-27 08:57
**/ **/
@Component @Component
public class SecurityAuthenticationHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler , LogoutSuccessHandler { public class SecurityAuthenticationHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler , LogoutSuccessHandler {
@Override @Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
UsernamePasswordAuthenticationToken at = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); UsernamePasswordAuthenticationToken at = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
@ -35,6 +35,7 @@ public class SecurityAuthenticationHandler implements AuthenticationSuccessHandl
Map<String, String> token = new HashMap<>(); Map<String, String> token = new HashMap<>();
token.put("token", at.getToken()); token.put("token", at.getToken());
token.put("username", at.getName()); token.put("username", at.getName());
token.put("authority", at.getAuthority());
writer.write(gson.toJson(ResultUtil.success(token)) ); writer.write(gson.toJson(ResultUtil.success(token)) );
writer.flush(); writer.flush();
} }

View File

@ -1,14 +1,17 @@
package io.qyi.e5.config.security; package io.qyi.e5.config.security;
import io.qyi.e5.config.security.filter.LinkTokenAuthenticationFilter; import io.qyi.e5.config.security.filter.LinkTokenAuthenticationFilter;
import io.qyi.e5.service.security.SecurityUserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 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.core.context.SecurityContextHolder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/** /**
@ -24,56 +27,58 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired @Autowired
SecurityAuthenticationHandler securityAuthenticationHandler; SecurityAuthenticationHandler securityAuthenticationHandler;
@Autowired
private SecurityUserService securityUserService;
@Autowired @Autowired
UsernamePasswordAuthenticationConfig usernamePasswordAuthenticationConfig; UsernamePasswordAuthenticationConfig usernamePasswordAuthenticationConfig;
@Autowired
MyAccessDecisionManager myAccessDecisionManager;
@Autowired
MyInvocationSecurityMetadataSourceService myInvocationSecurityMetadataSourceService;
@Override @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { protected void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("AuthenticationManagerBuilder auth"); System.out.println("AuthenticationManagerBuilder auth");
// auth.userDetailsService(securityUserService).passwordEncoder(new BCryptPasswordEncoder());
// auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
// .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("user").and()
// .withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("USER", "ADMIN");
} }
// 通过重载该方法可配置如何通过拦截器保护请求 // 通过重载该方法可配置如何通过拦截器保护请求
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
System.out.println("HttpSecurity http"); System.out.println("HttpSecurity http");
http.addFilterBefore(new LinkTokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); /* http.authorizeRequests()
http.csrf().disable() .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
.apply(usernamePasswordAuthenticationConfig); @Override
public <O extends FilterSecurityInterceptor> O postProcess(O o) {
o.setSecurityMetadataSource(myInvocationSecurityMetadataSourceService);
o.setAccessDecisionManager(myAccessDecisionManager);
return o;
}
});*/
/*关闭创建session*/ /*关闭创建session*/
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests().antMatchers("/user/login", "/user/loginFrom", "/auth2/getGithubUrl").permitAll()// 指定相应的请求 不需要验证 // http.authorizeRequests().antMatchers("/user/login", "/user/loginFrom", "/auth2/getGithubUrl").permitAll()// 指定相应的请求 不需要验证
// .and() // .accessDecisionManager(myAccessDecisionManager)
// .authorizeRequests().antMatchers("/quartz/**").permitAll()//测试 http.authorizeRequests().anyRequest().authenticated().withObjectPostProcessor(filterSecurityInterceptorObjectPostProcessor());
.anyRequest()// 任何请求 http.addFilterBefore(new LinkTokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
.authenticated();// 都需要身份认证 /*自定义*/
http.csrf().disable().apply(usernamePasswordAuthenticationConfig);
//自定义过滤器
}
/**
* 自定义 FilterSecurityInterceptor ObjectPostProcessor 以替换默认配置达到动态权限的目的
* @return ObjectPostProcessor
*/
private ObjectPostProcessor<FilterSecurityInterceptor> filterSecurityInterceptorObjectPostProcessor() {
return new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object) {
object.setAccessDecisionManager(myAccessDecisionManager);
object.setSecurityMetadataSource(myInvocationSecurityMetadataSourceService);
return object;
}
};
} }
/*@Bean
public LinkTokenAuthenticationFilter linkTokenAuthenticationFilter (){
return new LinkTokenAuthenticationFilter();
}*/
/*@Bean
public AccessDeniedHandler getAccessDeniedHandler() {
return new RestAuthenticationAccessDeniedHandler();
}*/
/* @Override
public void configure(WebSecurity web) {
System.out.println("WebSecurity web");
String antPatterns = "/pdfjs-2.1.266/**,/favicon.ico,/css/**,/js/**,/ico/**,/images/**,/jquery-1.12.4/**,/uuid-1.4/**,/layui-2.4.5/**,/jquery-easyui-1.6.11/**,/zTree-3.5.33/**,/select2-4.0.5/**,/greensock-js-1.20.5/**";
web.ignoring().antMatchers(antPatterns.split(","));
}*/
} }

View File

@ -1,12 +1,15 @@
package io.qyi.e5.config.security; package io.qyi.e5.config.security;
import io.qyi.e5.config.security.filter.LinkTokenAuthenticationFilter;
import io.qyi.e5.config.security.filter.LoginAuthenticationFilter; import io.qyi.e5.config.security.filter.LoginAuthenticationFilter;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter; import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -25,10 +28,12 @@ public class UsernamePasswordAuthenticationConfig extends SecurityConfigurerAdap
@Autowired @Autowired
SecurityAuthenticationHandler securityAuthenticationHandler; SecurityAuthenticationHandler securityAuthenticationHandler;
@Override @Override
public void configure(HttpSecurity http) throws Exception { public void configure(HttpSecurity http) throws Exception {
LoginAuthenticationFilter authenticationFilter = new LoginAuthenticationFilter(); LoginAuthenticationFilter authenticationFilter = new LoginAuthenticationFilter();
logger.info("自定义用户认证处理逻辑"); logger.info("自定义用户认证处理逻辑");
// 自定义用户认证处理逻辑时需要指定AuthenticationManager否则无法认证 // 自定义用户认证处理逻辑时需要指定AuthenticationManager否则无法认证
authenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); authenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
@ -36,12 +41,11 @@ public class UsernamePasswordAuthenticationConfig extends SecurityConfigurerAdap
// 指定自定义的认证成功和失败的处理器 // 指定自定义的认证成功和失败的处理器
authenticationFilter.setAuthenticationSuccessHandler(securityAuthenticationHandler); authenticationFilter.setAuthenticationSuccessHandler(securityAuthenticationHandler);
authenticationFilter.setAuthenticationFailureHandler(securityAuthenticationHandler); authenticationFilter.setAuthenticationFailureHandler(securityAuthenticationHandler);
// 把自定义的用户名密码认证过滤器和处理器添加到UsernamePasswordAuthenticationFilter过滤器之前 // 把自定义的用户名密码认证过滤器和处理器添加到UsernamePasswordAuthenticationFilter过滤器之前
http.authenticationProvider(usernamePasswordAuthenticationProvider) http.authenticationProvider(usernamePasswordAuthenticationProvider)
.addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class); .addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);
} }
} }

View File

@ -41,11 +41,13 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
@Value("${isdebug}") @Value("${isdebug}")
boolean isDebug; boolean isDebug;
@Value("${user.admin.githubId}")
int adminGithubId;
@Autowired @Autowired
RedisUtil redisUtil; RedisUtil redisUtil;
@Autowired @Autowired
IGithubService githubService; IGithubService githubService;
@ -59,15 +61,17 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
String state = authenticationToken.getState(); String state = authenticationToken.getState();
logger.info("Github 认证: code{} state{} Token", code, state); logger.info("Github 认证: code{} state{} Token", code, state);
Map<String, Object> userInfo_redis = new HashMap<>(); Map<String, Object> userInfo_redis = new HashMap<>();
/*是否调试模式*/ /*是否调试模式*/
if (isDebug) { if (isDebug) {
String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString()); String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString());
UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken("debugName", UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken("debugName",
"DebugAvatar", 19658189,token, AuthorityUtils.createAuthorityList("user")); "DebugAvatar", adminGithubId, token, "ADMIN", AuthorityUtils.createAuthorityList("ROLE_ADMIN1"));
authenticationToken1.setDetails(authenticationToken); authenticationToken1.setDetails(authenticationToken);
userInfo_redis.put("github_name", "debug"); userInfo_redis.put("github_name", "debug");
userInfo_redis.put("github_id", 19658189); userInfo_redis.put("github_id", adminGithubId);
userInfo_redis.put("avatar_url", "https://www.baidu.com"); userInfo_redis.put("avatar_url", "https://www.baidu.com");
userInfo_redis.put("authority","ROLE_ADMIN1");
redisUtil.hmset(token_ + token, userInfo_redis, 3600); redisUtil.hmset(token_ + token, userInfo_redis, 3600);
return authenticationToken1; return authenticationToken1;
} }
@ -105,16 +109,23 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
} }
String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString()); String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString());
/*配置角色*/
String Authority = "ROLE_user";
if (adminGithubId == github.getGithubId()) {
Authority = "ROLE_admin";
}
/*写token信息到redis*/ /*写token信息到redis*/
userInfo_redis.put("github_name", github.getName()); userInfo_redis.put("github_name", github.getName());
userInfo_redis.put("github_id", github.getGithubId()); userInfo_redis.put("github_id", github.getGithubId());
userInfo_redis.put("avatar_url", github.getAvatarUrl()); userInfo_redis.put("avatar_url", github.getAvatarUrl());
userInfo_redis.put("authority",Authority);
redisUtil.hmset(token_ + token, userInfo_redis, 3600); redisUtil.hmset(token_ + token, userInfo_redis, 3600);
// 创建一个已认证的token // 创建一个已认证的token
UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken(github.getName(), UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken(github.getName(),
github.getAvatarUrl(), github.getGithubId(), token, AuthorityUtils.createAuthorityList("user")); github.getAvatarUrl(), github.getGithubId(), token, Authority, AuthorityUtils.createAuthorityList(Authority));
// 设置一些详细信息 // 设置一些详细信息
authenticationToken1.setDetails(authenticationToken); authenticationToken1.setDetails(authenticationToken);

View File

@ -29,6 +29,8 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
private String Token; private String Token;
private String Authority;
private int github_id; private int github_id;
// 创建未认证的用户名密码认证对象 // 创建未认证的用户名密码认证对象
@ -55,21 +57,23 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
// 创建已认证的用户密码认证对象 // 创建已认证的用户密码认证对象
public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id, Collection<? extends GrantedAuthority> authorities) { public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id,String Authority, Collection<? extends GrantedAuthority> authorities) {
super(authorities); super(authorities);
this.name = name; this.name = name;
this.avatar_url = avatar_url; this.avatar_url = avatar_url;
this.github_id = github_id; this.github_id = github_id;
this.Authority = Authority;
super.setAuthenticated(true); super.setAuthenticated(true);
} }
// 创建已认证的用户密码认证对象 // 创建已认证的用户密码认证对象
public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id, String token, Collection<? extends GrantedAuthority> authorities) { public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id, String token, String Authority, Collection<? extends GrantedAuthority> authorities) {
super(authorities); super(authorities);
this.name = name; this.name = name;
this.avatar_url = avatar_url; this.avatar_url = avatar_url;
this.github_id = github_id; this.github_id = github_id;
this.Token = token; this.Token = token;
this.Authority = Authority;
super.setAuthenticated(true); super.setAuthenticated(true);
} }
@ -132,4 +136,12 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT
public void setGithub_id(int github_id) { public void setGithub_id(int github_id) {
this.github_id = github_id; this.github_id = github_id;
} }
public String getAuthority() {
return Authority;
}
public void setAuthority(String authority) {
Authority = authority;
}
} }

View File

@ -1,16 +1,14 @@
package io.qyi.e5.config.security.filter; package io.qyi.e5.config.security.filter;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.qyi.e5.config.security.UsernamePasswordAuthenticationToken; import io.qyi.e5.config.security.UsernamePasswordAuthenticationToken;
import io.qyi.e5.util.SpringUtil; import io.qyi.e5.util.SpringUtil;
import io.qyi.e5.util.redis.RedisUtil; import io.qyi.e5.util.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;
@ -18,7 +16,6 @@ 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;
import java.io.PrintWriter;
import java.util.Map; import java.util.Map;
/** /**
@ -31,20 +28,19 @@ import java.util.Map;
**/ **/
public class LinkTokenAuthenticationFilter extends OncePerRequestFilter { public class LinkTokenAuthenticationFilter extends OncePerRequestFilter {
@Override @Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String token = httpServletRequest.getHeader("token"); String token = httpServletRequest.getHeader("token");
if (token != null) { if (token != null) {
RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class); RedisUtil RedisUtil = SpringUtil.getBean(RedisUtil.class);
if (redisUtil.hasKey("token:" + token)) { if (RedisUtil.hasKey("token:" + token)) {
Map<Object, Object> userInfo = redisUtil.hmget("token:" + token); Map<Object, Object> userInfo = RedisUtil.hmget("token:" + token);
// 将未认证的Authentication转换成自定义的用户认证Token // 将未认证的Authentication转换成自定义的用户认证Token
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken();
UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken(userInfo.get("github_name") == null ? "" : userInfo.get("github_name").toString(), UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken(userInfo.get("github_name") == null ? "" : userInfo.get("github_name").toString(),
userInfo.get("avatar_url").toString(), (int) userInfo.get("github_id"), AuthorityUtils.createAuthorityList("user")); userInfo.get("avatar_url").toString(), (int) userInfo.get("github_id"), userInfo.get("authority").toString(), AuthorityUtils.createAuthorityList("user"));
authenticationToken1.setDetails(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authenticationToken1); SecurityContextHolder.getContext().setAuthentication(authenticationToken1);
System.out.println("完成授权"); System.out.println("完成授权,角色:" + userInfo.get("authority").toString());
} }
} }
System.out.println("--------------Token鉴权---------------"); System.out.println("--------------Token鉴权---------------");
@ -63,12 +59,4 @@ public class LinkTokenAuthenticationFilter extends OncePerRequestFilter {
} }
} }
public void sendJson(HttpServletResponse httpServletResponse, Object o) throws IOException {
Gson gson = new Gson();
String s = gson.toJson(o);
PrintWriter writer = httpServletResponse.getWriter();
writer.write(s);
writer.flush();
}
} }

View File

@ -1,4 +1,4 @@
package io.qyi.e5.controller; package io.qyi.e5.controller.admin;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -10,8 +10,12 @@ import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData; import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.UUID; import java.util.UUID;
@ -22,8 +26,8 @@ import java.util.UUID;
* @author: 落叶随风 * @author: 落叶随风
* @create: 2020-03-16 01:01 * @create: 2020-03-16 01:01
**/ **/
@Controller
@RestController @RestController
@RequestMapping("/admin")
public class TestController { public class TestController {
@Autowired @Autowired
RabbitTemplate rabbitTemplate; RabbitTemplate rabbitTemplate;
@ -53,6 +57,12 @@ public class TestController {
return "ok"; return "ok";
} }
@GetMapping("/test")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String test() {
return "ok";
}
} }

View File

@ -1,11 +1,6 @@
package io.qyi.e5.service.rabbitMQ.impl; package io.qyi.e5.service.rabbitMQ.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.rabbitmq.client.Channel; import com.rabbitmq.client.Channel;
import io.qyi.e5.outlook.entity.Outlook;
import io.qyi.e5.outlook.service.IOutlookService; import io.qyi.e5.outlook.service.IOutlookService;
import io.qyi.e5.service.task.ITask; import io.qyi.e5.service.task.ITask;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -17,7 +12,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Type;
/** /**
* @program: msgpush * @program: msgpush
@ -35,7 +29,7 @@ public class ListenerImpl {
ITask Task; ITask Task;
@RabbitHandler @RabbitHandler
@RabbitListener(queues = "delay_queue1", containerFactory = "rabbitListenerContainerFactory") @RabbitListener(queues = "delay_queue3", containerFactory = "rabbitListenerContainerFactory")
public void listen(Message message, Channel channel) throws IOException { public void listen(Message message, Channel channel) throws IOException {
logger.info("消费者1开始处理消息 {},时间戳:{}" ,message,System.currentTimeMillis()); logger.info("消费者1开始处理消息 {},时间戳:{}" ,message,System.currentTimeMillis());
System.out.println("消费者1开始处理消息"+System.currentTimeMillis()); System.out.println("消费者1开始处理消息"+System.currentTimeMillis());

View File

@ -1,39 +0,0 @@
package io.qyi.e5.service.security;
import io.qyi.e5.user.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/**
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-02-26 21:38
**/
@Component
public class SecurityUserService implements UserDetailsService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String encode = bCryptPasswordEncoder.encode("123");
String encodePasswd = encode;
logger.info("登录用户名: {} , 密码:{}",s,encodePasswd);
UserDetails userDetails = new User(s, encode, AuthorityUtils.createAuthorityList("admin"));
return userDetails;
}
}

View File

@ -4,7 +4,7 @@
<!--Configuration后面的status这个用于设置log4j2自身内部的信息输出可以不设置 <!--Configuration后面的status这个用于设置log4j2自身内部的信息输出可以不设置
当设置成trace时会看到log4j2内部各种详细输出--> 当设置成trace时会看到log4j2内部各种详细输出-->
<!--monitorIntervalLog4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数--> <!--monitorIntervalLog4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<configuration status="DEBUG" monitorInterval="5"> <configuration status="INFO" monitorInterval="5">
<Properties> <Properties>
<!-- 日志模板 --> <!-- 日志模板 -->
<Property name="log_pattern" value="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Property name="log_pattern" value="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>