⒈添加starter依赖
1 <dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-web</artifactId>
4 </dependency>
5
6 <dependency>
7 <groupId>org.springframework.boot</groupId>
8 <artifactId>spring-boot-starter-security</artifactId>
9 </dependency>
10
11 <dependency>
12 <groupId>org.springframework.boot</groupId>
13 <artifactId>spring-boot-starter-thymeleaf</artifactId>
14 </dependency>
15
16 <!--添加Thymeleaf Spring Security依赖-->
17 <dependency>
18 <groupId>org.thymeleaf.extras</groupId>
19 <artifactId>thymeleaf-extras-springsecurity4</artifactId>
20 <version>3.0.4.RELEASE</version>
21 </dependency>
⒉使用配置类定义授权与定义规则
1 package cn.coreqi.config;
2
3 import org.springframework.context.annotation.Configuration;
4 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
5 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
6 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
7 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
8
9 //@Configuration
10 @EnableWebSecurity
11 public class SecurityConfig extends WebSecurityConfigurerAdapter {
12
13 //定义授权规则
14 @Override
15 protected void configure(HttpSecurity http) throws Exception {
16 //定制请求授权规则
17 http.authorizeRequests()
18 .antMatchers("/css/**","/js/**","/fonts/**","index").permitAll() //不拦截,直接访问
19 .antMatchers("/vip1/**").hasRole("VIP1")
20 .antMatchers("/vip2/**").hasRole("VIP2")
21 .antMatchers("/vip3/**").hasRole("VIP3");
22 //开启登陆功能(自动配置)
23 //如果没有登陆就会来到/login(自动生成)登陆页面
24 //如果登陆失败就会重定向到/login?error
25 //默认post形式的/login代表处理登陆
26 http.formLogin().loginPage("/userLogin").failureUrl("/login-error");
27 //开启自动配置的注销功能
28 //访问/logout表示用户注销,清空session
29 //注销成功会返回/login?logout页面
30 //logoutSuccessUrl()设置注销成功后跳转的页面地址
31 http.logout().logoutSuccessUrl("/");
32 //开启记住我功能
33 //登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登陆
34 //点击注销会删除cookie
35 http.rememberMe();
36 }
37
38 //定义认证规则
39 @Override
40 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
41 //jdbcAuthentication() 在JDBC中查找用户
42 //inMemoryAuthentication() 在内存中查找用户
43
44 auth.inMemoryAuthentication().withUser("fanqi").password("admin").roles("VIP1","VIP2","VIP3")
45 .and()
46 .withUser("zhangsan").password("123456").roles("VIP1");
47 }
48 }
⒊编写控制器类(略)
⒋编写相关页面
1 <!DOCTYPE html>
2 <html lang="en"
3 xmlns:th="http://www.thymeleaf.org"
4 xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
5 xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
6 <head>
7 <meta charset="UTF-8">
8 <title>登录页面</title>
9 </head>
10 <body>
11 <div sec:authorize="isAuthenticated()">
12 <p>用户已登录</p>
13 <p>登录的用户名为:<span sec:authentication="name"></span></p>
14 <p>用户角色为:<span sec:authentication="principal.authorities"></span></p>
15 </div>
16 <div sec:authorize="isAnonymous()">
17 <p>用户未登录</p>
18 </div>
19 </body>
20 </html>