springboot2.x整合springSecurity

本文详细介绍了如何在Spring Boot项目中集成Spring Security,包括依赖导入、配置类编写及页面控制。通过示例展示了请求授权规则、自动登录与注销功能、记住我功能的实现,以及如何在页面上使用Thymeleaf进行权限控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springSecurity

1.导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lmh</groupId>
    <artifactId>spring-boot-12</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-12</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.编写springSecurity配置类

package com.lmh.springboot12.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    //定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       // super.configure(http);
        //antMatchers指定访问路径,permitAll表示均可访问,hasRole表示只有该角色才有权限访问
        http.authorizeRequests().antMatchers("/index").permitAll().antMatchers("/").hasRole("VIP1");

        //开启自动配置的登录功能
        //规则:/login 请求来到登录页,重定向到 /login?error 表示登录失败  loginPage("/");可以发送请求自定义登录页面
        //默认post形式的/login 代表处理登陆 passwordParameter("password").usernameParameter("username");与表单项name属性对应
        http.formLogin().loginPage("/userLogin").passwordParameter("password").usernameParameter("username");

        //开启自动配置注销功能,并销毁session
        //规则:访问  /logout  注销成功返回 /login?logout 页面 可通过.logoutSuccessUrl("/");修改注销成功路径
        http.logout().logoutSuccessUrl("/");

        //开启 记住我 功能 rememberMeParameter("rememberMe");要与表单项的name对应
        http.rememberMe().rememberMeParameter("rememberMe");
    }
//定制认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("lmh").password(new BCryptPasswordEncoder().encode("123")).roles("VIP1")
        .and().passwordEncoder(new BCryptPasswordEncoder()).withUser("张三").password(new BCryptPasswordEncoder().encode("123")).roles("VIP2");
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

其中不使用PasswordEncoder则会报错

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" (security)

其中很多基础功能都在注释上
3.页面上控制


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>

需要导入这个约束则可使用springSecurity页面控制

常用security标签

1.authorize:
access属性需要使用表达式来判断权限,当表达式的返回结果为true时表示拥有对应的权限

<sec:authorize access="hasRole('ROLE_ADMIN')">
此内容仅对在授予权限列表中拥有“ROLE_ADMIN”权限的用户可见
--------------------------
<sec:authorize access="hasPermission(#domain,'read') or hasPermission(#domain,'write')">
只有具有读取或写入权限的用户才能看到此内容,该用户被发现为名为“domain”的请求属性。
-----------------------------
<sec:authorize url="/admin">
此内容仅对有权将请求发送到“/ admin”链接的用户可见
-----------------------------
<div class="btn-group" sec:authorize="!isAuthenticated()">
判断有无登陆

2.authentication
标签用来代表当前Authentication对象,主要用于获取当前Authentication的相关信息。包含以下属性。
property
property属性只允许指定Authentication所拥有的属性。

<!--获取当前用户的用户名-->
<sec:authentication property="principal.username" />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值