SpringBoot整合Spring Security的详细教程

yizhihongxing

SpringBoot整合SpringSecurity的详细教程

Spring Security是Spring框架家族中的一员,是基于Spring的实现了安全控制的框架。

SpringBoot是一个快速开发的框架,整合SpringSecurity可以让开发者快速实现安全控制功能。

下面我们一步步的来学习如何在SpringBoot中整合SpringSecurity实现安全控制。

1. 引入Spring Security依赖

我们需要在pom.xml文件中引入Spring Security依赖,代码如下:

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

2. 配置Spring Security

配置Spring Security可以通过继承WebSecurityConfigurerAdapter类和重写其中的方法来实现。例如:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll() // 不需要认证的页面
                .anyRequest().authenticated() // 其他所有页面都需要认证
                .and()
            .formLogin()
                .loginPage("/login") // 登录页面
                .permitAll() // 登录页面不需要认证
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

上述代码实现了以下功能:

  • 配置了不需要认证的页面
  • 配置了需要认证的页面并跳转到登录页面
  • 配置了登录页面
  • 配置了退出登录

3. 添加自定义登录页面

如果需要使用自己的登录页面,可以通过以下步骤实现:

  • application.properties文件中添加以下配置:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
  • src/main/webapp/WEB-INF目录下添加jsp文件夹,并在其中添加login.jsp文件。
  • 修改SecurityConfig类的configure()方法:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/", "/home").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login") // 使用自定义的登录页面
            .permitAll()
            .and()
        .logout()
            .permitAll();
}

4. 使用数据库存储用户信息

Spring Security默认使用内存来存储用户信息,但是我们也可以使用数据库来存储用户信息。例如:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource; // 自动注入DataSource对象

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        String userSql = "SELECT username, password, enabled FROM users WHERE username = ?";
        String authoritySql = "SELECT username, authority FROM authorities WHERE username = ?";

        auth
            .jdbcAuthentication()
                .dataSource(dataSource) // 指定数据源
                .usersByUsernameQuery(userSql)
                .authoritiesByUsernameQuery(authoritySql);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}

上述代码使用了JdbcAuthentication来实现,并指定了使用的数据源。同时,我们需要在数据库中创建两张表usersauthorities来存储用户信息和权限信息。

示例1:使用默认登录页面

使用默认登录页面,代码如下:

@Controller
public class HomeController {

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

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

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

}

上述代码中使用了默认的登录页面。

示例2:使用自定义登录页面和数据库存储用户信息

使用自定义登录页面和数据库存储用户信息,代码如下:

@Controller
public class HomeController {

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

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

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

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        String userSql = "SELECT username, password, enabled FROM users WHERE username = ?";
        String authoritySql = "SELECT username, authority FROM authorities WHERE username = ?";

        auth
            .jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery(userSql)
                .authoritiesByUsernameQuery(authoritySql);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

}

上述代码中使用了自定义的登录页面和使用数据库存储了用户信息。同时,我们也需要在数据库中创建两张表:usersauthorities用来存储用户信息和权限信息。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot整合Spring Security的详细教程 - Python技术站

(0)
上一篇 2023年5月15日
下一篇 2023年5月15日

相关文章

  • 一篇文章告诉你如何在Java数组中插入一个字符

    下面是详细的攻略: 1. 准备工作 在 Java 中,数组是一个固定大小的对象容器,其中每个元素都必须是相同的数据类型。在插入一个字符到数组中,我们需要先确定以下几点: 数组是否足够容量存放新元素 新元素的数据类型是否与数组中元素的数据类型相同 2. 创建新数组并复制元素 由于 Java 数组的大小是固定不变的,我们无法插入一个元素到原有的数组。因此我们需要…

    Java 2023年5月26日
    00
  • Java中的this指针使用方法分享

    Java中的this指针使用方法分享 在Java中,this关键字代表当前对象,可以在类的实例方法中使用。本文将分享Java中this指针的用法。 1. 使用this代替实例变量 在类中,实例变量前不带任何前缀,而方法中的参数名可能与实例变量同名。这时候就需要使用this关键字来区分参数名和实例变量名。比如: public class Person { pr…

    Java 2023年5月19日
    00
  • java10下编译lombok注解代码分享

    为了在Java 10环境下编译Lombok注解代码,我们需要遵循以下步骤: 1.安装Lombok 可以通过Maven或Gradle依赖来安装Lombok。我们在Maven项目中添加以下依赖: <dependency> <groupId>org.projectlombok</groupId> <artifactId&g…

    Java 2023年5月20日
    00
  • springboot+jsonp解决前端跨域问题小结

    下面是“springboot+jsonp解决前端跨域问题小结”的详细攻略。 前言 在开发前后端分离的应用时,常常会遇到前端请求后端时跨域的问题。这个时候,可以采用jsonp方式来解决跨域问题。 引入依赖 在我们使用springboot+jsonp的时候,需要引入一下两个依赖: <dependency> <groupId>org.spr…

    Java 2023年5月26日
    00
  • RxJava入门之介绍与基本运用

    首先,感谢您对RxJava入门教程的关注与支持。 1. 什么是RxJava? RxJava是一个用于基于事件流和数据流的异步编程库。它使用观察者设计模式处理异步数据流和事件序列。RxJava的主要特点是提供灵活的响应式编程模式,使开发者可以更加高效地组合不同的数据源、事件和数据转换操作,实现更加优雅灵活的异步编程方案。 2. RxJava 的基本概念 Obs…

    Java 2023年5月19日
    00
  • JAVA生产者消费者(线程同步)代码学习示例

    JAVA生产者消费者(线程同步)代码学习示例 什么是生产者消费者模型 生产者消费者模型是一种常用的线程同步模型,它通过在多个线程之间协调共享资源的访问,来提高系统的效率和可靠性。在生产者消费者模型中,生产者线程负责生成数据,消费者线程负责消费数据,两者通过共享队列来协作,实现生产与消费的同步和协调。 学习示例1:基本实现 假设有一个生产者线程和一个消费者线程…

    Java 2023年5月26日
    00
  • Spring security 自定义过滤器实现Json参数传递并兼容表单参数(实例代码)

    这里给出详细的“Spring security 自定义过滤器实现Json参数传递并兼容表单参数(实例代码)”攻略: 1. 概述 当我们用 Spring Security 来进行用户认证和授权时,为了保证安全性,一般使用 POST 请求提交表单参数,而不能使用 GET 请求进行参数传递。但是在某些情况下,我们需要通过 Json 参数来进行传递,此时就需要用到自…

    Java 2023年5月20日
    00
  • 用java将GBK工程转为uft8的方法实例

    下面是将GBK编码的Java项目转换为UTF-8编码的攻略,包含两个示例说明。 步骤一:备份项目 在进行编码转换之前,务必备份Java项目,以免出现转换失败或其他问题导致数据丢失。 步骤二:使用文本编辑器转换文件编码 使用文本编辑器打开Java项目源文件。 将文件的编码方式从GBK转换为UTF-8。 示例一:使用notepad++进行编码转换。 打开note…

    Java 2023年6月1日
    00
合作推广
合作推广
分享本页
返回顶部