源代码

package club.zstuca.myzstu.filter;import club.zstuca.myzstu.entity.Resource;
import club.zstuca.myzstu.entity.Role;
import club.zstuca.myzstu.mapper.ResourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.stereotype.Component;
import org.springframework.util.AntPathMatcher;import java.util.Collection;
import java.util.List;/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-03-07 21:57*/
@Component
public class CustomFilterInvocationSecurityMetadataSourceimplements FilterInvocationSecurityMetadataSource {AntPathMatcher antPathMatcher = new AntPathMatcher();@Autowiredprivate ResourceMapper resourceMapper;@Overridepublic Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {String ruquestUrl = ((FilterInvocation) o).getRequestUrl();List<Resource> resources = resourceMapper.getAllResource();for (Resource resource : resources){if(antPathMatcher.match(resource.getPattern(),ruquestUrl)){List<Role> roles = resource.getRoles();String[] roleArr = new String[roles.size()];for (int i = 0; i < roleArr.length;i++ ){roleArr[i] = roles.get(i).getName();}return SecurityConfig.createList(roleArr);}}return SecurityConfig.createList("ROLE_LOGIN");}@Overridepublic Collection<ConfigAttribute> getAllConfigAttributes() {return null;}@Overridepublic boolean supports(Class<?> aClass) {return FilterInvocation.class.isAssignableFrom(aClass);}
}
package club.zstuca.myzstu.filter;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.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;import java.util.Collection;/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-03-07 22:26*/
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {@Overridepublic void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {Collection<? extends GrantedAuthority> auths = authentication.getAuthorities();for(ConfigAttribute configAttribute:collection){if("ROLE_LOGIN".equals(configAttribute.getAttribute())&& authentication instanceof UsernamePasswordAuthenticationToken){return;}for(GrantedAuthority authority : auths){if(configAttribute.getAttribute().equals(authority.getAuthority())){return;}}}throw new AccessDeniedException("权限不足");}@Overridepublic boolean supports(ConfigAttribute configAttribute) {return true;}@Overridepublic boolean supports(Class<?> aClass) {return true;}
}
package club.zstuca.myzstu.config;import club.zstuca.myzstu.dto.ApiResponse;
import club.zstuca.myzstu.handler.AuthenticationAccessDeniedHandler;
import club.zstuca.myzstu.security.CustomAccessDecisionManager;
import club.zstuca.myzstu.security.CustomFilterInvocationSecurityMetadataSource;
import club.zstuca.myzstu.service.IUserService;
import club.zstuca.myzstu.utils.ApiResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-03-07 16:48*/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MyZSTUWebSecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredIUserService iUserService;@AutowiredCustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;@AutowiredCustomAccessDecisionManager customAccessDecisionManager;@AutowiredAuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;@BeanPasswordEncoder passwordEncoder(){return NoOpPasswordEncoder.getInstance();}@Overridepublic void configure(WebSecurity web){web.ignoring().antMatchers("/index.html");}@Overrideprotected void configure(AuthenticationManagerBuilder auth)throws Exception{auth.userDetailsService(iUserService);}@Overrideprotected void configure(HttpSecurity http)throws Exception{http.authorizeRequests().withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {@Overridepublic <O extends FilterSecurityInterceptor> O postProcess(O object) {object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);object.setAccessDecisionManager(customAccessDecisionManager);return object;}}).and().formLogin()//.loginPage("/login").loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password").failureHandler(new AuthenticationFailureHandler() {@Overridepublic void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {httpServletResponse.setContentType("application/json;charset=UTF-8");ApiResponse retTemp = ApiResponseUtil.getRetTemp();retTemp.setCode("400");retTemp.setMsg("登录失败");PrintWriter out = httpServletResponse.getWriter();out.write(new ObjectMapper().writeValueAsString(retTemp));out.flush();out.close();}}).successHandler(new AuthenticationSuccessHandler() {@Overridepublic void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {httpServletResponse.setContentType("application/json;charset=UTF-8");ApiResponse retTemp = ApiResponseUtil.getRetTemp();retTemp.setCode("200");retTemp.setMsg("登录成功");retTemp.setData(authentication.getPrincipal());PrintWriter out = httpServletResponse.getWriter();out.write(new ObjectMapper().writeValueAsString(retTemp));out.flush();out.close();}}).permitAll().and().logout().permitAll().and().csrf().disable().exceptionHandling().accessDeniedHandler(authenticationAccessDeniedHandler);}
}

教学资源

https://www.bilibili.com/video/av73730658?p=13

常见问题

Filter过滤器注入Bean时注入失败[NULL]

参考文章

https://blog.csdn.net/qushapos/article/details/84940810

https://segmentfault.com/a/1190000010232638

https://blog.csdn.net/lichuangcsdn/article/details/95041605

https://github.com/lenve/vhr

Spring Boot——配置Spring Security配置类DEMO相关推荐

  1. Spring Security 实战:Spring Boot 下的自动配置

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 来源 | 公众号「码农小胖哥」 1. 前言 我们在前几篇 ...

  2. springboot 读取配置文件_使用 @ConfigurationProperties 在 Spring Boot 中加载配置

    本文地址: 使用 @ConfigurationProperties 在 Spring Boot 中加载配置 使用 Spring Boot 加载配置文件的配置非常便利,我们只需要使用一些注解配置一下就能 ...

  3. Spring Boot 2.0 的配置详解(图文教程)

    本文来自作者 泥瓦匠 @ bysocket.com 在 GitChat 上分享 「Spring Boot 2.0 的配置详解(图文教程)」 编辑 | 哈比 Spring Boot 配置,包括自动配置和 ...

  4. boot spring 接口接收数据_在 Spring Boot 中使用 Dataway 配置数据查询接口

    Dataway介绍 Dataway 是基于 DataQL 服务聚合能力,为应用提供的一个接口配置工具.使得使用者无需开发任何代码就配置一个满足需求的接口. 整个接口配置.测试.冒烟.发布.一站式都通过 ...

  5. datav本地部署 java,Spring Boot对Spring Data JPA的自动配置

    一 点睛 Spring Boot对Spring Data JPA的自动配置放置在如下路径: 二 源码分析 1 JpaRepositoriesAutoConfiguration类分析 @Configur ...

  6. Spring Boot Validation提示信息国际化配置

    引言 之前介绍过Spring Boot Validation的使用及扩展,可参见:<SpringBoot Validation> 本文在此基础上重点讲解下Spring Boot Valid ...

  7. Spring Boot 灵活实现自动配置背后的故事~用起来更香了

    最近一直忙着在做新应届生的员工技术培训和面试 ,培训的则是Spring Boot部分的内容,这部分也是面试常问的点,于是想到了各位读者大大,特地的把内容分享大家一份. 不知道大家第一次搭Spring ...

  8. spring boot通过命令行配置属性

    spring boot通过命令行配置属性 命令:java -jar xxx.jar --server.port=8888,通过使用–-server.port属性来设置xxx.jar应用的端口为8888 ...

  9. chrome charset使用_使用JWT保护你的Spring Boot应用 Spring Security实战

    关键词 Spring Boot.OAuth 2.0.JWT.Spring Security.SSO.UAA 写在前面 最近安静下来,重新学习一些东西,最近一年几乎没写过代码.整天疲于奔命的日子终于结束 ...

  10. 使用JWT保护你的Spring Boot应用 - Spring Security实战

    使用JWT保护你的Spring Boot应用 - Spring Security实战 作者 freewolf 原创文章转载请标明出处 关键词 Spring Boot.OAuth 2.0.JWT.Spr ...

最新文章

  1. 可恶的MSSQL 内部 SQL Server 错误。(臭BUG)
  2. 08年度世界最佳照片(三)
  3. 如何让Moodle中所连结的flash等媒体事先呈现在画面上?
  4. 如何在Ruby中获得随机数
  5. 扯一扯 之 面试经历
  6. 腾讯云智服确保战“疫”期间服务不间断
  7. python实例31[解析buildlog]
  8. Linux下OneinStack一键安装JAVA+PHP+Tomcat+Nginx+MySQL网站环境
  9. 语音识别技术应用领域介绍
  10. 移动应用设计领域中最拔尖的15大应用
  11. seay代码审计工具_渗透测试 网站代码审计等基础方法篇
  12. 继承ActionSupport
  13. Paper再现:MD+AI自动编码机探测蛋白变构(一):文章分析
  14. 照片放大后怎么变清晰?
  15. Mysql出现问题:ERROR 1062 (23000): Duplicate entry ‘‘ for key ‘PRIMARY‘解决方案
  16. css中图片在div中的位置,纯CSS实现任意图片在div中垂直居中
  17. iOS开发:如何使用ShareSDK让APP快速拥有分享功能
  18. android 阿拉伯语符号,阿拉伯文符号
  19. 硬链接、软链接、ln命令
  20. Java:实现​lz4格式解压缩算法(附完整源码)

热门文章

  1. android studio failed to open zip file,Android Studio出现Failed to open zip file问题的解决方法...
  2. c语言printout函数,只使用处理I/O的PrintDigit函数,编写一个过程以输出任意实数...
  3. mysql中xml类型_使用 SQLXML 数据类型
  4. linux 上传工具 lr,Linux传输工具lrzsz
  5. MATLAB中cif用于清除什么,cifti-matlab-master 能够对MRI数据进行功能成像 - 下载 - 搜珍网...
  6. Android实现相册分享功能,Android系统自带分享功能的实现(可同时分享文字和图片)...
  7. Oracle表的分区update卡着,分区表update global indexes引起表阻塞
  8. 八十五、Eureka搭建分布式SpringCloud项目
  9. 额外篇| Python制作词云
  10. 小程序实现图片的放大预览