SpringBoot专题学习Part30:SpringBoot整合Spring Security实现Web权限控制【完结】

本文详细介绍了如何在SpringBoot应用中整合Spring Security进行Web权限控制,包括开启默认登录页、定义认证规则、实现注销功能、根据用户权限显示页面、启用'记住我'功能以及自定义登录页面的配置方法。通过实例展示了Spring Security的强大功能。
摘要由CSDN通过智能技术生成

一、概述

目前流行的安全框架有Shiro和Spring Security
Shiro较简单易用
Spring Security较复杂 但功能强大
Spring Security能无缝整合SpringBoot 因此SpringBoot底层使用的是SpringSecurity

Spring Security是针对Spring项目的安全框架 其可以实现强大的web安全控制
对于安全控制 仅需引入spring-boot-starter-security模块 然后进行少量的配置 即可实现强大的安全管理

认证和授权:
应用程序的两个主要区域是“认证”和“授权”(即访问控制)
这两个主要区域是Spring Security的两个控制目标

  • 认证”(Authentication)是建立一个声明的主体的过程
    一个主体一般是指用户 设备或一些可在应用程序中执行动作的其他系统
  • 授权”(Authorization)指确定一个主体是否允许在应用程序中执行某个动作的过程

二、使用

引入Spring Security模块的依赖:

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

然后 编写配置类:
该配置类必须继承WebSecurityConfigurerAdapter
然后给配置类上添加@EnableWebSecurity注解
@EnableWebSecurity注解已经自带了@Configuration注解 因此无须添加@Configuration注解了

1、访问权限控制及开启默认登录页

重写configure(HttpSecurity http)方法 定制请求的授权规则
使用antMatchers()方法添加路径 使用permitAll()方法允许所有用户访问 使用hasRole()方法指定可访问的角色
在这里插入图片描述
根据不同等级的页面设置不同的访问权限

@EnableWebSecurity
public class MySecurityConfig 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();
        // 通过/login请求来到登录页 若登录失败会重定向到/login?error
    }
}

默认的自动生成的登录页:
在这里插入图片描述


2、定义认证规则

使用inMemoryAuthentication()方法来配置内存中的用户
当然 还可从数据库中查询用户 此处为演示方便 只演示保存在内存中的用户

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
   

    // 定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
        // inMemoryAuthentication() 内存中的用户
        // 通过passwordEncoder()指定加密方式 通过withUser()方法来定义用户名 通过password()方法来定义密码 通过roles()方法来定义角色
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2")
        .and()
        .passwordEncoder(new B
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值