Spring Boot----安全
SpringBoot 整合 shiro(略)
SpringBoot 整和 Spring Security
官方文档:https://docs.spring.io/spring-security/site/docs/5.1.6.RELEASE/reference/htmlsingle/
1、添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2、登录权限配置
@EnableWebSecurity public class MySecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //super.configure(http); //定制请求授权规则 http.authorizeRequests().antMatchers("/static/**").permitAll() .antMatchers("/leve1").hasRole("vip1"); http.formLogin().loginProcessingUrl("/login"); //配置注销功能 http.logout(); //开启记住我功能 http.rememberMe(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //方法1 //PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); //auth.inMemoryAuthentication().withUser("zy").password(encoder.encode("123")).roles("vip1"); //方法2 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("zy").password(new BCryptPasswordEncoder().encode("123")).roles("vip1"); } }
2、注销权限配置
Spring Security整和thymeleaf
参考:https://docs.spring.io/spring-security/site/docs/current/guides/html5//helloworld-boot.html
1、引入依赖
<dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> <version>3.0.4.RELEASE</version> </dependency>
2、html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5"> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/logout" method="get"> <input type="submit" value="提交"> </form> <div sec:authorize="!isAuthenticated()"> 请登录:游客 </div> <div sec:authorize="isAuthenticated()"> 用户:<span sec:authentication="name"></span> --您拥有的权限:<span sec:authentication="principal.authorities"></span> <form th:action="@{/logout}" method="post"><input type="submit" value="注销"></form> <!--url 必须写成 th:action="@{/logout}" 这种格式,method:post--> </div> <div sec:authorize="hasRole('vip1')"> <li>只有有了vip1权限,这个li才会显示</li> </div> </body> </html>
3、自定义用户登录页面
1、修改configure方法中的配置
//走的是controller http.formLogin().usernameParameter("user").passwordParameter("password").loginPage("/login"); //默认login get请求到登录页面 //默认login post请求处理登录 //如果自定制了页面,如果loginPage("/login"),提交表单的时候的url是如果loginPage中写的url //开启记住我功能(自定义的html页面) http.rememberMe().rememberMeParameter("remember");
2、html
<form th:action="@{/login}" method="post"> //url必须用@{} 来写 <input name="user"> <input name="password"> <input type="checkbox" name="remember"> <input type="submit" value="登录"> </form>