初探SpringSecurity
Spring Security是一个强大的、高度可定制的身份验证和访问控制框架。它是保护基于spring的应用程序的事实上的标准。并且和springboot高度集成
快速开始
- 导入依赖
<!--thymeleaf与springsecurity5整和依赖-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<!--springsecurity依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.11.RELEASE</version>
</dependency>
<!--导入Thymeleaf依赖-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
- 编写自己的配置类,并在类上加
@EnableWebSecurity
注解,配置类继承WebSecurityConfigurerAdapter
类并实现两个核心方法
授权:configure(HttpSecurity httpSecurity)
认证:configure(AuthenticationManagerBuilder auth)
在configure(HttpSecurity httpSecurity)方法中,用户可以根据实际需要添加需要设置权限才能进入的页面已经相应的进入等级。
httpSecurity.formLogin()
开启默认的权限验证页面,用户也可也进行个性定制httpSecurity.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
表示验证页面访问/toLogin请求,用户名和密码提交至/login请求。当然默认的参数名为username和password
@EnableWebSecurity//Aop拦截器
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//super.configure(auth);
//首页所有人都可以访问,功能页,只有对应权限的人才可以访问
httpSecurity.authorizeRequests().
antMatchers("/").permitAll().
antMatchers("/level1/**").hasRole("vip1").
antMatchers("/level2/**").hasRole("vip2").
antMatchers("/level3/**").hasRole("vip3");
//没有权限默认跳到登录页
httpSecurity.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
//开启注销功能,注销成功回到首页
httpSecurity.logout().logoutSuccessUrl("/");
//开启记住我功能,放入cookie中保存
httpSecurity.rememberMe().rememberMeParameter("remember");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//super.configure(auth);
//从内存中读取数据
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("declan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");
}
}
configure(AuthenticationManagerBuilder auth)
方法中用户可以设置允许访问的用户以及权限,本例子只是把相应数据存入内存中,实际应用时可以借助数据库读取数据并授权。
前端登录页,注意看参数名username和password
<div class="ui placeholder segment">
<div class="ui column very relaxed stackable grid">
<div class="column">
<div class="ui form">
<form th:action="@{/login}" method="post">
<div class="field">
<label>Username</label>
<div class="ui left icon input">
<input type="text" placeholder="Username" name="username">
<i class="user icon"></i>
</div>
</div>
<div class="field">
<label>Password</label>
<div class="ui left icon input">
<input type="password" name="password">
<i class="lock icon"></i>
</div>
</div>
<div class="field">
记住我: <input type="checkbox" name="remember" >
</div>
<input type="submit" class="ui blue submit button"/>
</form>
</div>
</div>
</div>
</div>