文章目录
简介:
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。 它是保护基于spring的应用程序的事实上的标准。 Spring Security是一个专注于为Java应用程序提供身份验证和授权的框架。 像所有Spring项目一样,Spring Security的真正强大之处在于它可以很容易地扩展以满足定制需求。
新建spring security项目
选择springWeb即可
导入thymeleaf与security依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
访问二级与三级目录
代码如下
@Controller
public class RouterController {
@RequestMapping({"/index","/"})
public String toIndex(){
return "index";
}
@RequestMapping({"/login"})
public String toLogin(){
return "views/login";
}
@RequestMapping("/level1/{id}")
public String toLevel(@PathVariable("id") int id){
return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String toLevel2(@PathVariable("id") int id){
return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String toLevel3(@PathVariable("id") int id){
return "views/level3/"+id;
}
}
目录如下
设置访问拦截器
可以登录首页,但是必须要会员身份才能登录功能页,当非会员登录登录页时会跳到首页,首页由方法提供。
代码如下:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception{
//首页所有人均可访问,功能页只有有对应权限的人才能访问
http.authorizeHttpRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level1/**").hasRole("vip2")
.antMatchers("/level1/**").hasRole("vip3");
//没有权限会默认跳到登录页
http.formLogin();//转法请求到login
}
}
因为设置了权限,所以当你点击功能页时:
会到登录页面
此时我们可以进一步设置登录的账号和密码,输入即可访问,在securityConfig中
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//从内存中读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("botany").password(new BCryptPasswordEncoder().encode("123456"))
.roles("vip2","vip3").and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
在springboot2.6中可以不需要进行加密,在springboot2.6.3中需要进行加密,否则会报错:
注销登录功能
在前端添加logout
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
</a>
在后端的方法中加上http.logout
注销后跳到首页
http.logout().logoutSuccessUrl("/");
设置不给其他vip看目录
导入依赖,查找thymeleaf与security相关的依赖
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
当为登录时,显示登录,登录后显示注销,用户名
<!--未登录,此时显示登录选项-->
<div sec:authorize="!isAuthenticated()">
<a th:href="@{/toLogin}"> 登录 </a>
</div>
<!--登录则显示注销选项-->
<div sec:authorize="isAuthenticated()">
<a th:href="@{/logout}">注销</a>
<a>
用户名:<span sec:authentication="name"></span>
角色:<span sec:authentication="principal.getAuthorities()">
</span>
</a>
</div>
运行:
登录后显示用户名
1:需要springboot的版本不要太新,我用的是2. 0.9,security的依赖为版本4
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.9.RELEASE</version>
</parent>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
2:html如下
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-spring-security4">
<div sec:authorize="isAuthenticated()">
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
</a>
<a class="item">
用户名:<span sec:authentication="name"></span>
角色:<span sec:authentication="principal.authorities">
</span>
</a>
</div>
</html>
3:有的版本需要关闭跨站请求攻击
http.csrf().disable();//登出失败可能存在的原因
同时security的config为:
http.authorizeRequests().antMatchers("/").permitAll()
@EnableWebSecurity
public class SecurityConfig 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");
//没有权限会默认跳到登录页
http.formLogin();//转法请求到login
//开启注销功能,注销后跳到首页
http.logout().logoutSuccessUrl("/");
//关闭跨站请求攻击
http.csrf().disable();//登出失败可能存在的原因
}
//制定认证的规则
//直接进入会报错,密码没有加密
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//从内存中读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("botany").password(new BCryptPasswordEncoder().encode("123456"))
.roles("vip2","vip3").and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
页面如下
访问:
登录页面是springboot自带的页面
登录后显示用户名,密码和注销
页面内容分权显示
有vip1的用户显示某些页面,没有vip的用户显示其他页面
sec:authorize=“hasRole(‘vip1’)”
<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>
位置如下
记住我功能
http.rememberMe();
位置:
更换系统登录页面
html中点击登录对应的是,表示当点击链接时会触发login请求,此请求会申请系统的页面
<a class="item" th:href="@{/login}">
<i class="address card icon"></i> 登录
</a>
在securityConfig中写入
//更换系统登录页面
http.formLogin().loginPage("/login");
表示当出发/login时不再是系统页面,而是去寻找controller中的/login请求
我们的controller如下
@RequestMapping({"/login"})
public String toLogin(){
return "views/login";
}
返回login.html
记住html中对应的name一定是username与password。
如果我们一定要叫user与pwd可以在config中写入:
http.formLogin().loginPage("/login").usernameParameter("user").
passwordParameter("pwd").loginProcessingUrl("/login");
在自己的登录页面中加入remember me
html
<input type="checkbox" name="remember">记住我
在securityConfig中
加入
http.rememberMe().rememberMeParameter(“remember”);
检查是否有remember,检查提交后是否出现:
汇总
login.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="@{/login}" 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>
<input type="checkbox" name="remember">记住我
<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>blog.kuangstudy.com</small>
</div>
<div class="ui segment" style="text-align: center">
<h3>Spring Security Study by 秦疆</h3>
</div>
</div>
</div>
<script th:src="@{/static/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/static/qinjiang/js/semantic.min.js}"></script>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-spring-security4">
<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="@{/static/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="@{/index}">首页</a>
<!--登录注销-->
<div class="right menu">
<!--未登录,此时显示登录选项-->
<div sec:authorize="!isAuthenticated()">
<a class="item" th:href="@{/login}">
<i class="address card icon"></i> 登录
</a>
</div>
<!--登录则显示注销选项-->
<div sec:authorize="isAuthenticated()">
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
</a>
<a class="item">
用户名:<span sec:authentication="name"></span>
角色:<span sec:authentication="principal.authorities">
</span>
</a>
</div>
<!--已登录
<a th:href="@{/usr/toUserCenter}">
<i class="address card icon"></i> admin
</a>
-->
</div>
</div>
</div>
<div class="ui segment" style="text-align: center">
<h3>Spring Security Study by sheepBotany</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="@{/static/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/static/qinjiang/js/semantic.min.js}"></script>
</body>
</html>
securityConfig
package com.example.springsecurity.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 SecurityConfig 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");
//没有权限会默认跳到登录页
http.formLogin();//转法请求到login
//开启注销功能,注销后跳到首页
http.logout().logoutSuccessUrl("/");
//关闭跨站请求攻击
http.csrf().disable();//登出失败可能存在的原因
//开启记住我功能
http.rememberMe().rememberMeParameter("remember");
//更换系统登录页面
http.formLogin().loginPage("/login");
// http.formLogin().loginPage("/login").usernameParameter("user").
// passwordParameter("pwd").loginProcessingUrl("/login");
}
//制定认证的规则
//直接进入会报错,密码没有加密
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//从内存中读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("botany").password(new BCryptPasswordEncoder().encode("123456"))
.roles("vip2","vip3").and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
RouterController
package com.example.springsecurity.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RouterController {
@RequestMapping({"/index","/"})
public String toIndex(){
return "index";
}
@RequestMapping({"/login"})
public String toLogin(){
return "views/login";
}
@RequestMapping("/level1/{id}")
public String toLevel(@PathVariable("id") int id){
return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String toLevel2(@PathVariable("id") int id){
return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String toLevel3(@PathVariable("id") int id){
return "views/level3/"+id;
}
}
d.annotation.RequestMapping;
@Controller
public class RouterController {
@RequestMapping({"/index","/"})
public String toIndex(){
return "index";
}
@RequestMapping({"/login"})
public String toLogin(){
return "views/login";
}
@RequestMapping("/level1/{id}")
public String toLevel(@PathVariable("id") int id){
return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String toLevel2(@PathVariable("id") int id){
return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String toLevel3(@PathVariable("id") int id){
return "views/level3/"+id;
}
}