官网:https://spring.io/projects/spring-security
一:建立并配置项目
导入thymeleaf依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
导入security依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
然后建立对应的html文件结构。
建立config对应文件,路由可以用自配的,也可以直接去Controller中写,这里主要介绍Security的配置文件。
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
}
}
路由详情:
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/vip1").setViewName("/vip1/vip1");
registry.addViewController("/vip2").setViewName("/vip2/vip2");
}
}
yaml中关闭thymeleaf缓存:
spring:
thymeleaf:
cache: false
server:
port: 8045
访问,出现如下界面说明security已经拦截了我们的请求
二:配置Security规则
于是现在我们希望它不再拦截我们的所有页面,放开login页,但其他页面需要权限访问,在Security文件中修改:
.antMatchers("/"):添加一个security的路由路径
.permitAll():允许所有人访问
.hasRole(“vip2”):设定特定人访问
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/vip1").hasRole("vip1")
.antMatchers("/vip2").hasRole("vip2");
//权限不足跳转登录页面
http.formLogin();
}
}
访问的时候主页随便进,但访问其他路径会提示权限不允许
但是这样还是不能登录,所以需要进行配置密码和用户。
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/vip1").hasRole("vip1")
.antMatchers("/vip2").hasRole("vip2");
//权限不足跳转登录页面
http.formLogin();
//注销,直接在前台用thymeleaf加th:href="@{/logout}"即可
http.logout().logoutSuccessUrl("/");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1","vip2")
.and()
.withUser("user").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1");
}
}
然后输入密码,对应的角色即可访问我们的页面
以及可以配置一下rememberme功能。
当然如果不想要它默认提供的页面,可以用loginpage指向自己定制的页面