SpringSecurity回顾

本文详细回顾了SpringSecurity的配置过程,包括加入SpringSecurity环境、放行首页和静态资源、实现登录流程、退出登录、基于角色的访问控制以及密码加密。通过设置web.xml、创建配置类以及实现UserDetailsService接口等步骤,逐步展示了SpringSecurity在实际应用中的配置和使用。

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

1. SpringSecurity 回顾

1.1 准备工作

准备 SpringMVC 的环境。发送请求访问资源时完全没有限制。

1.2 加入 SpringSecurity 环境

1.2.1 加入 SpringSecurity 依赖

在这里插入图片描述

<!-- SpringSecurity 对 Web 应用进行权限管理 -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <!-- SpringSecurity 配置 -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <!-- SpringSecurity 标签库 -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
        </dependency>

1.2.2 在 web.xml 中配置 DelegatingFilterProxy

<!-- SpringSecurity 的 Filter -->
            <filter>
              <filter-name>springSecurityFilterChain</filter-name>
              <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
            </filter>
            <filter-mapping>
              <filter-name>springSecurityFilterChain</filter-name>
              <url-pattern>/*</url-pattern>
            </filter-mapping>

注意:SpringSecurity 会根据 DelegatingFilterProxy 的 filter-name 到 IOC 容器中
查找所需要的 bean。所以 filter-name 必须是 springSecurityFilterChain 名字。

1.2.3 创建基于注解的配置类

在这里插入图片描述

// 注意!这个类一定要放在自动扫描的包下,否则所有配置都不会生效!
// 将当前类标记为配置类
@Configuration
// 启用 Web 环境下权限控制功能
@EnableWebSecurity
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {
   
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
   
// 与 SpringSecurity 环境下用户登录相关
}
@Override
protected void configure(HttpSecurity security) throws Exception {
   
// 与 SpringSecurity 环境下请求授权相关
}
}

1.3 放行首页和静态资源

security
.authorizeRequests()	// 对请求进行授权
.antMatchers("/index.jsp")	// 针对/index.jsp 路径进行授权
.permitAll()	// 可以无条件访问
.antMatchers("/layui/**")	// 针对/layui 目录下所有资源进行授权
.permitAll()	// 可以无条件访问
.and()
.authorizeRequests()	// 对请求进行授权
.anyRequest()	// 任意请求
.authenticated()	// 需要登录以后才可以访问

设置授权信息时需要注意,范围小的放在前面、范围大的放在后面。不然的话,小范围的设置会被大范围设置覆盖。
效果:未登录请求访问需要登录的请求时会看到 403 页面。

1.4 未认证请求跳转到登录页

security
……
.and()
.formLogin()
// 使用表单形式登录
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值