SpringBoot与安全—Spring Security

目录

 

一、介绍

二、测试环境搭建

1、pom.xml文件

2、Controller

3、页面

二、登录&认证&授权

1、引入spring-security相关依赖

2、编写SpringSecurity配置类

3、控制请求的访问权限

三、注销

四、实现按角色显示对应的内容

1、Thymeleaf提供的SpringSecurity标签支持 –需要引入thymeleaf-extras-springsecurity4 

2、页面上引入thymeleaf

五、记住我&定制登录页

1、记住我

2、定制登录页

完整代码:

1、pom.xml

2、Controller

3、config

4、页面

(1)welcome.html

(2)login.html


一、介绍

Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模 块默认的技术选型。他可以实现强大的web安全控制。对于安全控制,我们仅 需引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的 安全管理。
几个类:

WebSecurityConfigurerAdapter:自定义Security策略

AuthenticationManagerBuilder:自定义认证策略

@EnableWebSecurity:开启WebSecurity模式

 应用程序的两个主要区域是“认证”和“授权”(或者访问控制)。 这两个主要区域是Spring Security 的两个目标。
• “认证”(Authentication),是建立一个他声明的主体的过程(一 个“主体”一般是指用户,设备或一些可以在你的应用程序中执行动 作的其他系统)。
• “授权”(Authorization)指确定一个主体是否允许在你的应用程序 执行一个动作的过程。为了抵达需要授权的店,主体的身份已经有认 证过程建立。
• 这个概念是通用的而不只在Spring Security中。

二、测试环境搭建

1、pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot_security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_security</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
       
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、Controller

@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;
	}


}

3、页面

访问:http://localhost,会自动跳转到welcome.html页面

二、登录&认证&授权

1、引入spring-security相关依赖

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

2、编写SpringSecurity配置类

(1)@EnableWebSecurity

(2)extends WebSecurityConfigurerAdapter

3、控制请求的访问权限

ctrl+O:打开能够重写的方法

(1)定义授权规则

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //定义授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        //定制请求的授权规则
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");
        //开启自动配置的登录功能,如果没有权限,就会来到登录页面
        http.formLogin();
        //1、/login来到登录页
        //2、重定向到/login?error表示登录失败
        //3、更多详细规定
    }
}

(2)定义认证规则

//定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        //这里本来应该查询数据库的,但是emmm
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("VIP1","VIP2")
                .and().withUser("lisi").password("123456").roles("VIP2","VIP3")
                .and().withUser("wangwu").password("123456").roles("VIP3","VIP1");

    }

此时登录“zhangsan”,可以访问level1和level2的所有内容,但是level3下的内容仍然被禁止访问

三、注销

四、实现按角色显示对应的内容

比如说:

a、未登录的时候查看不到任何武功秘籍,显示【欢迎光临武林秘籍管理系统游客您好,如果想查看武林秘籍 请登录

b、登录的时候查看到角色对应的武功秘籍【VIP1显示普通武功秘籍、VIP2显示高级武功秘籍、VIP3显示绝世武功秘籍】

并且登录的成功后现实的是:【zhangsan 您好,您的角色有 [ROLE_VIP1, ROLE_VIP2]】

1、Thymeleaf提供的SpringSecurity标签支持 –需要引入thymeleaf-extras-springsecurity4 

2、页面上引入thymeleaf

根据是否登录显示相应内容

根据角色显示对应内容:

五、记住我&定制登录页

1、记住我

结果:

查看控制台可看到如下cookie信息:

2、定制登录页

/userlogin接口:

login.html页面:

-------------------------------------------------------------------------------------------------------------------------------

完整代码:

1、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot_security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_security</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
        <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、Controller

@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;
	}


}

3、config

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //定义授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        //定制请求的授权规则
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");
        //开启自动配置的登录功能,如果没有权限,就会来到登录页面
        http.formLogin().usernameParameter("user").passwordParameter("pwd").loginPage("/userlogin");//默认用户名是username,密码是password
        //1、/login来到登录页
        //2、重定向到/login?error表示登录失败
        //3、更多详细规定
        //4、默认post形式的/login代表处理登录

        //开启自动配置的注销功能
        http.logout().logoutSuccessUrl("/");//注销成功之后来到首页
        //1、访问/logoout表示用户注销,清空session
        //2\注销成功会返回 /login?logout 页面

        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember");
        //登录成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以
        //注销时也会自动清除
    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        //这里本来应该查询数据库的,但是emmm
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("VIP1","VIP2")
                .and().withUser("lisi").password("123456").roles("VIP2","VIP3")
                .and().withUser("wangwu").password("123456").roles("VIP3","VIP1");

    }
}

4、页面

(1)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>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div sec:authorize="!isAuthenticated()">
<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</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>

(2)login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</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="checkbox" name="remember"/>记住我<br/>
			<input type="submit" value="登陆"/>
		</form>
	</div>
</body>
</html>

文件存放位置:

发布了96 篇原创文章 · 获赞 16 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_38151401/article/details/103469808