目录

1、基于内存认证

2、基于数据库认证


1、基于内存认证

1)、配置pom文件

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>

2)、自定义WebSecurityConfigurerAdapter

@Configuration
public class WebImSecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder() {return NoOpPasswordEncoder.getInstance();}//配置基于内存认证@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("admin").password("123").roles("ADMIN","USER").and().withUser("zhao").password("123").roles("USER");}//配置HttpSecurity@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").access("hasAnyRole('ADMIN','USER')").antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')").anyRequest().authenticated().and().formLogin().loginProcessingUrl("/login").usernameParameter("name").passwordParameter("passwd").successHandler(new AuthenticationSuccessHandler() {//登录成功@Overridepublic void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {Object principal = authentication.getPrincipal();resp.setContentType("application/json;charset=utf-8");PrintWriter out = resp.getWriter();resp.setStatus(200);Map<String,Object> map = new HashMap<>();map.put("status",200);map.put("msg",principal);ObjectMapper om = new ObjectMapper();out.write(om.writeValueAsString(map));out.flush();out.close();}}).failureHandler(new AuthenticationFailureHandler() {//登录失败@Overridepublic void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {resp.setContentType("application/json;charset=utf-8");PrintWriter out = resp.getWriter();resp.setStatus(401);Map<String,Object> map = new HashMap<>();map.put("status",401);if(e instanceof LockedException) {map.put("msg","账户被锁定,登录失败!");}else if (e instanceof BadCredentialsException) {map.put("msg","账户密码输入错误,登录失败!");}else if (e instanceof BadCredentialsException) {map.put("msg","账户密码输入错误,登录失败!");}else if (e instanceof DisabledException) {map.put("msg","账户被禁用,登录失败!");}else if (e instanceof AccountExpiredException) {map.put("msg","账户已过期,登录失败!");}else if (e instanceof CredentialsExpiredException) {map.put("msg","密码已过期,登录失败!");}else {map.put("msg","登录失败");}ObjectMapper om = new ObjectMapper();out.write(om.writeValueAsString(map));out.flush();out.close();}}).and().logout().logoutUrl("/logout").clearAuthentication(true).invalidateHttpSession(true).addLogoutHandler(new LogoutHandler() {//退出@Overridepublic void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {}}).logoutSuccessHandler(new LogoutSuccessHandler() {//退出成功@Overridepublic void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {httpServletResponse.sendRedirect("/login_page");}}).permitAll().and().csrf().disable();}
}

3)、密码加密

@Bean
public PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();
}

4)、方法安全使用 @EnableGlobalMethodSecurity

prePostEnabled = true 会解锁@PreAuthorize 和@PostAuthorize两个注解

以上是基于内存认证的spring security,下节我们继续讲spring security 怎么基于数据库认证! 

spring boot 整合security相关推荐

  1. Spring Boot整合Security系列步骤及问题排查(十一)—— 集成QQ登录

    工具类准备: Repository: Connection: ConnectionFactory(ServiceProvider.ApiAdapter): ServiceProvider(OAuth2 ...

  2. Spring Boot整合Security+Swagger2踩坑记录,Swagger2无法访问首页

    问题: 访问不了Swagger的页面 有可能出现的原因: 1.Security将访问拦截掉了 2.给拦截器拦截了 3.Swagger返回的结果,被自己定义的拦截器or其他方式给篡改了数据,导致无法正常 ...

  3. 解决Spring Boot 整合Security后,所有接口提示Unauthorized、返回401

    解决办法 在启动类前的@SpringBootApplication注解中加入exclude属性SecurityAutoConfiguration和ManagementWebSecurityAutoCo ...

  4. spring boot整合security时候处理静态资源拦截问题

    添加上箭头注意写法和对应项目中的实际路径包名/css/**的意思可以跨包访问css下的所有文件与包

  5. spring boot整合spring security笔记

    最近自己做了一个小项目,正在进行springboot和spring Security的整合,有一丢丢的感悟,在这里分享一下: 首先,spring boot整合spring security最好是使用T ...

  6. Spring boot 整合Spring Security Jwt

    记录学习Spring boot 整合Spring Security Jwt 学习参考 – 慢慢的干货 https://shimo.im/docs/OnZDwoxFFL8bnP1c/read 首先创建S ...

  7. 认证与授权流程与spring boot整合 spring security(1)

    一   spring security 1.1 spring security的作用 Spring Security所解决的问题就是安全访问控制,而安全访问控制功能其实就是对所有进入系统的请求进行拦截 ...

  8. Spring Boot(十四):spring boot整合shiro-登录认证和权限管理

    Spring Boot(十四):spring boot整合shiro-登录认证和权限管理 使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉 ...

  9. spring boot整合cxf发布和调用webservice

    一.前言 说起web service最近几年restful大行其道,大有取代传统soap web service的趋势,但是一些特有或相对老旧的系统依然使用了传统的soap web service,例 ...

最新文章

  1. PostgresSQL生成UUID
  2. 利用matlab处理点云
  3. 玩转u8g2 OLED库,一篇就够
  4. js 正则表达式,正整数
  5. oracle数据库归档闪回,[Oracle]Oracle的闪回归档
  6. c语言中把时间拷到字符串中,C语言中将日期和时间以字符串格式输出的方法
  7. 填坑-关于SysTick定时器
  8. 非关系型数据库和关系型数据库区别(转载)
  9. 艾伟也谈项目管理,我的项目管理观点
  10. 计算机毕业设计ssm汽车租赁系统42876系统+程序+源码+lw+远程部署
  11. 常用RF连接器SMA/SMB/SMP/MMCX/BNC/TNC/2.92/2.4
  12. 字节跳动 IconPark 免费图标库、阿里巴巴矢量图标库
  13. 清华2019最新AI发展报告出炉!400页干货,13大领域一文看懂
  14. 如何将pdf生成二维码链接?
  15. winsxs是什么文件夹 Winsxs文件夹可以删除吗
  16. ECCV2022论文列表(中英对照)
  17. python——人工智能(AI)之网络图片文字识别案例详细讲解
  18. android电量优化方法,Android性能优化——电池使用优化
  19. PDF文件压缩和优化的原理是什么?看了这篇C#案例实践就知道了
  20. 4个有助于保护网站免受劫持的方法

热门文章

  1. VC资源分配、释放表
  2. ab plc编程软件_三菱PLC编程程序PLC的软件编程
  3. vc udp 广播接收和发送_UDP编程与DatagramSocket类:UDP的套接字
  4. android videoview播放进度,android – 获取视频播放视频的进度时间?
  5. C++ 标准库类型 map
  6. codeforces educational round110 e
  7. 【机器学习】数据不平衡问题都怎么解?
  8. 【深度学习】何恺明经典之作—2009 CVPR Best Paper | Dark Channel Prior
  9. 【NLP】10000亿参数!英伟达用3072块A100训出史上最大最贵GPT!
  10. 【小白学PyTorch】扩展之Tensorflow2.0 | 21 Keras的API详解(下)池化、Normalization