SpringBoot 安全管理(一)

一、springSecurity入门

  • 添加依赖

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId></dependency>
  • 不做配置时,每次访问都需要验证,用户名默认为user,密码为启动时控制台打印的密文(每次启动都会随机生成),访问/logout即可注销登录

    • 如 Using generated security password: 31612171-4f6a-4c43-92ae-6826bc1d5e49
    • 注意,登录如果404,是因为没有配置页面,登录成功后默认跳转到 “/ ” 下面,没有页面,便404了
  • 手动配置(数据是写死的)

    • 在spring5以后,security是不允许明文的,必须加密

    • 在application.properties中配置

      spring.security.user.name=user
      spring.security.user.password=123
      spring.security.user.roles=admin
    • 在类中配置(注意继承了WebSecurityConfigurerAdapter,加上Configuration注解)

      @Configuration
      public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean
      PasswordEncoder passwordEncoder(){
      //这个已过期,作用是无需加密,允许明文
      return NoOpPasswordEncoder.getInstance();
      } @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.inMemoryAuthentication()
      .withUser("user").password("123").roles("admin")
      .and() //可重复添加
      .withUser("user1").password("123").roles("super");
      }
      }
  • HttpSecurity(登陆注销相关的配置,有点长,请耐心观看)

     @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests() //开启登录配置
    .antMatchers("admin/**").hasRole("admin") // 访问/admin下需要admin角色
    .antMatchers("user/**").hasAnyRole("admin","user") //访问/user下需要admin或user其中一个角色
    .anyRequest().authenticated() //除以上2个url 访问其他只需要登录
    .and()
    .formLogin()
    .loginProcessingUrl("/login") //配置登录接口
    .usernameParameter("uname") //定义用户名的key
    .passwordParameter("passwd") //定义密码的key
    //.successForwardUrl("xxxxx") 定义登录成功后跳转的页面(前后端不分离) .successHandler(new AuthenticationSuccessHandler() {
    @Override //定义成功后返回json数据 ,前后端分离
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    response.setContentType("application/json;charset=utf-8");
    PrintWriter writer = response.getWriter();
    Map<String,Object> map = new HashMap<>();
    map.put("status",200);
    map.put("msg","success");
    writer.write(new ObjectMapper().writeValueAsString(map)); //将map以json格式输出
    writer.flush();
    writer.close();
    }
    }) .failureHandler(new AuthenticationFailureHandler() {
    @Override //定义失败后的操作(前后端分离)
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
    response.setContentType("application/json;charset=utf-8");
    PrintWriter writer = response.getWriter();
    Map<String,Object> map = new HashMap<>();
    map.put("status",401);
    if (e instanceof LockedException){
    map.put("msg","账户被锁定,登陆失败");
    }//在lockerException的父类的父类中就有很多异常,如下图,灵活使用
    writer.write(new ObjectMapper().writeValueAsString(map)); //将map以json格式输出
    writer.flush();
    writer.close();
    }
    })
    .permitAll() //登录接口对所有人开放
    .and() .logout()
    .logoutUrl("/logout")
    .logoutSuccessHandler(new LogoutSuccessHandler() {
    @Override //注销登录
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    response.setContentType("application/json;charset=utf-8");
    PrintWriter writer = response.getWriter();
    Map<String,Object> map = new HashMap<>();
    map.put("status",200);
    map.put("msg","注销成功");
    writer.write(new ObjectMapper().writeValueAsString(map)); //将map以json格式输出
    writer.flush();
    writer.close();
    }
    })
    .permitAll();
    }

  • 多个HttpSecurity配置(使代码看起来更简洁)

    @Configuration

    public class Config2 {

      @Bean
    PasswordEncoder passwordEncoder(){
    return NoOpPasswordEncoder.getInstance();
    } @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
    .withUser("user").password("123").roles("admin")
    .and()
    .withUser("user1").password("123").roles("super");
    } @Configuration
    @Order(1) //优先级 ,数字越小,级别越高
    public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter(){
    //参考SecurityConfig的配置
    } @Configuration
    public static class UserSecurityConfig extends WebSecurityConfigurerAdapter(){
    //参考SecurityConfig的配置
    }

    }


  • 密码加密

    • @Bean
      PasswordEncoder passwordEncoder(){
      return new BCryptPasswordEncoder();
      }
    • SpringSecurity使用的密码加密比MD5+盐更加严谨,即使相同的明文,加密的密文也一样,不易被暴力破解,而且不用解决存盐问题,当然,世界上没有绝对的安全加密,只能说更加安全。


    如果有对你帮助,求点个赞。

SpringBoot 安全管理(一)的更多相关文章

  1. SpringBoot安全管理--(三)整合shiro

    简介: Apache Shiro 是一一个开源的轻量级的Java安全框架,它提供身份验证.授权.密码管理以及会话管理等功能. 相对于Spring Security, Shiro框架更加直观.易用,同时 ...

  2. SpringBoot安全管理--(二)基于数据库的认证

    简介: 上篇文章向读者介绍的认证数据都是定义在内存中的,在真实项目中,用户的基本信息以及角色等都存储在数据库中,因此需要从数据库中获取数据进行认证. 开始: 首先建表并且插入数据: pom.xml & ...

  3. SpringBoot安全管理--(一)SpringSecurity基本配置

    简介: Spring Boot针对Spring Security提供了自动化配置方案,因此可以使Spring Security非常容易地整合进Spring Boot项目中,这也是在Spring Boo ...

  4. 2流高手速成记(之五):Springboot整合Shiro实现安全管理

    废话不多说,咱们直接接上回 上一篇我们讲了如何使用Springboot框架整合Nosql,并于文章最后部分引入了服务端Session的概念 而早在上上一篇中,我们则已经讲到了如何使用Springboo ...

  5. Shiro 核心功能案例讲解 基于SpringBoot 有源码

    Shiro 核心功能案例讲解 基于SpringBoot 有源码 从实战中学习Shiro的用法.本章使用SpringBoot快速搭建项目.整合SiteMesh框架布局页面.整合Shiro框架实现用身份认 ...

  6. 【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础授权权限

    上一篇<[原]无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础认证权限>介绍了实现Shiro的基础认证.本篇谈谈实现 ...

  7. 【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础认证权限

    开发环境搭建参见<[原]无脑操作:IDEA + maven + SpringBoot + JPA + Thymeleaf实现CRUD及分页> 需求: ① 除了登录页面,在地址栏直接访问其他 ...

  8. springboot 注册dao层 service 层

    可以使用三种注解来引入DAO层的接口到spring容器中.1.@Mapper,写在每一个DAO层接口上,如下: 2.@MapperScan和@ComponentScan两者之一.前者的意义是将指定包中 ...

  9. 补习系列(6)- springboot 整合 shiro 一指禅

    目标 了解ApacheShiro是什么,能做什么: 通过QuickStart 代码领会 Shiro的关键概念: 能基于SpringBoot 整合Shiro 实现URL安全访问: 掌握基于注解的方法,以 ...

随机推荐

  1. 【mybatis xml】数据层框架应用--Mybatis(三)关系映射之一对一关系映射

    实际的开发中,对数据库的操作常常会涉及到多张表,这在面向对象中就涉及到了对象与对象之间的关联关系. 针对多表之间的操作,MyBatis提供了关联映射,通过关联映射就可以很好的处理对象与对象之间的关联关 ...

  2. Kafka平滑滚动升级2.4.0指南

    今天测试了下kafka从2.0.0滚动升级至2.4.0,下面做一下记录.这个链接是Kafka官网对升级2.4.0的指南,可以参考  http://kafka.apache.org/24/documen ...

  3. Mariadb 主主复制

    两台server1  192.168.1.189 &&  server2 192.168.1.226 安装mariadb数据库 yum -y install mariadb maria ...

  4. 【Java8新特性】还没搞懂函数式接口?赶快过来看看吧!

    写在前面 Java8中内置了一些在开发中常用的函数式接口,极大的提高了我们的开发效率.那么,问题来了,你知道都有哪些函数式接口吗? 函数式接口总览 这里,我使用表格的形式来简单说明下Java8中提供的 ...

  5. HDU1214圆桌会议

    一个环,从1编号到n. 每次可以交换相邻的两个人, 问最少交换几次,使得每个数字的左右数字交换. 转载自:https://blog.csdn.net/yin_zongming/article/deta ...

  6. 阿里巴巴泰山版《Java 开发者手册》,也是一份防坑指南

    我是风筝,公众号「古时的风筝」,一个不只有技术的技术公众号,一个在程序圈混迹多年,主业 Java,另外 Python.React 也玩儿的 6 的斜杠开发者. Spring Cloud 系列文章已经完 ...

  7. 设计模式之GOF23解释器模式

    解释器模式Interpreter -是一种不常用的设计模式 -用于描述如何构成一个简单的语言解释器,主要用于使用面向对象语言开发的编译器和解释器设计 -当我们需要开发一种新的语言时,可以考虑使用解释器 ...

  8. iOS事件的响应和传递机制

    跟二狗子哥哥交流的时候,他总说我,说的过程太业余.故 好好学习整理一下.努力不那么业余. 一.事件的产生.传递.响应: 1.事件从父控件依次传递到子控件,寻找最合适的子控件View. 2.寻找最合适的 ...

  9. 【SMB源码解析系列】——003.SMB游戏基本框架

    前面有了解到RESET中断相关代码,结尾处通过一句jmp进入了无限循环,之后CPU将会在每一帧PUU进入VBlank状态时,接收NMI中断信号, 跳转至NMI代码处继续执行,直到遇见RTI指令时又返回 ...

  10. java -> 异常类与自定义异常

    异常 什么是异常?Java代码在运行时期发生的问题就是异常. 在Java中,把异常信息封装成了一个类.当出现了问题时,就会创建异常类对象并抛出异常相关的信息(如异常出现的位置.原因等). 异常的继承体 ...