springboot整合spring-security

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

        在web开发中安全性问题比较重要一般会使用过滤器或者拦截器的方式对权限等进行验证过滤。此博客根据b站up主使用demo示例进行展示spring-security的一些功能作用。

目  录

1、创建项目

2、编写controller

3、添加spring-security依赖

4、编写spring-security配置类

5、添加thymeleaf-extras-springsecurity5 依赖

6、页面访问测试


        先来最终的目录结构

         pom文件springboot版本为 2.0.9.RELEASE

<?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.0.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ljy</groupId>
    <artifactId>test-spring-security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test-spring-security</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1、创建项目

        创建项目并添加web和Thymeleaf依赖

        下载静态资源并进行导入下载地址为静态资源地址

2、编写controller

package com.ljy.testspringsecurity.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author 不要有情绪的  ljy
 * @Date 2023/1/13 15:23
 * @Description:
 */
@Controller
public class RouterController {
    @RequestMapping({"/", "index"})
    public String index() {
        return "index";
    }

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

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id) {
        return "views/level1/" + id;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id) {
        return "views/level2/" + id;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id) {
        return "views/level3/" + id;
    }
}

3、添加spring-security依赖

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

4、编写spring-security配置类

package com.ljy.testspringsecurity.config;

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;

/**
 * @Author 不要有情绪的  ljy
 * @Date 2023/1/13 15:39
 * @Description:
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //授权认证
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //定制请求的授权规则    其目的是告诉有哪些权限的人才可以访问页面
        http.authorizeRequests()
                .antMatchers("/").permitAll()  //首页所有人可以访问
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //开启自动配置的登录功能
        //没有权限默认会到登录页面
        //定制登陆页面("/toLogin")
        //登录认证("/login")
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/toLogin")
                .loginProcessingUrl("/login");


        /*防止网站攻击*/   //也是解决注销报错的方法
        http.csrf().disable();//关闭csrf


        // 开启自动配置的注销的功能
        /*注销成功后跳到首页*/
        http.logout().logoutSuccessUrl("/");


        //记住我功能自定义接受前端数据
        http.rememberMe().rememberMeParameter("remember");
    }


    //定义认证规则     其目的是告诉哪些的用户拥有哪些权限即给用户绑定用户角色
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中定义,也可以在jdbc中去拿
        //Spring security 5.0中新增了多种加密方式也改变了密码的格式
        //要想我们的项目还能够正常登录需要修改以下configure中的代码我们要将前端传过来的密码进行某种方法的加密
        //spring security 官方推荐的是使用bcrypt加密方式。
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2");
    }
}

        对以上代码进行简单描述configure(HttpSecurity http)方法是授权认证其目的是告诉有哪些权限的人才可以访问哪个页面configure(AuthenticationManagerBuilder auth)方法是定义认证规则其目的是定义哪些用户有权限即给每个用户绑定权限。

5、添加thymeleaf-extras-springsecurity5 依赖

        为了在前端实现动态展示页面的效果即不同权限看到的页面内容不一样引入thymeleaf-extras-springsecurity5依赖即使用 secauthorize=“isAuthenticated()”是否认证登录来显示不同的页面。前端页面不在描述可以根据b站视频查看视频地址

6、页面访问测试

http://localhost:8080/

项目已上传到github上地址源码地址        

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring