微服务技术系列教程(38)- SpringBoot -整合SpringSecurity

简介: 微服务技术系列教程(38)- SpringBoot -整合SpringSecurity

1. 引言

代码已提交至Github,有兴趣的同学可以下载看看:https://github.com/ylw-github/SpringBoot-Security-Demo

上一篇博客《微服务技术系列教程(37)- SpringBoot -SpringSecurity简介》主要讲解了SpringSecurity介绍以及应用场景。

本文主要讲解SpringBoot整合SpringSecurity,学习之前,先来了解一个概念“Basic认证”。

什么是Basic认证?

  1. 在HTTP协议进行通信的过程中,HTTP协议定义了基本认证过程以允许HTTP服务器对WEB浏览器进行用户身份证的方法,当一个客户端向HTTP服务器进行数据请求时,如果客户端未被认证,则HTTP服务器将通过基本认证过程对客户端的用户名及密码进行验证,以决定用户是否合法。
  2. 客户端在接收到HTTP服务器的身份认证要求后,会提示用户输入用户名及密码,然后将用户名及密码以BASE64加密,加密后的密文将附加于请求信息中,如当用户名为ylw,密码为:123456时,客户端将用户名和密码用“:”合并,并将合并后的字符串用BASE64加密为密文,并于每次请求数据时,将密文附加于请求头(Request Header)中。
  3. HTTP服务器在每次收到请求包后,根据协议取得客户端附加的用户信息(BASE64加密的用户名和密码),解开请求包,对用户名及密码进行验证,如果用户名及密码正确,则根据客户端请求,返回客户端所需要的数据;否则,返回错误代码或重新要求客户端提供用户名及密码。

2. SpringBoot整合Security

2.1 添加依赖与配置

1.添加Maven依赖:

<parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.0.1.RELEASE</version>
 </parent>
 <!-- 管理依赖 -->
 <dependencyManagement>
     <dependencies>
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-dependencies</artifactId>
             <version>Finchley.M7</version>
             <type>pom</type>
             <scope>import</scope>
         </dependency>
     </dependencies>
 </dependencyManagement>
 <dependencies>
     <!-- SpringBoot整合Web组件 -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
     </dependency>
     <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
     </dependency>
     <!-- springboot整合freemarker -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-freemarker</artifactId>
     </dependency>
     <!-->spring-boot 整合security -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
     </dependency>
 </dependencies>
 <!-- 注意: 这里必须要添加, 否者各种依赖有问题 -->
 <repositories>
     <repository>
         <id>spring-milestones</id>
         <name>Spring Milestones</name>
         <url>https://repo.spring.io/libs-milestone</url>
         <snapshots>
             <enabled>false</enabled>
         </snapshots>
     </repository>
 </repositories>

2.application.yml

# 配置freemarker
spring:
  freemarker:
    # 设置模板后缀名
    suffix: .ftl
    # 设置文档类型
    content-type: text/html
    # 设置页面编码格式
    charset: UTF-8
    # 设置页面缓存
    cache: false
    # 设置ftl文件路径
    template-loader-path:
      - classpath:/templates
  # 设置静态文件路径,js,css等
  mvc:
    static-path-pattern: /static/**

3.前端资源

4.请求Controller

@Controller
public class OrderController {
  // 首页
  @RequestMapping("/")
  public String index() {
    return "index";
  }
  // 查询订单
  @RequestMapping("/showOrder")
  public String showOrder() {
    return "showOrder";
  }
  // 添加订单
  @RequestMapping("/addOrder")
  public String addOrder() {
    return "addOrder";
  }
  // 修改订单
  @RequestMapping("/updateOrder")
  public String updateOrder() {
    return "updateOrder";
  }
  // 删除订单
  @RequestMapping("/deleteOrder")
  public String deleteOrder() {
    return "deleteOrder";
  }
  // 自定义登陆页面
  @GetMapping("/login")
  public String login() {
    return "login";
  }
}

2.2 Security配置

配置两个账号并配置每个路径配置拦截请求资源:

  • 账号admin:可以对订单进行增删改查
  • 账号userAdd :只能对订单进行查询和添加

配置详情如下:

// Security 配置
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private MyAuthenticationFailureHandler failureHandler;
  @Autowired
  private MyAuthenticationSuccessHandler successHandler;
  // 配置认证用户信息和权限
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // 添加admin账号
    auth.inMemoryAuthentication().withUser("admin").password("123456").
    authorities("showOrder","addOrder","updateOrder","deleteOrder");
    // 添加userAdd账号
    auth.inMemoryAuthentication().withUser("userAdd").password("123456").authorities("showOrder","addOrder");
    // 如果想实现动态账号与数据库关联 在该地方改为查询数据库
  }
  // 配置拦截请求资源
  protected void configure(HttpSecurity http) throws Exception {
    // 如何权限控制 给每一个请求路径 分配一个权限名称 让后账号只要关联该名称,就可以有访问权限
    http.authorizeRequests()
    // 配置查询订单权限
    .antMatchers("/showOrder").hasAnyAuthority("showOrder")
    .antMatchers("/addOrder").hasAnyAuthority("addOrder")
    .antMatchers("/login").permitAll()
    .antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
    .antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
    .antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").
    successHandler(successHandler).failureHandler(failureHandler)
    .and().csrf().disable();
  }
  @Bean
  public static NoOpPasswordEncoder passwordEncoder() {
    return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
  }
}

2.3 权限不足配置

1.控制器页面请求跳转

@Controller
public class ErrorController {
  // 403权限不足页面
  @RequestMapping("/error/403")
  public String error() {
    return "/error/403";
  }
}

2.自定义WEB 服务器参数

/**
 * 自定义 WEB 服务器参数 可以配置默认错误页面
 */
@Configuration
public class WebServerAutoConfiguration {
  @Bean
  public ConfigurableServletWebServerFactory webServerFactory() {
    TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
    ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
    ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
    ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
    ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
    ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
    ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
    factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
    return factory;
  }
}

2.4 认证成功或者失败处理

认证失败接口:AuthenticationFailureHandler

//认证失败
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
  public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException auth)
      throws IOException, ServletException {
    System.out.println("登陆失败!");
    res.sendRedirect("http://baidu.com");
  }
}

认证成功接口:AuthenticationSuccessHandler

// 认证成功
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
  public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication arg2)
      throws IOException, ServletException {
    System.out.println("用户认证成功");
    res.sendRedirect("/");
  }
}

3. 启动测试

1.浏览器输入:http://localhost:8080,可以由于权限配置,看到自动跳转到了登录界面。

自动跳转到了登录界面:

3.1 使用admin测试

1.登录页面输入账号admin、密码123456,进入了订单系统

2.点击4个链接,均能访问,因为已经分配所有权限给admin了。

3.1 使用useAdd测试

1.登录页面输入账号userAdd、密码123456,进入了订单系统

2.点击查询和添加链接,可以访问。但是删除和修改链接失败,因为代码里没有赋予其权限。

目录
相关文章
|
3天前
|
机器学习/深度学习 负载均衡 Java
【SpringBoot系列】微服务远程调用Open Feign深度学习
【4月更文挑战第9天】微服务远程调度open Feign 框架学习
|
8天前
|
安全 Java API
第7章 Spring Security 的 REST API 与微服务安全(2024 最新版)(上)
第7章 Spring Security 的 REST API 与微服务安全(2024 最新版)
28 0
第7章 Spring Security 的 REST API 与微服务安全(2024 最新版)(上)
|
9天前
|
Java API 微服务
【Spring Boot系列】通过OpenAPI规范构建微服务服务接口
【4月更文挑战第5天】通过OpenAPI接口构建Spring Boot服务RestAPI接口
|
1月前
|
存储 安全 Java
Spring Boot整合Spring Security--学习笔记
Spring Boot整合Spring Security--学习笔记
55 1
|
6天前
|
存储 Java 时序数据库
【SpringBoot系列】微服务监测(常用指标及自定义指标)
【4月更文挑战第6天】SpringBoot微服务的监测指标及自定义指标讲解
|
20天前
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
|
5天前
|
Java 关系型数据库 数据库
【SpringBoot系列】微服务集成Flyway
【4月更文挑战第7天】SpringBoot微服务集成Flyway
【SpringBoot系列】微服务集成Flyway
|
10天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
11天前
|
存储 数据可视化 安全
Java全套智慧校园系统源码springboot+elmentui +Quartz可视化校园管理平台系统源码 建设智慧校园的5大关键技术
智慧校园指的是以物联网为基础的智慧化的校园工作、学习和生活一体化环境,这个一体化环境以各种应用服务系统为载体,将教学、科研、管理和校园生活进行充分融合。无处不在的网络学习、融合创新的网络科研、透明高效的校务治理、丰富多彩的校园文化、方便周到的校园生活。简而言之,“要做一个安全、稳定、环保、节能的校园。
37 6
|
19天前
|
消息中间件 监控 Java
微服务技术发展
微服务技术发展

热门文章

最新文章