SpringBoot-SpringSecurity

Spring Security 中文文档:https://springdoc.cn/spring-security/
Thymeleaf:https://www.thymeleaf.org/


依赖




<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-securityartifactId>
dependency>

<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-webartifactId>
dependency>

<dependency>
	<groupId>org.thymeleafgroupId>
	<artifactId>thymeleaf-spring5artifactId>
dependency>
<dependency>
	<groupId>org.thymeleaf.extrasgroupId>
	<artifactId>thymeleaf-extras-java8timeartifactId>
dependency>

application.yml

spring:
  thymeleaf:
    # 关闭缓存
    cache: false
    # 视图解析配置
    prefix: classpath:/templates/
    suffix: .html

SecurityConfig.java

// 开启 WebSecurity 并交给 spring 管理
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 请求授权规则:这些请求需要校验权限
        http.authorizeRequests()
                // 所有人都能访问
                .antMatchers("/").permitAll()
                // 限定角色可以访问
                .antMatchers("/vip/1").hasRole("vip1")
                .antMatchers("/vip/2").hasRole("vip2")
                .antMatchers("/vip/3").hasRole("vip3");
        // 没有权限默认返回登录页面
        http.formLogin()
                // 定制登录页
                .loginPage("/toLogin")
                // 自定义验证参数名
                .usernameParameter("username")
                .passwordParameter("password")
                // 登录页面提交的数据从这里认证
                .loginProcessingUrl("/login");
        // 关闭跨域访问
        http.csrf().disable();
        // 开启注销功能:注销成功默认返回登录页
        http.logout().logoutSuccessUrl("/");// 返回首页
        // 开启记住我功能:生成 session 和 cookie 默认有效期 14天
        http.rememberMe().rememberMeParameter("rememberMe");
    }
    // 认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 注入数据源,从数据库认证
        // auth.jdbcAuthentication().dataSource(dataSource).withDefaultSchema().withUser("");
        // 从内存中认证
        auth.inMemoryAuthentication()
                // 设置密码加密方式
                .passwordEncoder(new BCryptPasswordEncoder())
                // 用户名、加密的密码、角色
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                // 拼接多个用户
                .and()
                .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

controller

@Controller
public class RouterController {
    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "views/login";
    }
    @RequestMapping("/vip/{id}")
    public String vip(@PathVariable("id") Integer id){
        return "views/vip/vip" + id;
    }
}

你可能感兴趣的:(spring,boot)