springboot的jar包地址:
导入依赖:
thymeleaf:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
SpringSecurity:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
简介
地址:
SpringSecurity 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,只需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理,SpringSecurity的两个主要目标是“认证”和“授权”(访问控制)
package com.working.study.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;
/**
* WebSecurityConfigurerAdapter: 自定义Security策略。
*
* AuthenticationManagerBuilder: 自定义认证策略。
*
* @EnableWebSecurity: 开启WebSecurity模式。
*/
@EnableWebSecurity
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//授权规则
http.authorizeRequests()
// “/”下的都可以访问
.antMatchers("/").permitAll()
// “/”下的只有“gj”可以访问
.antMatchers("/gj").hasRole("gj");
//配置没有权限默认页面
http.formLogin();
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//数据库(jdbc)里进行数据认证
//auth.jdbcAuthentication().dataSource(dataSource)
//内存里进行数据认证
auth.inMemoryAuthentication()
//设置密码编码加密
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("gj").password(new BCryptPasswordEncoder().encode("666666")).roles("权限1","权限2","权限3","...")
//通过and()拼接
.and()
.withUser("gj1").password(new BCryptPasswordEncoder().encode("997997")).roles("权限1","权限2");
}
}