<!--SpringSecurity 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
package com.juju.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 = 用户验证
http.authorizeRequests()
.antMatchers("/").permitAll()//antMatchers =那个页面 再.就是谁可访问permitAll=所有人
.antMatchers("/level1/**").hasRole("vip1")//leverl1下面的所有页面,只有vip1权限的人有权访问
.antMatchers("/level2/**").hasRole("vip2")//leverl2下面的所有页面,只有vip2权限的人有权访问
.antMatchers("/level3/**").hasRole("vip3");//lever31下面的所有页面,只有vip3权限的人有权访问
//没有权限默认会跳到登陆页面,需要开启登陆的页面
//为什么会到/login页面
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");//loginPage() 是定制登陆页面的,toLogin是在controller上写的,去登陆页面的方法
http.rememberMe().rememberMeParameter("remember"); //开启记住我功能,cook默认保存两周
//注销,开启了注销功能
http.csrf().disable(); //关闭防止跨站脚本攻击功能
http.logout().logoutSuccessUrl("/");//注销后到首页
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/**
* inMemoryAuthentication = 内存认证
* jdbcAuthentication = 数据库认证
*
* whitUser =用户名
* password = 密码
* roles = 拥有的权限
*
* ps:
* 在Spring Secutiry 5。0x中,新增了很多的加密方式,如果不加密就会报错,不让你使用
* 1.解决方法:在内存/数据库认证后面加 .passwordEncoder(new BCryptPasswordEncoder())
* 2.在.password(new BCryptPasswordEncoder().encode("123456"))
*/
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("juju").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
}
}
package com.juju.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;
}
}
补充下:
评论