1-新建一个项目

springboot安全之整合spring security_html

,先不引入security

springboot安全之整合spring security_ide_02

,引入

springboot安全之整合spring security_spring_03

,

springboot安全之整合spring security_spring_04

2-resources->templates->welcome.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>sdfasfa</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
<hr>

<h3>普通武功秘籍</h3>
<ul>
<li><a th:href="@{/level1/1}">罗汉拳</a></li>
<li><a th:href="@{/level1/2}">武当长拳</a></li>
<li><a th:href="@{/level1/3}">全真剑法</a></li>
</ul>

<h3>高级武功秘籍</h3>
<ul>
<li><a th:href="@{/level2/1}">太极拳</a></li>
<li><a th:href="@{/level2/2}">七伤拳</a></li>
<li><a th:href="@{/level2/3}">梯云纵</a></li>
</ul>

<h3>绝世武功秘籍</h3>
<ul>
<li><a th:href="@{/level3/1}">葵花宝典</a></li>
<li><a th:href="@{/level3/2}">龟派气功</a></li>
<li><a th:href="@{/level3/3}">独孤九剑</a></li>
</ul>
</body>
</html>

3-resources->templates->pages->level1->1.html,2.html,3.html

springboot安全之整合spring security_html_05

...

   resources->templates->pages->level2->1.html,2.html,3.html

   resources->templates->pages->level3->1.html,2.html,3.html

4-新建controller包KungfuController类

package com.example.springboot05security.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class KungfuController {
private final String PREFIX = "pages/";

/**
* 欢迎页
* @return
*/
@GetMapping("/")
public String index(){
return "welcome";
}

/**
* 登录页
* @return
*/
@GetMapping("/userlogin")
public String loginPage(){
return PREFIX+"login";
}

/**
* level1页面映射
* @param path
* @return
*/
@GetMapping("/level1/{path}")
public String level1(@PathVariable("path")String path){
return PREFIX+"level1/"+path;
}

/**
* level2页面映射
* @param path
* @return
*/
@GetMapping("/level2/{path}")
public String level2(@PathVariable("path")String path){
return PREFIX+"level2/"+path;
}

/**
* level3页面映射
* @param path
* @return
*/
@GetMapping("/level3/{path}")
public String level3(@PathVariable("path")String path){
return PREFIX+"level3/"+path;
}
}

springboot安全之整合spring security_html_06

5-引入SpringSecurity

pom.xml中新增

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

6-编写SpringSecurity的配置类

spring官网->PROJECTS->SPRING SECURITY

访问​​https://docs.spring.io/spring-security/site/docs/current/guides/html5/​

springboot安全之整合spring security_html_07

新建config包MySecurityConfig类

package com.example.springboot05security.config;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
}

 

7-控制请求的访问权限

springboot安全之整合spring security_html_08

package com.example.springboot05security.config;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http); 父类方法需要注释掉
//定制请求的授权规则 .permitAll() 允许所有用户访问 .hasRole("xxx") 只有xxx用户才能访问
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
}
}

此时,访问首页时,

springboot安全之整合spring security_html_09

访问其他页面时.

springboot安全之整合spring security_html_10

8-加入登录

springboot安全之整合spring security_html_11

HttpSecurity中,

/**
* Specifies to support form based authentication. If
* {@link FormLoginConfigurer#loginPage(String)} is not specified a default login page
* will be generated.
*
* <h2>Example Configurations</h2>
*
* The most basic configuration defaults to automatically generating a login page at
* the URL "/login", redirecting to "/login?error" for authentication failure. The
* details of the login page can be found on
* {@link FormLoginConfigurer#loginPage(String)}
*
* <pre>
* @Configuration
* @EnableWebSecurity
* public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {
*
* @Override
* protected void configure(HttpSecurity http) throws Exception {
* http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin();
* }
*
* @Override
* protected void configure(AuthenticationManagerBuilder auth) throws Exception {
* auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
* }
* }
* </pre>
*
* The configuration below demonstrates customizing the defaults.
*
* <pre>
* @Configuration
* @EnableWebSecurity
* public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {
*
* @Override
* protected void configure(HttpSecurity http) throws Exception {
* http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
* .usernameParameter("username") // default is username
* .passwordParameter("password") // default is password
* .loginPage("/authentication/login") // default is /login with an HTTP get
* .failureUrl("/authentication/login?failed") // default is /login?error
* .loginProcessingUrl("/authentication/login/process"); // default is /login
* // with an HTTP
* // post
* }
*
* @Override
* protected void configure(AuthenticationManagerBuilder auth) throws Exception {
* auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
* }
* }
* </pre>
*
* @see FormLoginConfigurer#loginPage(String)
*
* @return the {@link FormLoginConfigurer} for further customizations
* @throws Exception
*/
public FormLoginConfigurer<HttpSecurity> formLogin() throws Exception {
return getOrApply(new FormLoginConfigurer<>());
}

 

9-重写定义认证规则方法

springboot安全之整合spring security_spring_12

springboot安全之整合spring security_ide_13

 

package com.example.springboot05security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http); 父类方法需要注释掉
//定制请求的授权规则 .permitAll() 允许所有用户访问 .hasRole("xxx") 只有xxx用户才能访问
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");

//开启自动配置的登录功能,如果没有登录,没有权限就会来到自动生成的登录页面
http.formLogin(); // /login来到登录页,重定向到/login?error表示登录失败
}

//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//super.configure(auth);
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2")
.and()
.withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2","VIP3")
.and()
.withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP3");
}
}

即可完成登录及认证与授权

10-注销功能


MySecurityConfig类中添加


springboot安全之整合spring security_html_14

welcome.html中添加 

<form th:action="@{/logout}" method="post">
<input type="submit" value="注销" />
</form>

 

springboot安全之整合spring security_html_15

springboot安全之整合spring security_spring_16

 

修改MySecurityConfig类,使注销成功之后返回首页

springboot安全之整合spring security_html_17

11-页面使用权限控制

springboot安全之整合spring security_html_18

查看依赖

springboot安全之整合spring security_html_19

点进starter-parent

springboot安全之整合spring security_spring_20

进入dependencies

springboot安全之整合spring security_spring_21

可以看到

springboot安全之整合spring security_html_22

如果需要换版本

 可以在pom中写入

springboot安全之整合spring security_html_23

此时出现sec标签不生效的问题:

解决:

pom.xml中添加

<!--引入>thymeleaf-extras-springsecurity5-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>

welcome.html如下

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>sdfasfa</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div sec:authorize="!isAuthenticated()">
<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
<h2>
<span sec:authentication="name"></span>,您好,您的角色有:
<span sec:authentication="principal.authorities"></span>
</h2>
<form th:action="@{/logout}" method="post">
<input type="submit" value="注销" />
</form>
</div>

<hr>

<div sec:authorize="hasRole('VIP1')">
<h3>普通武功秘籍</h3>
<ul>
<li><a th:href="@{/level1/1}">罗汉拳</a></li>
<li><a th:href="@{/level1/2}">武当长拳</a></li>
<li><a th:href="@{/level1/3}">全真剑法</a></li>
</ul>
</div>

<div sec:authorize="hasRole('VIP2')">
<h3>高级武功秘籍</h3>
<ul>
<li><a th:href="@{/level2/1}">太极拳</a></li>
<li><a th:href="@{/level2/2}">七伤拳</a></li>
<li><a th:href="@{/level2/3}">梯云纵</a></li>
</ul>
</div>

<div sec:authorize="hasRole('VIP3')">
<h3>绝世武功秘籍</h3>
<ul>
<li><a th:href="@{/level3/1}">葵花宝典</a></li>
<li><a th:href="@{/level3/2}">龟派气功</a></li>
<li><a th:href="@{/level3/3}">独孤九剑</a></li>
</ul>
</div>

</body>
</html>

springboot安全之整合spring security_ide_24

 

 

springboot安全之整合spring security_spring_25

12-开启记住我功能

springboot安全之整合spring security_spring_26


//登录成功时,将cookie发送给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录,点击注销会删除cookie


springboot安全之整合spring security_ide_27

springboot安全之整合spring security_html_28

注销的时候

springboot安全之整合spring security_ide_29

13-定制登录页

修改welcome.html

springboot安全之整合spring security_ide_30

修改MySecurityConfig

springboot安全之整合spring security_ide_31

templates->pages文件夹下新建login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>定制的登录页</title>
</head>
<body>
<h1 align="center">欢迎登录武林秘籍管理系统</h1>
<hr>
<div align="center">
<form th:action="@{/userlogin}" method="post">
用户名:<input name="user" /><br>
密码:<input name="pwd"><br>
<input type="submit" value="登录">
</form>
</div>
</body>
</html>

或者:

springboot安全之整合spring security_html_32

springboot安全之整合spring security_html_33

springboot安全之整合spring security_ide_34

springboot安全之整合spring security_ide_35

14-定制页面添加remember me功能

springboot安全之整合spring security_html_36

springboot安全之整合spring security_spring_37