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是一个功能强大且高度可定制的身份验证和访问 ...
随机推荐
- iscroll在谷歌浏览器中bug
https://segmentfault.com/q/1010000008489619 iscroll 在安卓app嵌套html页面时,导致列表页滑动不起来,并且在chorme浏览器中使用手机模式,也 ...
- HTML5 Canvas绘图如何使用
--------------复制而来--原地址http://jingyan.baidu.com/article/ed15cb1b2e642a1be369813e.html HTML5 Canvas绘图 ...
- SpringBoot之整合MongoDB
MongoDB官网安装:https://www.mongodb.com/download-center/community MongoDB客户端工具(Mongo Management Studio)安 ...
- 【python爬虫】scrapy入门8:发送POST请求
scrapy基础知识之发送POST请求与使用 FormRequest.from_response() 方法模拟登陆 https://blog.csdn.net/qq_33472765/article/ ...
- PHP SQL预处理
php预处理查询 $query='insert into p1(info) values(?)'; $query2='select info from p1 where id=?'; $country ...
- Linux下VCS2014和Verdi2015的联合使用
VCS和Verdi是IC设计中常用的两款开发工具.VCS是Synopsys公司的产品,和大家所熟知的ModeSim一样的都是EDA仿真工具.Verdi是Nocas公司(已经被Synopsys公司收购) ...
- python中几个双下划线用法的含义
_ _ init() _ _(self[,...]) 我们有时在类定义写__init()__方法,但是有时又没有.__init()__方法相当于其他面向对象的编程语言中的构造方法,也就是类在实例化成对 ...
- Unity实现写入json文件
using System.Collections; using System.Collections.Generic; using UnityEngine; using LitJson; using ...
- 【JAVA习题三】求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加
import java.util.Scanner; public class a加aa加aaa { public static void main(String[] args) { // TODO A ...
- [Python基础]005.语法(4)
语法(4) 类 创建 self 方法 变量 综合例子 继承 类 创建 与其他大部分语言一样,Python也用 class 来创建类. class Person: # Person类 pass # 空语 ...