Spring Security

Spring Security

SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。

为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

其核心就是一组过滤器链,项目启动后将会自动配置。

最核心的就是 Basic Authentication Filter 用来认证用户的身份,一个在spring security中一种过滤器处理一种认证方式。

几个重要的类

  • webSecurityConfiguration : 自定义 security 策略
  • AuthenticationManagerBuilder : 自定义认证策略
  • @EnableWebSecurity : 开启 WebSecurity 模式

测试

1.导入依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

基本框架

java 复制代码
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }
}

2.根据权限认证

java 复制代码
@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();
}
java 复制代码
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //jdbcAuthentication(),在数据库中认证
    //inMemoryAuthentication()内存中认证
    //passwordEncoder(new BCryptPasswordEncoder())给密码加密
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3");
}

如果注销404了,就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能;我们试试:在 配置中增加 http.csrf().disable();

复制代码
http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
http.logout().logoutSuccessUrl("/");
java 复制代码
//没有权限默认到登录页
http.formLogin().loginProcessingUrl("/login");
//注销
http.logout().logoutSuccessUrl("/login");

动态权限控制

xml 复制代码
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>
html 复制代码
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
复制代码
sec:authorize="hasRole('vip3')"

/www.thymeleaf.org/thymeleaf-extras-springsecurity5"

复制代码

sec:authorize="hasRole('vip3')"

复制代码
相关推荐
Nebula_g11 分钟前
JavaSE基础语法:面向对象高级(代码中的成分)
java·开发语言·编程·javase·技术栈·高级语法
IT_陈寒2 小时前
Python线程池吞了异常还不告诉我,这谁顶得住啊
前端·人工智能·后端
小强库计算机毕业设计2 小时前
SpringBoot+Vue3 学生宿舍管理系统实战
java·spring boot·后端·vue·学生宿舍管理系统
小狼1832 小时前
实践6|SDD 实战:AI 写的规格被推翻了四次
后端·claude
篮框坏了2 小时前
"DeepSeek Harness 实测:一毛钱干三活,但默认配置是个坑"
后端·ai编程
李冰然2 小时前
深入Java集合框架:HashMap源码解析(JDK 8)
java
jobBridge213 小时前
大模型到底是怎么"想"的?我把 Transformer 拆开,发现它其实是个"接词狂魔"
人工智能·后端·编程语言
人道领域3 小时前
【0-1的agent进阶篇】RAG:从Embedding到检索增强生成的底层逻辑
java·embedding·agent·rag
唐青枫4 小时前
看懂内存地址之后,才算真正入门 Zig:指针、切片与实战
后端
朋克洛德的码农4 小时前
Go并发-sync包四剑客:Mutex、RWMutex、WaitGroup、Once-从入门到原理
开发语言·后端·golang