springboot-security 快速使用

本文介绍了如何使用Spring Boot Security实现用户权限管理,包括搭建项目、配置路由跳转、静态资源导入、安全配置和不同级别的用户授权。通过实例展示了如何设置登录验证、角色映射和定制登录界面。

功能:不同级别用户拥有的相应权限

一、搭建

新建一个 springboot-security 项目,
初始化
导入相关依赖,

<!-- thymeleaf模板 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
        <!-- 判断登录状态要用到,可见index.html-->
        <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-web</artifactId>
        </dependency>

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

二、路由跳转

在自己新建的controller包下写一个实现路由跳转的类

package com.zh.controller;

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

@Controller
public class RouterController {
	// 首页
    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }
	// 跳转登录页
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "views/login";
    }
    // level1层级
    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id){
        return "views/level1/"+id;
    }
    // level2层级
    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id){
        return "views/level2/"+id;
    }
    // level3层级
    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id){
        return "views/level3/"+id;
    }
}

在浏览器上测试跳转功能,无误后进行下一步。

三、静态资源导入

.properties 文件中关闭模板引擎缓存

 spring.thymeleaf.cache=false

导入静态资源(提取码:az66),

静态资源
不过,在 index.html 页面中,有一个功能是:未登录时,页面右上角应为登录图标,已登录时才显示用户名和注销图标,此时需要将 springboot 版本降到 2.0.9 才能体现出来。
2.0.9
耐心等待加载……

四、配置

加载完成后,在自己新建的config包下创建一个安全性配置类(注意父类的configure方法有多个不要选错了)

package com.zh.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;

@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");
        http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd");
        http.csrf().disable(); // 关闭防CSRF
        http.logout().logoutSuccessUrl("/"); // 登出后跳转首页
        http.rememberMe().rememberMeParameter("remember"); // 记住我勾选框
    }
    // 这里是在内存认证不同级别用户
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuang").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");
    }
}

五、测试

启动项目,打开浏览器输入 localhost:8080
首页
使用 guest(123456)登录
登录

guest
如果你勾选了记住我,关闭浏览器再次打开会自动登录上次登录的用户。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值