新建一个SpringBoot
项目,起名springboot-security-form
,核心依赖为Web
,SpringSecurity
与Thymeleaf
。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
实验0:HttpBasic
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// There is no PasswordEncoder mapped for the id "null"
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String yourPassword = "123";
System.out.println("Encoded password: " + encoder.encode(yourPassword));
// Config account info and permissions
auth.inMemoryAuthentication()
.withUser("dev").password(encoder.encode(yourPassword)).authorities("p1")
.and()
.withUser("test").password(encoder.encode(yourPassword)).authorities("p2");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/user/add").hasAuthority("p1")
.antMatchers("/user/query").hasAuthority("p2")
.antMatchers("/user/**").authenticated()
.anyRequest().permitAll() // Let other request pass
.and()
.httpBasic();
}
实验1:自定义登录页面
- 登录页面配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/user/add").hasAuthority("p1")
.antMatchers("/user/query").hasAuthority("p2")
.antMatchers("/user/**").authenticated()
.anyRequest().permitAll() // Let other request pass
.and()
.csrf().disable() // turn off csrf, or will be 403 forbidden
.formLogin() // Support form and HT