1、新建一个springboot项目,选择web、thymeleaf、spring security
2、创建好当前文件和目录结构
3、首先是一些相关的界面
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.0modelVersion> <parent> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-parentartifactId> <version>2.2.4.RELEASEversion> <relativePath/> parent> <groupId>com.ginggroupId> <artifactId>springboot-securityartifactId> <version>0.0.1-SNAPSHOTversion> <name>springboot-securityname> <description>Demo project for Spring Bootdescription> <properties> <java.version>1.8java.version> properties> <dependencies> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-securityartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-thymeleafartifactId> dependency> <dependency> <groupId>org.thymeleaf.extrasgroupId> <artifactId>thymeleaf-extras-springsecurity5artifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> <exclusions> <exclusion> <groupId>org.junit.vintagegroupId> <artifactId>junit-vintage-engineartifactId> exclusion> exclusions> dependency> <dependency> <groupId>org.springframework.securitygroupId> <artifactId>spring-security-testartifactId> <scope>testscope> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-maven-pluginartifactId> plugin> plugins> build> project>
welcome.html
DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统h1>
<h2 align="center">游客您好,如果想查看武林秘籍 >请登录a>h2>
div>
<h2 align="center">
<span sec:authentication="name">span>,您好,您的角色有:
<span sec:authentication="principal.authorities">span>
<form th:action="@{/logout}" method="post">
<input type="submit" value="注销"/>
form>
<h2>
div>
<hr>
<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>
<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>
<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>
说明:重要的地方已经加粗放大了。
login.html
DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
head>
<body>
<h1 align="center">欢迎登陆武林秘籍管理系统h1>
<hr>
<div align="center">
<form th:action="@{/userlogin}" method="post">
用户名:<input name="username"/><br>
密码:<input name="password"><br/>
<input type="checkbox" name="remember">记住我<br/>
<input type="submit" value="登陆">
form>
div>
body>
html>
这里只展示其中一个1.html,它们大致相同:
DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<a th:href="@{/}">返回a>
<h1>罗汉拳h1>
<p>罗汉拳站当央,打起来不要慌p>
body>
html>
KungfuController.java
package com.ging.springbootsecurity.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@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;
}
}
MySecurityConfig.java
package com.ging.springbootsecurity.config;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
@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");
//开启自动配置的登录功能
//1、login请求来到登录页面
//2、重定向/login?Error表示登录失败
//3、设置转到我们自己的登录界面
//4、自定义的登录界面要发送post请求,action需要为/login,字段要匹配这里的
http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/userlogin");//.loginProcessingUrl("/login")
//开启自动配置的注销功能
//1、访问logout表示用户注销,清空session
//2、默认注销成功会返回login?logout页面
//3、设置注销成功来到首页
http.logout().logoutSuccessUrl("/");
//开启记住我功能
http.rememberMe().rememberMeParameter("remember");
}
//定义认证规则
@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");
}
}
接下来跟着实际的操作一步步探索。
启动服务器:
首先输入localhost:8080,会自动跳转到welcome.html,由于我们配置了authorizeRequests()和formLogin(),并且设置了/level?/**的权限,所以我们在浏览器输入localhost:8080/level/1等请求时,由于没有登录,即不是哪一个用户,所以会跳转到springboot自定义的login界面。
如果我们不定义自己的登录页面的话,系统确实会跳转到springboot自己的界面,但是我们若想要跳转到自己的界面呢?
http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/userlogin");//.loginProcessingUrl("/login")
这里需要设置用户名和密码的名称,以及自动跳转的页面,即发送/userlogin请求,而/userlogin请求则会返回我们真正的登录界面:login.html。在login.html中输入框里面的name要和这里的分别对应,同时我们还要发送post请求,对应的action要与发送的请求相同,即为@{/userlogin}。我们设置记住我时,同样要置http.rememberMe().rememberMeParameter("remember");对应的名称。然后我们输入:
@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");
}
这里定义好的角色,一般这里是从数据库中获取,这里就只进行模拟。比如输入:zhangsan,密码:123456,我们就会进入到:
在welcome.html界面可以通过sec属性来获取相关的值。通过isAuthenticated来判断当前的用户是否具有权限,有的化我们的欢迎界面就变化了,显名称以及角色。然后在不同的代码块中我们有
标识。zhangsan拥有“VIP1”和“VIP2”角色,因此可以看到普通武功秘籍和高级武功秘籍。我们点击注销,就可以退出登录。在配置文件中定义了注销后返回到主界面。由于此时没有了权限,则会显示欢迎您,游客。。。
接下来我们再试一下登录:lisi 123456,并勾选记住我。
点进去看一本:
它是VIP2和VIP3,因此可以看到高级武功秘籍和绝世武功秘籍。由于我们勾选了记住我,所以我们关闭这个界面,在访问localhost:8080,此时就不需要我们再进行登陆了。
总结:基本上实现了普通游客只有在登录了之后才能够访问到level?/**下的内容,强行访问会被拦截到登录界面。用户登陆之后根据不同角色显示不同内容。勾选记住我后会保存一个cookie,再次访问不需要再登录,点击注销之后删除cookie,退出登录。