org.springframework.boot
spring-boot-starter-security
2.编写配置类
package com.fdw.springbootstudy.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
public class securityconfig extends WebSecurityConfigurerAdapter {
//授权
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().loginPage("/tologin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");
//注销报错404,需要关闭csrf功能
http.csrf().disable();
//开启记住我功能,cookie默认保存两周,input的name参数设置
http.rememberMe().rememberMeParameter("remember");
//开启注销功能,跳到首页
http.logout().deleteCookies("remove").invalidateHttpSession(true).logoutSuccessUrl("/");
}
//认证
//密码编码,PasswordEncoding
//springSecurity5.0中增加了很多加密方式
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//从内存中读,也可以在数据库中读
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("fdw").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");
}
}
数据库认证方式
效果: 整合Thymeleaf实现页面授权 引入依赖
org.thymeleaf
thymeleaf-spring5
org.thymeleaf.extras
thymeleaf-extras-java8time
org.thymeleaf.extras
thymeleaf-extras-springsecurity4
index.html页面(加了命名空间)
首页
首页
登录
用户名:
角色:
注销
Spring Security Study
Level 1
Level-1-1
Level-1-2
Level-1-3
Level 2
Level-2-1
Level-2-2
Level-2-3
Level 3
Level-3-1
Level-3-2
Level-3-3
login.html页面
登录
登录
注册
blog.kuangstudy.com Spring Security Study 定制首页
//定制登录页
http.formLogin().loginPage("/tologin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");



