首页 > 技术文章 > 5.1_springboot2.x与安全(spring security)

jatpeo 原文

1、简介

常见的两个安全框架shiro|spring security,这里只介绍spring security;

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

几个类:
WebSecurityConfigurerAdapter:自定义Security策略
AuthenticationManagerBuilder:自定义认证策略
@EnableWebSecurity:开启WebSecurity模式

应用程序的两个主要区域是“认证”和“授权”(或者访问控制)。这两个主要区域是Spring Security 的两个目标。

“认证”(Authentication),是建立一个他声明的主体的过程(一个“主体”一般是指用户,设备或一些可以在你的应用程序中执行动作的其他系统)

“授权”(Authorization)指确定一个主体是否允许在你的应用程序执行一个动作的过程。为了抵达需要授权的店,主体的身份已经有认证过程建立。

2、测试安全登录&认证&授权

1、导入依赖

测试环境说明:

springboot:2.2.0、thyemelaf:3.0.11.RELEASE、

<!--引入spring security模块-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
<!--thyemelaf模块-->
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

2、配置spring security配置类

该类要用@EnableWebSecurity标注并且继承WebSecurityConfigurerAdapter

public class MySecurityConfig extends WebSecurityConfigurerAdapter{    
}

3、控制请求的访问权限

重写protected void configure(HttpSecurity http)方法

定制请求的授权规则:

//开启自动配置的登录功能,如果没有登录,没有权限就会来到登录页面
        /*formLogin()
         * 1、/login 来到登录页面
         * 2、重定向到/login?error表示登录失败
         * 3、更多详细规定
         * 4、默认post形式的/login代表处理登录
         * 5、一旦定制loginpage:那么loginPage的post请求就是登录
         * */
http.formLogin()

详细代码:

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {


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

   

4、定制授权规则

重写:protected void configure(AuthenticationManagerBuilder auth)

这里主要从auth.inMemoryAuthentication 从内存中获取,如果从硬盘查看密码的话,注意:Spring security 5.0中新增了多种加密方式,也改变了密码的格式。请看此博客:https://blog.csdn.net/canon_in_d_major/article/details/79675033

  @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //inMemoryAuthentication 从内存中获取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("1").password(new BCryptPasswordEncoder().encode("123")).roles("VIP1","VIP2")
                .and()
                .withUser("2").password(new BCryptPasswordEncoder().encode("123")).roles("VIP2","VIP3")
                .and()
                .withUser("3").password(new BCryptPasswordEncoder().encode("123")).roles("VIP2","VIP3");

    }

3、测试权限控制&注销

1、注销功能

开启自动配置的注销功能 1、访问/loginout表示用户注销,清空session 2、注销成功之后,会返回login?logout

http.logout().logoutSuccessUrl("/");//注销成功之后来到首页

html这样写:

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

当页面点击注销按钮,会跳到登录页面,logoutSuccessUrl("/")可到指定位置

2、权限控制

这里可以指定特定用户访问相对应的信息,不同角色显示不同内容

引入thymeleaf-extras-springsecurity5依赖

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

这里:记录springBoot2.2.0版本里添加thymeleaf-extras-springsecurity4后,也无法正常读取到sec标签

html命名空间:

 xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

即可解决

<!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>

4、测试记住我&定制登录页

1、记住我

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

       /*
        * 登录成功以后,将cookie发给浏览器保存,以后访问页面会带上这个cookie,只要通过检查就可以实现免登陆
        * 点击注销会删除cookie
        * */
        http.rememberMe().rememberMeParameter("remember");

2、定制登录页

spring security默认访问/login,

 http.formLogin()
                .usernameParameter("user")
                .passwordParameter("pwd")
                .loginPage("/userlogin");

这时候点登录会到自己定制的登录页,这里要提交登录的用户名和密码 ,loginPage()—>默认post形式的/login代表处理登录,

一旦定制loginpage:那么loginPage的post请求就是登录

在这里插入图片描述

登录页:

<div align="center">
		<form th:action="@{/userlogin}" method="post">
			用户名:<input name="user"/><br>
			密码:<input name="pwd"><br/>
			remember me:<input type="checkbox" name="remember">
			 <input type="submit" value="登陆">
		</form>
	</div>

推荐阅读