依赖
org.springframework.boot spring-boot-starter-weborg.thymeleaf thymeleaf-spring5org.thymeleaf.extras thymeleaf-extras-java8timeorg.springframework.boot spring-boot-starter-securityorg.thymeleaf.extras thymeleaf-extras-springsecurity53.0.4.RELEASE org.springframework.boot spring-boot-starter-testtest org.junit.vintage junit-vintage-engine
Controller:
package com.blu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RouterController {
@RequestMapping({ "/", "/index" })
public String index() {
return "index";
}
@RequestMapping("/tologin")
public String toLogin() {
return "views/login";
}
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id) {
return "views/level1/" + id;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id") int id) {
return "views/level2/" + id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id) {
return "views/level3/" + id;
}
}
SecurityConfig:
package com.blu.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{
@Override
protected void configure(HttpSecurity http) throws Exception {
//所有人可以访问首页,功能页需要指定权限才可以访问
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("BLU").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("111222")).roles("vip1");
}
}
注:以上方式认证的用户和角色信息是存储在内存中的,在实际开发中应该从数据库中获取,详见:SpringSecurity从数据库中获取用户信息进行验证
index.html
首页 首页 登录 用户名: 角色: 注销 Spring Security Study by BLU
Level 1
Level-1-1 Level-1-2 Level-1-3Level 2
Level-2-1 Level-2-2 Level-2-3Level 3
Level-3-1 Level-3-2 Level-3-3
views/login.html
登录 登录 注册
736917155@qq.com Spring Security Study by BLU
views/level1/1.html
首页 Level-1-1
views/level2/1.html 等其他页面:略
运行效果:
项目源码:
链接: https://pan.baidu.com/s/1AtbcCht84NT-69-sSUAQRw
提取码: nh92
到此这篇关于SpringBoot与SpringSecurity整合的文章就介绍到这了,更多相关SpringBoot与SpringSecurity整合内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!



