SpringBoot整合Spring Security

本文介绍了Spring Security作为Spring Boot安全框架的使用,通过引入spring-boot-starter-security模块,配合WebSecurityConfigurerAdapter、AuthenticationManagerBuilder等关键类,实现认证和授权功能。Spring Security的核心目标包括用户认证与访问控制。

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

一、简介

Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
1.WebSecurityConfigurerAdapter: 自定义Security策略
2.AuthenticationManagerBuilder: 自定义认证策略
3.@EnableWebSecurity: 开启WebSecurity模式
Spring Security的两个主要目标是“认证”和“授权”(访问控制)。
“认证”(Authentication)
"授权”(Authorization)
这个概念是通用的,而不是只在Spring Security中存在。


二、配置Spring Security

1.导入依赖(这里导入了SpringSecurity和Thymeleaf)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.3.4.RELEASE</version>
</dependency>
<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>
    <version>2.3.4.RELEASE</version>
</dependency>

2.编写对应的配置

@EnableWebSecurity//开启Security服务
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");
        //没有权限默认跳转到登陆页面,需要开启登陆页面 loginProcessingUrl是指前端请求地址 loginPage是指实际请求地址
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
        //开启注销功能
        http.logout().logoutSuccessUrl("/");
        //将信息存在cookie中
        http.rememberMe().rememberMeParameter("remember-me");
//        super.configure(http);
    }
    //认证
    //密码编码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("mi").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");
//        super.configure(auth);
    }
}

具体见文件

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值