SpringBoot整合Security
依赖
<!-- thymeleaf整合springsecurity5包-->
<!-- 整合了之后再HTML页面配合xmlns:sec="http://www.thymeleaf.org/extras/spring-security"命名空间,
可以提示sec: 类型语句
sec:authorize="isAuthenticated()":判断是已经认证
-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<!-- springboot整合security包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- web包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springboot整合thymeleaf包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置SecurityConfig
@EnableWebSecurity // 开启WebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 授权配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() //授权请求
.antMatchers("/").permitAll() // '/'地址所有人可以访问
.antMatchers("/level1/**").hasRole("vip1") // level1下所有地址只有vip1用户才可以访问
.antMatchers("/level2/**").hasRole("vip2") // level2下所有地址只有vip2用户才可以访问
.antMatchers("/level3/**").hasRole("vip3") // level3下所有地址只有vip3用户才可以访问
.and()
.formLogin() // 开启登录页面,没有权限会跳转至登录页面
.loginPage("/toLogin") // 定制登录页
.loginProcessingUrl("/login") //定制登录成功的form表单提交地址
.usernameParameter("user") // 指定前端传入的用户名字段名称,security默认为username
.passwordParameter("pwd") // 指定前端传入的密码字段名称,security默认为password
.and()
.logout().logoutSuccessUrl("/") // 开启注销功能,指定注销成功跳转地址
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET")) // 定制了登录页之后,需要再指定注销请求地址和请求方式
.and()
.rememberMe() // 开启记住我功能
.rememberMeParameter("remember"); // 记住我前端配置字段名称
}
// 认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication() // 在内存中认证:inMemoryAuthentication() ,在数据认证:jdbcAuthentication()
.passwordEncoder(new BCryptPasswordEncoder()) // 设置密码编码
.withUser("lzp").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3") // 配置用户名,密码,角色
.and()
.withUser("hye").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3");
}
}