banner
NEWS LETTER

SpringBoot项目整合SpringSecurity笔记

  • Home
  • springboot-security
Scroll down

SpringSecurity是安全框架,与shiro相似。其主要功能是:用户认证(Authentication)和用户授权(Authorization)。用户登录时完成登录认证,并存储登录认证信息;用户访问接口、方法时,权限认证根据登录认证信息,通过权限信息和授权策略完成授权。
本案例完成项目搭建,并作出相应测试

一、Security基本搭建

1、创建springboot项目

  • 项目结构

2、添加项目依赖

pom.xml

pom.xml >folded
1
2
3
4
5
<!-- spring security依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

本案例使用的依赖版本如下:
spring-boot-starter:2.3.4
spring-boot-starter-web:2.3.4
spring-boot-starter-security:2.3.4

3、修改配置文件

修改application.properties文件为application.yml

  • 若不自定义用户名,密码,Security会有一个默认用户名为:user,密码在控制台输出
  • 例如:Using generated security password: 9673fc9a-8506-4b27-8011-f5b16f068c24
    application.yml
    1
    2
    3
    4
    5
    spring:
    security:
    user:
    name: lmg
    password: 123123

4、创建Security配置类

SpringSecurityConfiguration.java

  • @Configuration:注解用于定义配置类
  • @EnableWebSecurity:注解开启Spring Security的功能
    Configuration.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import org.springframework.context.annotation.Configuration;
    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;

    @Configuration
    @EnableWebSecurity
    public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    // Security提供自带的Login页面,可不用自定义,若采用自带Login页面,本行代码可注释
    http.formLogin().loginPage("/login").permitAll()
    .and()
    .authorizeRequests()
    .anyRequest()
    .authenticated();
    }
    }

5、创建Controller类

IndexController.java

  • 若采用Security自带Login页面,可不用创建Controller类
    IndexController.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
    public class IndexController {

    @RequestMapping("/login")
    public String login(){
    return "login";
    }
    }

6、定义一个静态页面

index.html

  • Security登录验证后,默认进入index.html页面
    index.html
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>SpringSecurity笔记</title>
    </head>
    <body>
    <p align="center">欢迎访问SpringSecurity首页</p>
    </body>
    </html>

7、启动项目

使用浏览器测试,测试地址:http://localhost:8080

请随意打赏

评论