Spring Boot确保Web应用安全(登陆认证)
Spring Boot官方提供了一个登陆认证的清晰易懂的 例子 ,
我们在次以此例展开演示Spring Boot是如何实现登陆认证的。
首先我们去 https://start.spring.io/ 下载一个样例工程 spring-test。
我们这个例子中包含三个页面,放在src/main/resources/templates/目录下:
- 登陆页面:login.html
- 主页:home.html
- 欢迎页面:hello.html
包含三个类:
- 主类:SpringTestApplication.java
- MVC映射关系类:MvcConfig.java
- 安全控制类:WebSecurityConfig.java
相关的maven依赖:
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- tag::security[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- end::security[] -->
<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>
</dependencies>
MvcConfig.java
package com.zifeiy.springtest.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
这个类主要用于配置url和view的对应关系。
WebSecurityConfig.java
package com.zifeiy.springtest.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@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();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
其中:
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
表示的意思是:
允许所有用户可以访问"/"和"/home";
通过form上传表单的形式登陆,form对应的url为"/login";
允许所有用户登出(logout)。
但是除此之外的所有的url都不能直接访问,除非登陆了,比如这里的"/hello"链接,就不能直接登陆。
这里的 UserDetails 用于设置登陆的用户名为user,密码为password的时候才能正确登陆。
login.html
<!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}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
home.html
<!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>
<h1>Welcome!</h1>
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
</body>
</html>
hello.html
<!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>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>
Spring Boot确保Web应用安全(登陆认证)的更多相关文章
- 使用Spring Boot开发Web项目(二)之添加HTTPS支持
上篇博客使用Spring Boot开发Web项目我们简单介绍了使用如何使用Spring Boot创建一个使用了Thymeleaf模板引擎的Web项目,当然这还远远不够.今天我们再来看看如何给我们的We ...
- 【spring boot】5.spring boot 创建web项目并使用jsp作前台页面
贼烦的是,使用spring boot 创建web项目,然后我再idea下创建的,but 仅仅启动spring boot的启动类,就算整个项目都是好着的,就算是能够进入controller中,也不能成功 ...
- 通过docker-composer启动容器nginx,并完成spring.boot的web站点端口转发
前面已经讲过2篇基于docker的mysql.redis容器编排并启动.这次将练习下nginx的docker方式的部署,以及通过nginx去代理宿主主机上的Web服务应该怎么配 PS:(这里由于ngi ...
- Spring Boot 2.X(四):Spring Boot 自定义 Web MVC 配置
0.准备 Spring Boot 不仅提供了相当简单使用的自动配置功能,而且开放了非常自由灵活的配置类.Spring MVC 为我们提供了 WebMvcConfigurationSupport 类和一 ...
- Spring Boot开发Web应用之Thymeleaf篇
前言 Web开发是我们平时开发中至关重要的,这里就来介绍一下Spring Boot对Web开发的支持. 正文 Spring Boot提供了spring-boot-starter-web为Web开发予以 ...
- Spring Boot 嵌入式Web容器
目录 前言 1.起源 2.容器启动流程解析 2.1.获取应用类型 2.2.容器启动流程 3.加载 Web 容器工厂 4.总结 前言 最近在学习Spring Boot相关的课程,过程中以 ...
- 使用Spring Boot开发Web项目
前面两篇博客中我们简单介绍了Spring Boot项目的创建.并且也带小伙伴们来DIY了一个Spring Boot自动配置功能,那么这些东西说到底最终还是要回归到Web上才能体现出它的更大的价值,so ...
- spring boot 搭建web项目常见五种返回形式
在web项目中一般常见的五种返回形式: 返回页面,使用模板引擎,spring boot推荐使用thymeleaf,类似的还有freemarker等. 返回字符串(json),一般用于完全的前后端分离开 ...
- Spring Boot的web开发
web开发的自动配置类:org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration 自动配置的ViewResolver 视图的 ...
随机推荐
- ip_srcroute函数
当响应某个分组时,I C M P和标准的运输层协议必须把分组带的任意源路由逆转.逆转源路由是通过i p _ s r c r o u t e保存的路由构造的. 7 7 7 - 7 8 3 i p _ s ...
- Java8-Lambda-No.04
public class Lambda4 { static int outerStaticNum; int outerNum; void testScopes() { int num = 1; Lam ...
- 工作 巧遇 sql 查询 一组数据中 最新的一条
SELECT * FROM rsl a, (SELECT CODE, max(time_key) time_key FROM rsl GROUP BY CODE ) b WHERE a. CODE = ...
- linux重启之后No CUDA-supporting devices found!
实验室做并行计算的服务重启后,采用cuda接口的应用程序vasp_gpu,运行时提示: CUDA Error in cuda_main.cu, line 144: unknown error No C ...
- [Luogu P4145] 上帝造题的七分钟2 / 花神游历各国
题目链接 题目简要:我们需要一个能支持区间内每一个数开方以及区间求和的数据结构. 解题思路:说道区间修改区间查询,第一个想到的当然就是分块线段树.数据范围要用long long.本来我是看到区间这两个 ...
- min-width
min-width 语法: min-width:<length> | <percentage> 默认值:0 适用于:除非置换内联元素,table-row, table-row- ...
- JAVA类的无参方法
Java注释: //:单行注释 /**/:多行注释 /** */:JavaDoc注释 方法: ...
- SPOJ GSS1 - Can you answer these queries I(线段树维护GSS)
Can you answer these queries I SPOJ - GSS1 You are given a sequence A[1], A[2], -, A[N] . ( |A[i]| ≤ ...
- [Qt Quick] qmlscene 工具的使用
qmlscene是Qt 5提供的一个查看qml文件效果的工具.特点是不需要编译应用程序. qmlscene = qml + scene (场景) qmlscene.exe位于Qt的安装目录下 (类似/ ...
- Python学习日记(六)——内置函数和文件操作(lambda)
lambda表达式 学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即: # 普通条件语句 if 1 == 1: name = 'prime' else: name = 'c ...