构建Security的环境

一·导入依赖
1.首先在springboot项目中导入thymeleaf的依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

2.导入thymeleaf-extras-springsecurity5 的依赖

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    </dependency>

3.导入security的依赖


org.springframework.boot
spring-boot-starter-security

二·在主目录下建包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;
}
}
三·新建config包,用Security设置请求授权以及登录认证
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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/").hasRole("vip1")
.antMatchers("/level2/
").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");

// 没有授权会默认到登录页面
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
// 开启注销功能
http.csrf().disable();
http.logout().logoutSuccessUrl("/");
// 开启记住我功能 cookie
http.rememberMe().rememberMeParameter("remeber");
}
// 认证
//密码编码 passwordencoder
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 这些数据正常从数据库中读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("zhang").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
.and()
.withUser("xin").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
.and()
.withUser("java").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
}
}
四·打开application.properties
添加
spring.thymeleaf.cache=false
五·项目所需前端文件已上传

构建Security的环境

上一篇:123456


下一篇:jQuery1.11源码分析(7)-----jQuery一些基本的API