From c6233f66cffbc0008660a8ddcae4adfcec9c60c3 Mon Sep 17 00:00:00 2001 From: LuoYe_MyWork Date: Thu, 18 Jun 2020 17:24:12 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A4=87=E4=BB=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 21 ++++-- .../e5/config/rabbitMQ/RabbitMQConfig.java | 10 ++- .../security/MyAccessDecisionManager.java | 65 +++++++++++++++++ ...vocationSecurityMetadataSourceService.java | 68 +++++++++++++++++ .../SecurityAuthenticationHandler.java | 3 +- .../e5/config/security/SecurityConfig.java | 73 ++++++++++--------- .../UsernamePasswordAuthenticationConfig.java | 8 +- ...sernamePasswordAuthenticationProvider.java | 19 ++++- .../UsernamePasswordAuthenticationToken.java | 16 +++- .../filter/LinkTokenAuthenticationFilter.java | 28 ++----- .../{ => admin}/TestController.java | 14 +++- .../service/rabbitMQ/impl/ListenerImpl.java | 8 +- .../service/security/SecurityUserService.java | 39 ---------- src/main/resources/log4j2.xml | 2 +- 14 files changed, 251 insertions(+), 123 deletions(-) create mode 100644 src/main/java/io/qyi/e5/config/security/MyAccessDecisionManager.java create mode 100644 src/main/java/io/qyi/e5/config/security/MyInvocationSecurityMetadataSourceService.java rename src/main/java/io/qyi/e5/controller/{ => admin}/TestController.java (74%) delete mode 100644 src/main/java/io/qyi/e5/service/security/SecurityUserService.java diff --git a/pom.xml b/pom.xml index 46ef961..31261bd 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 2.2.4.RELEASE + 2.3.1.RELEASE io.qyi @@ -35,16 +35,23 @@ - + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot spring-boot-starter-log4j2 - - - org.springframework.boot - spring-boot-starter-freemarker - org.springframework.boot diff --git a/src/main/java/io/qyi/e5/config/rabbitMQ/RabbitMQConfig.java b/src/main/java/io/qyi/e5/config/rabbitMQ/RabbitMQConfig.java index d52bc61..e332096 100644 --- a/src/main/java/io/qyi/e5/config/rabbitMQ/RabbitMQConfig.java +++ b/src/main/java/io/qyi/e5/config/rabbitMQ/RabbitMQConfig.java @@ -22,12 +22,13 @@ import java.util.Map; public class RabbitMQConfig { @Value("") private String DirectQueueName; + /** * 处理死信队列的消费队列 - * */ + */ @Bean 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匹配 * DirectExchange:按照routingkey分发到指定队列 * TopicExchange:多关键字匹配 + * * @return */ @Bean public CustomExchange customExchangeDelay() { Map arg = new HashMap<>(); 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 @@ -54,7 +56,7 @@ public class RabbitMQConfig { //绑定 将队列和交换机绑定, @Bean public Binding bindingFanoutQueue1() { - return BindingBuilder.bind(fanoutQueue1()).to(customExchangeDelay()).with("delay").noargs(); + return BindingBuilder.bind(fanoutQueue1()).to(customExchangeDelay()).with("delay3").noargs(); } diff --git a/src/main/java/io/qyi/e5/config/security/MyAccessDecisionManager.java b/src/main/java/io/qyi/e5/config/security/MyAccessDecisionManager.java new file mode 100644 index 0000000..2df3486 --- /dev/null +++ b/src/main/java/io/qyi/e5/config/security/MyAccessDecisionManager.java @@ -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 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 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 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; + } +} diff --git a/src/main/java/io/qyi/e5/config/security/MyInvocationSecurityMetadataSourceService.java b/src/main/java/io/qyi/e5/config/security/MyInvocationSecurityMetadataSourceService.java new file mode 100644 index 0000000..fc16cc7 --- /dev/null +++ b/src/main/java/io/qyi/e5/config/security/MyInvocationSecurityMetadataSourceService.java @@ -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> map =null; + /** + * 加载权限表中所有权限 + */ + public void loadResourceDefine(){ + map = new HashMap<>(); + Collection array; + ConfigAttribute cfg; + List> permissions = new LinkedList<>(); + for(Map 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 getAttributes(Object o) throws IllegalArgumentException { + if(map ==null) loadResourceDefine(); + //object 中包含用户请求的request 信息 + HttpServletRequest request = ((FilterInvocation) o).getHttpRequest(); + AntPathRequestMatcher matcher; + String resUrl; + for(Iterator 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 getAllConfigAttributes() { + return null; + } + + @Override + public boolean supports(Class aClass) { + return false; + } +} diff --git a/src/main/java/io/qyi/e5/config/security/SecurityAuthenticationHandler.java b/src/main/java/io/qyi/e5/config/security/SecurityAuthenticationHandler.java index 48cd992..bf6aba0 100644 --- a/src/main/java/io/qyi/e5/config/security/SecurityAuthenticationHandler.java +++ b/src/main/java/io/qyi/e5/config/security/SecurityAuthenticationHandler.java @@ -25,7 +25,7 @@ import java.util.Map; * @create: 2019-12-27 08:57 **/ @Component -public class SecurityAuthenticationHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler , LogoutSuccessHandler { +public class SecurityAuthenticationHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler , LogoutSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { UsernamePasswordAuthenticationToken at = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); @@ -35,6 +35,7 @@ public class SecurityAuthenticationHandler implements AuthenticationSuccessHandl Map token = new HashMap<>(); token.put("token", at.getToken()); token.put("username", at.getName()); + token.put("authority", at.getAuthority()); writer.write(gson.toJson(ResultUtil.success(token)) ); writer.flush(); } diff --git a/src/main/java/io/qyi/e5/config/security/SecurityConfig.java b/src/main/java/io/qyi/e5/config/security/SecurityConfig.java index 592bba4..a93ec9f 100644 --- a/src/main/java/io/qyi/e5/config/security/SecurityConfig.java +++ b/src/main/java/io/qyi/e5/config/security/SecurityConfig.java @@ -1,14 +1,17 @@ package io.qyi.e5.config.security; 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.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.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.core.context.SecurityContextHolder; +import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** @@ -24,56 +27,58 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired SecurityAuthenticationHandler securityAuthenticationHandler; - @Autowired - private SecurityUserService securityUserService; @Autowired UsernamePasswordAuthenticationConfig usernamePasswordAuthenticationConfig; + @Autowired + MyAccessDecisionManager myAccessDecisionManager; + + @Autowired + MyInvocationSecurityMetadataSourceService myInvocationSecurityMetadataSourceService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { 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 protected void configure(HttpSecurity http) throws Exception { System.out.println("HttpSecurity http"); - http.addFilterBefore(new LinkTokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); - http.csrf().disable() - .apply(usernamePasswordAuthenticationConfig); + /* http.authorizeRequests() + .withObjectPostProcessor(new ObjectPostProcessor() { + @Override + public O postProcess(O o) { + o.setSecurityMetadataSource(myInvocationSecurityMetadataSourceService); + o.setAccessDecisionManager(myAccessDecisionManager); + return o; + } + });*/ /*关闭创建session*/ http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); - http.authorizeRequests().antMatchers("/user/login", "/user/loginFrom", "/auth2/getGithubUrl").permitAll()// 指定相应的请求 不需要验证 -// .and() -// .authorizeRequests().antMatchers("/quartz/**").permitAll()//测试 - .anyRequest()// 任何请求 - .authenticated();// 都需要身份认证 - - +// http.authorizeRequests().antMatchers("/user/login", "/user/loginFrom", "/auth2/getGithubUrl").permitAll()// 指定相应的请求 不需要验证 +// .accessDecisionManager(myAccessDecisionManager) + http.authorizeRequests().anyRequest().authenticated().withObjectPostProcessor(filterSecurityInterceptorObjectPostProcessor()); + http.addFilterBefore(new LinkTokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); + /*自定义*/ + http.csrf().disable().apply(usernamePasswordAuthenticationConfig); + //自定义过滤器 + } + /** + * 自定义 FilterSecurityInterceptor ObjectPostProcessor 以替换默认配置达到动态权限的目的 + * @return ObjectPostProcessor + */ + private ObjectPostProcessor filterSecurityInterceptorObjectPostProcessor() { + return new ObjectPostProcessor() { + @Override + public 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(",")); - }*/ - } diff --git a/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationConfig.java b/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationConfig.java index 7d03b8c..27beae0 100644 --- a/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationConfig.java +++ b/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationConfig.java @@ -1,12 +1,15 @@ package io.qyi.e5.config.security; +import io.qyi.e5.config.security.filter.LinkTokenAuthenticationFilter; import io.qyi.e5.config.security.filter.LoginAuthenticationFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.SecurityConfigurerAdapter; 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.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.stereotype.Component; @@ -25,10 +28,12 @@ public class UsernamePasswordAuthenticationConfig extends SecurityConfigurerAdap @Autowired SecurityAuthenticationHandler securityAuthenticationHandler; + @Override public void configure(HttpSecurity http) throws Exception { LoginAuthenticationFilter authenticationFilter = new LoginAuthenticationFilter(); + logger.info("自定义用户认证处理逻辑"); // 自定义用户认证处理逻辑时,需要指定AuthenticationManager,否则无法认证 authenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); @@ -36,12 +41,11 @@ public class UsernamePasswordAuthenticationConfig extends SecurityConfigurerAdap // 指定自定义的认证成功和失败的处理器 authenticationFilter.setAuthenticationSuccessHandler(securityAuthenticationHandler); authenticationFilter.setAuthenticationFailureHandler(securityAuthenticationHandler); - // 把自定义的用户名密码认证过滤器和处理器添加到UsernamePasswordAuthenticationFilter过滤器之前 http.authenticationProvider(usernamePasswordAuthenticationProvider) .addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class); - } + } diff --git a/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationProvider.java b/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationProvider.java index 8698e7a..accc5c6 100644 --- a/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationProvider.java +++ b/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationProvider.java @@ -41,11 +41,13 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro @Value("${isdebug}") boolean isDebug; + @Value("${user.admin.githubId}") + int adminGithubId; + @Autowired RedisUtil redisUtil; - @Autowired IGithubService githubService; @@ -59,15 +61,17 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro String state = authenticationToken.getState(); logger.info("Github 认证: code:{} state:{} Token:", code, state); Map userInfo_redis = new HashMap<>(); + /*是否调试模式*/ if (isDebug) { String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString()); UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken("debugName", - "DebugAvatar", 19658189,token, AuthorityUtils.createAuthorityList("user")); + "DebugAvatar", adminGithubId, token, "ADMIN", AuthorityUtils.createAuthorityList("ROLE_ADMIN1")); authenticationToken1.setDetails(authenticationToken); 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("authority","ROLE_ADMIN1"); redisUtil.hmset(token_ + token, userInfo_redis, 3600); return authenticationToken1; } @@ -105,16 +109,23 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro } String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString()); + /*配置角色*/ + String Authority = "ROLE_user"; + if (adminGithubId == github.getGithubId()) { + Authority = "ROLE_admin"; + } /*写token信息到redis*/ userInfo_redis.put("github_name", github.getName()); userInfo_redis.put("github_id", github.getGithubId()); userInfo_redis.put("avatar_url", github.getAvatarUrl()); + userInfo_redis.put("authority",Authority); redisUtil.hmset(token_ + token, userInfo_redis, 3600); + // 创建一个已认证的token 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); diff --git a/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationToken.java b/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationToken.java index 2417f0a..e96a41f 100644 --- a/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationToken.java +++ b/src/main/java/io/qyi/e5/config/security/UsernamePasswordAuthenticationToken.java @@ -29,6 +29,8 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT private String Token; + private String Authority; + private int github_id; // 创建未认证的用户名密码认证对象 @@ -55,21 +57,23 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT // 创建已认证的用户密码认证对象 - public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id, Collection authorities) { + public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id,String Authority, Collection authorities) { super(authorities); this.name = name; this.avatar_url = avatar_url; this.github_id = github_id; + this.Authority = Authority; super.setAuthenticated(true); } // 创建已认证的用户密码认证对象 - public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id, String token, Collection authorities) { + public UsernamePasswordAuthenticationToken(String name, String avatar_url, int github_id, String token, String Authority, Collection authorities) { super(authorities); this.name = name; this.avatar_url = avatar_url; this.github_id = github_id; this.Token = token; + this.Authority = Authority; super.setAuthenticated(true); } @@ -132,4 +136,12 @@ public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationT public void setGithub_id(int github_id) { this.github_id = github_id; } + + public String getAuthority() { + return Authority; + } + + public void setAuthority(String authority) { + Authority = authority; + } } diff --git a/src/main/java/io/qyi/e5/config/security/filter/LinkTokenAuthenticationFilter.java b/src/main/java/io/qyi/e5/config/security/filter/LinkTokenAuthenticationFilter.java index e69dea9..0f1226c 100644 --- a/src/main/java/io/qyi/e5/config/security/filter/LinkTokenAuthenticationFilter.java +++ b/src/main/java/io/qyi/e5/config/security/filter/LinkTokenAuthenticationFilter.java @@ -1,16 +1,14 @@ 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.util.SpringUtil; import io.qyi.e5.util.redis.RedisUtil; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; @@ -18,7 +16,6 @@ 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.Map; /** @@ -31,20 +28,19 @@ import java.util.Map; **/ public class LinkTokenAuthenticationFilter extends OncePerRequestFilter { + @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { String token = httpServletRequest.getHeader("token"); if (token != null) { - RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class); - if (redisUtil.hasKey("token:" + token)) { - Map userInfo = redisUtil.hmget("token:" + token); + RedisUtil RedisUtil = SpringUtil.getBean(RedisUtil.class); + if (RedisUtil.hasKey("token:" + token)) { + Map userInfo = RedisUtil.hmget("token:" + token); // 将未认证的Authentication转换成自定义的用户认证Token - UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(); 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")); - authenticationToken1.setDetails(authenticationToken); + userInfo.get("avatar_url").toString(), (int) userInfo.get("github_id"), userInfo.get("authority").toString(), AuthorityUtils.createAuthorityList("user")); SecurityContextHolder.getContext().setAuthentication(authenticationToken1); - System.out.println("完成授权"); + System.out.println("完成授权,角色:" + userInfo.get("authority").toString()); } } 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(); - } } diff --git a/src/main/java/io/qyi/e5/controller/TestController.java b/src/main/java/io/qyi/e5/controller/admin/TestController.java similarity index 74% rename from src/main/java/io/qyi/e5/controller/TestController.java rename to src/main/java/io/qyi/e5/controller/admin/TestController.java index 5009e66..2f61b80 100644 --- a/src/main/java/io/qyi/e5/controller/TestController.java +++ b/src/main/java/io/qyi/e5/controller/admin/TestController.java @@ -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.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.core.RabbitTemplate; 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.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.UUID; @@ -22,8 +26,8 @@ import java.util.UUID; * @author: 落叶随风 * @create: 2020-03-16 01:01 **/ -@Controller @RestController +@RequestMapping("/admin") public class TestController { @Autowired RabbitTemplate rabbitTemplate; @@ -53,6 +57,12 @@ public class TestController { return "ok"; } + @GetMapping("/test") + @PreAuthorize("hasRole('ROLE_ADMIN')") + public String test() { + return "ok"; + } + } diff --git a/src/main/java/io/qyi/e5/service/rabbitMQ/impl/ListenerImpl.java b/src/main/java/io/qyi/e5/service/rabbitMQ/impl/ListenerImpl.java index c2617b6..b3e7b6b 100644 --- a/src/main/java/io/qyi/e5/service/rabbitMQ/impl/ListenerImpl.java +++ b/src/main/java/io/qyi/e5/service/rabbitMQ/impl/ListenerImpl.java @@ -1,11 +1,6 @@ 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 io.qyi.e5.outlook.entity.Outlook; import io.qyi.e5.outlook.service.IOutlookService; import io.qyi.e5.service.task.ITask; import org.slf4j.Logger; @@ -17,7 +12,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; -import java.lang.reflect.Type; /** * @program: msgpush @@ -35,7 +29,7 @@ public class ListenerImpl { ITask Task; @RabbitHandler - @RabbitListener(queues = "delay_queue1", containerFactory = "rabbitListenerContainerFactory") + @RabbitListener(queues = "delay_queue3", containerFactory = "rabbitListenerContainerFactory") public void listen(Message message, Channel channel) throws IOException { logger.info("消费者1开始处理消息: {},时间戳:{}" ,message,System.currentTimeMillis()); System.out.println("消费者1开始处理消息:"+System.currentTimeMillis()); diff --git a/src/main/java/io/qyi/e5/service/security/SecurityUserService.java b/src/main/java/io/qyi/e5/service/security/SecurityUserService.java deleted file mode 100644 index c0f8b29..0000000 --- a/src/main/java/io/qyi/e5/service/security/SecurityUserService.java +++ /dev/null @@ -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; - } -} diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml index 13784fc..5999d31 100644 --- a/src/main/resources/log4j2.xml +++ b/src/main/resources/log4j2.xml @@ -4,7 +4,7 @@ - +