一、SpringSecurity概述
SpringSecurity是针对Spring项目的安全框架,也是SpringBoot底层安全模块默认的技术选型。它可以实现强大的web安全控制,对于安全控制,我们仅需引入spring-boot-starter-security模块,进行少量的配置,即可以实现强大的安全管理。
1.两个概念:
- 认证(Authentication):是建立一个他声明的主体的过程(一个“主体”一般是指用户,设备或一些可以在你应用程序中执行动作的其他系统);
- 授权(Authorization):指确定一个主体是否允许在你的应用程序执行一个动作的过程。为了抵达需要授权的店,主体的身份已经有认证过程的建立。
二、SpringBoot集成SpringSecurity
1. 引入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. 搭建测试环境
3.编写配置类
@EnableWebSecurity
public class MySecurityConfig{
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// 定制请求的授权规则
http
.authorizeHttpRequests((authorize) -> authorize
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3")
)
.httpBasic(withDefaults())
//开启自动配置的登录功能
//1. /login来到登录页
//2. 重定向到/login?error表示登录失败
//3.更多详细规定
//4.默认post形式的/login 代表处理登录
//5.一旦定制loginPage:那么loginPage的post请求就是登录
.formLogin(httpSecurityFormLoginConfigurer -> {
httpSecurityFormLoginConfigurer
//跳转到自定义登录页
.loginPage("/userlogin")
//登录表单用户名称参数名称指定,默认username
.usernameParameter("user")
//登录表单密码参数名称指定,默认password
.passwordParameter("pwd")
//登录失败跳转路径
.failureForwardUrl("/");
//指定登录表单提交路径
//.loginProcessingUrl("/login");
})
//自动配置的注销功能
//1.访问 /logout 表示用户注销,清空session
//2. 注销成功会返回 /login?success 页面
.logout().logoutSuccessUrl("/");//注销成功来到首页
//开启记住我功能
//登录成功后,将cookie发送给浏览器保存,以后访问页面带上这个cookie,只要通过检测就会免登录
//点击注销会删除cookie
http.rememberMe().rememberMeParameter("remeber").userDetailsService(this.userDetailsService());
//http.csrf().disable();
return http.build();
}
// 定义认证规则
@Bean
@Order(1)
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("VIP1")
.build();
return new InMemoryUserDetailsManager(user);
}
}
本文介绍SpringSecurity的基本概念,包括认证和授权,并演示如何在SpringBoot项目中集成SpringSecurity,实现自定义的安全控制。
6943

被折叠的 条评论
为什么被折叠?



