这里使用的thymeleaf做渲染
org.springframework.boot spring-boot-starter-securityorg.springframework.boot spring-boot-starter-thymeleaforg.thymeleaf.extras thymeleaf-extras-springsecurity53.0.4.RELEASE
SecurityConfig配置
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//登录配置
//loginPage() 自定义login的路径
//usernameParameter() and passwordParameter() 自定义接收的name参数
//loginProcessingUrl() 自定义请求的路径
http.formLogin().loginPage("/toLogin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");
//退出登录url配置
//logoutSuccessUrl() 定义退出后的路径
http.logout().logoutSuccessUrl("/");
//自定义记住我
http.rememberMe().rememberMeParameter("rememberMe");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1").and()
.withUser("wu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3").and()
.withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2");
// JDBC方式
// @Autowired()
// private DataSource dataSource;
// auth.jdbcAuthentication()
// .dataSource(datasource)
// .withUser("admin").password("password").roles("admin")
// .withUser("root").password("password").roles("admin")
}
}
RoutingController配置
@Controller
public class RoutingController {
@RequestMapping({"/","/index"})
public String index(){
return "index";
}
@RequestMapping("/toLogin")
public String login()
{
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;
}
}
判断是否已经登陆认证sec:authorize="isAuthenticated()"
获得用户名sec:authentication=“name”
判断权限sec:authorize=“hasRole(‘vip1’)”
获得角色(权限)sec:authentication="principal.authorities"
获取ID地址sec:authentication="details.remoteAddress"
获得会话IDsec:authentication="details.sessionId"
- 前端的一些代码
在控制类Controller上加@IsUser // 表明该控制器下所有请求都需要登入后才能访问



