使用Spring Security进行身份验证还是比较简单。
什么叫身份验证?
身份验证如同我们进公园验门票,进火车站难车票和身份证一样,它是验证身份,不是权限。权限在一定程序上等同于权力,如火车票上的座位号,有座位号就有坐某个位置的权力。
这里有一个应用场景:
有3个页面,index页面是入口,在index上访问hello页面。hello页面需要身份验证后才能登录。
我们通过实例来学习Spring Security 身份验证,新建一个Spring boot工程,工程结构如下:
Spring Security需要添加安全相关的依赖,它的pm.xml如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
|
spring-boot-starter-security 加载Spring Security 相关的依赖
为简单说明,仅用了个3个HTML,及注册3个MVC控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
HTML中加入了springsecurity标签,thymeleaf中叫命名空间。
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
加入命名空间xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
点击链接访问hello页面
hello.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
hello页面显示登录用户名[[${#httpServletRequest.remoteUser}]]
还有一个表单,请求指向logout
,logout由Spring Security 框架实现,程序无需关注怎么实现,这也节省了工作量。
登录页面login.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
表单提示两个域,一个用户名,一个密码,请求login由Spring Security 框架处理,程序员也不需要关注,也节省了开发时间。
第10行和第11行接收两个参数,参数不同显示不同的提示。
Spring Security 核心部分是继承org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
它创建一个用户(用户名,密码,角色),并将用户放到内存中。
同时指定了哪些资源无需身份验证可以访问,哪些资源必须身份验证后方可访问。见代码注解。
运行演示:
本文转自王二的网站,已获原文作者许可,欢迎转载
https://www.wangshenghua.com/wiki/spring-security/2bf63f12d9898ebaa32fa29ea48e33b0/