05 Spring Boot 整合Spring Security

时间:2022-07-22
本文章向大家介绍05 Spring Boot 整合Spring Security,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

整合Spring Security

整合方法

  1. 创建项目时选择security依赖或在pom中添加security依赖
  2. 建立SpringSecurityConfig类,继承WebSecurityConfigurerAdapter方法
  3. 在刚刚创建的类上添加@EnableWebSecurity注解
  4. 设置授权规则 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").permitAll() //所有人均可访问 .antMatchers("/level1/**").hasRole("vip1") //vip1可访问 .antMatchers("/level2/**").hasRole("vip2") //vip3可访问 .antMatchers("/level3/**").hasRole("vip3"); //vip3可访问 http.formLogin() //启动security自带login页面 .loginPage("/toLogin") //设置自定义login页面 .loginProcessingUrl("/login") //设置自定义login认证页面 .usernameParameter("user") //设置login页面中的账户参数名 .passwordParameter("pwd"); //设置login页面中的密码参数名 http.logout() //logout:添加登出页面 .logoutSuccessUrl("/"); //logoutSuccessUrl:添加登出后跳转页面 http.rememberMe() //开启记住我功能 .rememberMeParameter("rem"); //设置记住我参数名 }
  5. 设置角色 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("shimeath").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3") .and() .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3") .and() .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1"); }

Spring security整合thymeleaf

  1. 添加maven依赖 <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> </dependency> 2.添加命名空间 xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
  2. 常用方法 sec:authorize <!-- 授权 --> sec:authentication <!-- 认证方式 --> <!-- 函数 --> isAuthenticated() <!-- 已登录吗 --> hasRole('vip1') <!-- 判断角色 -->