SpringBoot与(Security)安全
1.简介
应用程序的两个主要区域
认证(Authentication):
是建立一个它声明的主体的过程(一个“主体” 一般是指用户,设备或一些可以在你的应用程序中执行动作的其他系统)
证明用户的身份,当用户登录之后,系统来查验用户名和密码,以此来证明你有对应身份,这个过程就是认证。
授权 (Authorization)
指确定一个主体是否允许在你的应用程序执行一个动作的过程。为了抵达需要授权的店,主体的身份已经有认证过程建立
指的是你能够干什么 ,有什么样的访问权限。
主要是几个类:
WebSecurityConfigurerAdapter:自定义Security策略
AuthenticationManagerBuilder:自定义认证策略
@EnableWebSecurity:开启WebSecurity模式
2.使用
引入SpringSecurity;
编写SpringSecurity的配置类;
- 继承
WebSecurityConfigurerAdapter - 在配置类上写上注解 @EnableWebSecurity
控制请求的访问权限:
需要重写方法
定制请求的授权规则
开启自动配置登录功能 :如果没有登录,没有权限就会到登录页面
- /login请求来到登录页
- 重定向到/login?error 表示登录失败
- 更多功能
开启自动配置的注销功能
http.logout().logoutSuccessUrl("/"); //注销成功之后 ,来到首页
- 访问 /logout 表示用户注销,清空session
- 注销成功会返回 /login?logout
- 防止网站攻击
@Override
protected void configure(HttpSecurity http) throws Exception {
//定制请求的授权规则
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
//开启自动配置登录功能
http.formLogin();
//1、/login请求来到登录页
//2、重定向到/login?error 表示登录失败
//3、更多功能
//4、默认post形式的/login代表处理登录
//5、一旦定制loginPage;name loginPage的post请求就是登录
// 开启自动配置的注销功能
//防止网站攻击
http.csrf().disable();
http.logout();
定义认证规则
需要重写 方法, 配置对应的账号密码 以及角色//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
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");
}
3.thymeleaf整合security
pom.xml文件中引入依赖
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
引入名称标签
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
</html>
实现 在用户登录的情况下显示注销,否则不显示
【注意:authorize:授权 isAuthenticated():在springboot2.0.7版本以上不生效,是否已经认证(用户是否登录)
需要导入 命名空间5版本才生效
】
<!--登录注销-->
<!-- 未登录-->
<div class="right menu">
<div sec:authorize="!isAuthenticated()">
<!--未登录-->
<a class="item" th:href="@{/toLogin}">
<i class="address card icon"></i> 登录
</a>
</div>
<!-- 已登录-->
<div sec:authorize="isAuthenticated()">
<h3>
用户名:<span sec:authentication="name"></span>
角色:<span sec:authentication="principal.authorities"></span>
</h3>
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
</a>
</div>
</div>
实现功能:根据不同的角色显示不同的字段
<div class="column" sec:authorize="hasRole('VIP3')">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 3</h5>
<hr>
<div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
<div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
<div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
</div>
</div>
</div>
</div>
定制登录页面
//开启自动配置登录功能
http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/toLogin");
实现记住我功能
// 开启记住我 功能
http.rememberMe().rememberMeParameter("remeber"); //需要对应登录界面的CheckBox 的name值
4.代码
配置类:
package com.king.security.config;
import org.springframework.security.authentication.AuthenticationManager;
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(AuthenticationManagerBuilder auth) throws Exception {
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");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//定制请求的授权规则
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
//开启自动配置登录功能
http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/toLogin");
//1、/login请求来到登录页
//2、重定向到/login?error 表示登录失败
//3、更多功能
// 开启自动配置的注销功能
//防止网站攻击
http.csrf().disable();
http.logout().logoutSuccessUrl("/");
// 开启记住我 功能
http.rememberMe().rememberMeParameter("remeber");
// 登录成功之后 将cookie发给浏览器保存,以后登录会带上这个cookie,只要通过验证就可以免登录访问页面
// 点击注销会删除cookie
}
}
controller:
package com.king.security.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SecurityController {
//首页
@RequestMapping({"/", "/index.html","/index"})
public String index(){
return "index";
}
//登录页
@RequestMapping("/toLogin")
public String loginPage(){
return "views/login";
}
// 页面映射
@RequestMapping("/level1/{path}")
public String level1(@PathVariable("path") String path){
return "views/level1/"+path;
}
@RequestMapping("/level2/{path}")
public String level2(@PathVariable("path") String path){
return "views/level2/"+path;
}
@RequestMapping("/level3/{path}")
public String level3(@PathVariable("path") String path){
return "views/level3/"+path;
}
}
首页:index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>首页</title>
<!--semantic-ui-->
<link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
<link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
</head>
<body>
<!--主容器-->
<div class="ui container">
<div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
<div class="ui secondary menu">
<a class="item" th:href="@{/}">首页</a>
<!--登录注销-->
<!-- 未登录-->
<div class="right menu">
<div sec:authorize="!isAuthenticated()">
<!--未登录-->
<a class="item" th:href="@{/toLogin}">
<i class="address card icon"></i> 登录
</a>
</div>
<!-- 已登录-->
<div sec:authorize="isAuthenticated()">
<h3>
用户名:<span sec:authentication="name"></span>
角色:<span sec:authentication="principal.authorities"></span>
</h3>
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
</a>
</div>
</div>
</div>
</div>
<div class="ui segment" style="text-align: center">
<h3>Spring Security </h3>
</div>
<div>
<br>
<div class="ui three column stackable grid">
<div class="column" sec:authorize="hasRole('VIP1')">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 1</h5>
<hr>
<div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
<div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
<div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
</div>
</div>
</div>
</div>
<div class="column" sec:authorize="hasRole('VIP2')">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 2</h5>
<hr>
<div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
<div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
<div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
</div>
</div>
</div>
</div>
<div class="column" sec:authorize="hasRole('VIP3')">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 3</h5>
<hr>
<div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
<div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
<div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>
</body>
</html>
登录页:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>登录</title>
<!--semantic-ui-->
<link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
</head>
<body>
<!--主容器-->
<div class="ui container">
<div class="ui segment">
<div style="text-align: center">
<h1 class="header">登录</h1>
</div>
<div class="ui placeholder segment">
<div class="ui column very relaxed stackable grid">
<div class="column">
<div class="ui form">
<form th:action="@{/toLogin}" method="post">
<div class="field">
<label>Username</label>
<div class="ui left icon input">
<input type="text" placeholder="Username" name="username">
<i class="user icon"></i>
</div>
</div>
<div class="field">
<label>Password</label>
<div class="ui left icon input">
<input type="password" name="password">
<i class="lock icon"></i>
</div>
</div>
<div class="field">
<div class="checkbox">
<label>
<input type="checkbox" name="remeber" id="">记住我 <br>
</label>
</div>
</div>
<input type="submit" class="ui blue submit button"/>
</form>
</div>
</div>
</div>
</div>
<div style="text-align: center">
<div class="ui label">
</i>注册
</div>
<br><br>
<small></small>
</div>
<div class="ui segment" style="text-align: center">
<h3></h3>
</div>
</div>
</div>
<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>
</body>
</html>
level1/1.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>首页</title>
<!--semantic-ui-->
<link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
<link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
</head>
<body>
<!--主容器-->
<div class="ui container">
<div th:replace="~{index::nav-menu}"></div>
<div class="ui segment" style="text-align: center">
<h3>Level-1-1</h3>
</div>
</div>
<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>
</body>
</html>
SpringBoot与(Security)安全的更多相关文章
- SpringBoot集成security
本文就SpringBoot集成Security的使用步骤做出解释说明.
- SpringBoot + Spring Security 学习笔记(五)实现短信验证码+登录功能
在 Spring Security 中基于表单的认证模式,默认就是密码帐号登录认证,那么对于短信验证码+登录的方式,Spring Security 没有现成的接口可以使用,所以需要自己的封装一个类似的 ...
- SpringBoot + Spring Security 学习笔记(三)实现图片验证码认证
整体实现逻辑 前端在登录页面时,自动从后台获取最新的验证码图片 服务器接收获取生成验证码请求,生成验证码和对应的图片,图片响应回前端,验证码保存一份到服务器的 session 中 前端用户登录时携带当 ...
- 基于Springboot集成security、oauth2实现认证鉴权、资源管理
1.Oauth2简介 OAuth(开放授权)是一个开放标准,允许用户授权第三方移动应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容,OAu ...
- springboot+spring security +oauth2.0 demo搭建(password模式)(认证授权端与资源服务端分离的形式)
项目security_simple(认证授权项目) 1.新建springboot项目 这儿选择springboot版本我选择的是2.0.6 点击finish后完成项目的创建 2.引入maven依赖 ...
- springboot使用security
springboot使用security 1.结构图 2.pom.xml <?xml version="1.0" encoding="UTF-8"?> ...
- SpringBoot+thymeleaf+security+vue搭建后台框架 基础篇(一)
刚刚接触SpringBoot,说说踩过的坑,主要的还是要记录下来,供以后反省反省! 今天主要讲讲 thymeleaf+security 的搭建,SpringBoot的项目搭建应该比较简单,这里就不多说 ...
- springboot对security的后端配置
一.Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring ...
- SpringBoot + Spring Security 基本使用及个性化登录配置详解
Spring Security 基本介绍 这里就不对Spring Security进行过多的介绍了,具体的可以参考官方文档 我就只说下SpringSecurity核心功能: 认证(你是谁) 授权(你能 ...
- SpringBoot系列——Security + Layui实现一套权限管理后台模板
前言 Spring Security官网:https://spring.io/projects/spring-security Spring Security是一个功能强大且高度可定制的身份验证和访问 ...
随机推荐
- python学习(12)使用正则表达式
1.正则表达式知识 符号 解释 示例 说明 . 匹配任意字符 b.t 可以匹配bat / but / b#t / b1t等 \w 匹配字母/数字/下划线 b\wt 可以匹配bat / b1t / b_ ...
- Istio-架构
读书笔记整理 工作机制:分为控制面和数据面 控制面:Pilot, Mixer(接收来自Envoy上报的数据), Citadel(证书和密钥管理) 数据面:Envoy 工作流程: 自动注入 应用程序启动 ...
- js 获取百度搜索关键词的代码
有可能有时候我们会用到在百度搜什么关键词进来我们的网站的,所有我们又想拿到用户搜索的关键词. 这是我研究了半天所得出的办法.话不多说直接贴代码 <script> function quer ...
- 转 vue动画总结
使用过渡类名(有进入及出去,适合显示隐藏,需要配合v-if) .v-enter,//进入前 .v-leave-to {//离开后 只需要入场动画 可以把v-leave-to删掉 opacity: 0; ...
- 0421for循环各类题目
for循环要点 1.确认外层控制内容 2.确认内层控制内容 3.将打印内容与行号产生关系式 4.有的语句可以用if语句,根据字符的个数来增减char,优化代码 //部分类型只能输出奇数行,可在下半部分 ...
- 如何理解Java中的自动拆箱和自动装箱?
小伟刚毕业时面的第一家公司就被面试官给问住了... 如何理解Java中的自动拆箱和自动装箱? 自动拆箱?自动装箱?什么鬼,听都没听过啊,这...这..知识盲区... 回到家后小伟赶紧查资料,我透,这不 ...
- [nginx报错问题]reload时报错:nginx: [error] invalid PID number "" in ...
错误 第一次探索nginx,执行以下命令时: nginx -s reload 报出错误: nginx: [error] invalid PID number "" in ... * ...
- Rocket - tilelink - RegionReplicator
https://mp.weixin.qq.com/s/XZVCdt50tM6lavchGm9GRg 简单介绍RegionReplicator的实现. 1. 基本介绍 根据mask ...
- ASP.NET中LINQ的基本用法
此Demo只是一个极其简单的LINQ查询Demo 一个类 using System; using System.Collections.Generic; using System.Linq; usin ...
- Java实现 LeetCode 239 滑动窗口最大值
239. 滑动窗口最大值 给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧.你只可以看到在滑动窗口内的 k 个数字.滑动窗口每次只向右移动一位. 返回滑动窗口中的最 ...