SpringSecurity依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
thymeleaf整合SpringSecurity依赖
<!--thymeleaf整合SpringSecurity--> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> <version>3.0.4.RELEASE</version> </dependency>
SecurityConfig.java
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //请求权限 http.authorizeHttpRequests() .antMatchers("/").permitAll() .antMatchers("/a1/**").hasRole("v1") .antMatchers("/a2/**").hasRole("v2") .antMatchers("/a3/**").hasRole("v3"); //没有权限则返回默认登录界面,自定义返回登录界面loginPage(),usernameParameter对应登录表单用户名的name值 http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/toLogin").loginProcessingUrl("/login"); //关闭csrf,登录失败的原因可能因为未关闭 http.csrf().disable(); //注销返回首页 http.logout().logoutSuccessUrl("/"); //开启记住我,下次访问url,仍然保持用户登录状态,默认保存14天,rememberMeParameter对应表单内name参数 http.rememberMe().rememberMeParameter("remeber"); } //SpringSecurity5+加密 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //用户名密码对应数据库,在这里是自定义的 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("aa").password(new BCryptPasswordEncoder().encode("123456")).roles("v1") .and() .withUser("bb").password(new BCryptPasswordEncoder().encode("123456")).roles("v1","v2") .and() .withUser("cc").password(new BCryptPasswordEncoder().encode("123456")).roles("v1","v2","v3"); } }
首界面index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--未登录--> <div sec:authorize="!isAuthenticated()"> <a th:href="@{/toLogin}">登录</a> </div> <!-- 登录显示用户名--> <div sec:authorize="isAuthenticated()"> 用户名:<span sec:authentication="name"></span> </div> <div sec:authorize="isAuthenticated()"> <a th:href="@{/toLogin}">退出</a> </div> <!--判断权限,有权限显示--> <div sec:authorize="hasRole('v1')"> <a th:href="@{/a1/a1}">v1权限所显示的界面</a> </div> <div sec:authorize="hasRole('v2')"> <a th:href="@{/a2/a2}">v2权限所显示的界面</a> </div> <div sec:authorize="hasRole('v3')"> <a th:href="@{/a3/a3}">v3权限所显示的界面</a> </div> </body> </html>