本文将具体介绍在Spring Boot中如何使用Spring Security进行安全控制。
准备工作:
创建一个简单的spring-boot web工程,为后面添加安全控制做准备。若对如何使用Spring Boot构建Web应用有疑问参考:快速构建spring-boot web项目一文。
web层实现请求映射:
package org.xixilover.springbootdemo1;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* @author xixilover
* @since 2018/4/23 0023
*/
@Controller
@RequestMapping
public class ThymeleafController {
@GetMapping("/index")
public ModelAndView index() {
ModelAndView view = new ModelAndView();
// 设置跳转的视图 默认映射到 src/main/resources/templates/{viewName}.html
view.setViewName("index");
// 设置属性
view.addObject("title", "我的第一个WEB页面");
view.addObject("desc", "欢迎进入spring-boot-web 系统");
Author author = new Author();
author.setAge(24);
author.setEmail("梦想飞翔的猪@qq.com");
author.setName("梦想飞翔的猪");
view.addObject("author", author);
return view;
}
@GetMapping("/index1")
public String index1(HttpServletRequest request) {
// TODO 与上面的写法不同,但是结果一致。
// 设置属性
request.setAttribute("title", "我的第一个WEB页面");
request.setAttribute("desc", "欢迎进入spring-boot-web 系统");
Author author = new Author();
author.setAge(24);
author.setEmail("梦想游泳的猫@qq.com");
author.setName("梦想游泳的猫");
request.setAttribute("author", author);
// 返回的 index 默认映射到 src/main/resources/templates/xxxx.html
return "index";
}
class Author {
private int age;
private String name;
private String email;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<!-- 可以看到 thymeleaf 是通过在标签里添加额外属性来绑定动态数据的 -->
<title th:text="${title}">Title</title>
<!-- 在/resources/static/js目录下创建一个hello.js 用如下语法依赖即可-->
<script type="text/javascript" th:src="@{/js/hello.js}"></script>
</head>
<body>
<h1 th:text="${desc}">Hello World</h1>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="注销"/>
</form>
<h2>=====作者信息=====</h2>
<p th:text="${author?.name}"></p>
<p th:text="${author?.age}"></p>
<p th:text="${author?.email}"></p>
<h1>欢迎使用Spring Security!</h1>
<p>点击 <a th:href="@{/index1}">这里</a> 跳转到index1</p>
</body>
</html>
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.xixilover</groupId>
<artifactId>spring-boot-demo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-demo1</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
.withUser("1").password("1").roles("USER");
}
}
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence arg0) {
return arg0.toString();
}
@Override
public boolean matches(CharSequence arg0, String arg1) {
return arg1.equals(arg0.toString());
}
}
@RequestMapping("/login")
public String login() {
return "login";
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
用户名或密码错
</div>
<div th:if="${param.logout}">
您已注销成功
</div>
<form th:action="@{/login}" method="post">
<div><label> 用户名 : <input type="text" name="username"/> </label></div>
<div><label> 密 码 : <input type="password" name="password"/> </label></div>
<div><input type="submit" value="登录"/></div>
</form>
</body>
</html>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="注销"/>
</form>
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |