前言
spring security 可以对网站进行用户访问控制(验证|authentication)和用户授权(authorization)。两者也在springboot 手册中明说到:authentication (who are you?) and authorization (what are you allowed to do?)。用户授权结合OAuth进行api或者第三方接入控制授权(授权),本文使用security进行用户登录,验证用户合法性(验证)。
1、创建不受访问限制的项目
1.1、初始化项目
在Spring Initializr 或者编辑器中生成空白项目,maven依赖添加web和thymeleaf就可以了,如下图:
1.2、创建两个展示界面
src/main/resources/templates/home.html
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
homeHome Page
click here to see a greeting.
希望通过上面这个界面跳转到 /hello,hello界面内容如下:
src/main/resources/templates/hello.html
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
Hello World!Hello world!
页面创建完成后,配置路由控制界面跳转,通过配置文件方式添加路由:
package com.noel.handbook.accesscontroll.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 {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// TODO Auto-generated method stub
registry.addViewController("/home").setViewName("/home");
registry.addViewController("/").setViewName("/home");
registry.addViewController("/login").setViewName("/login");
registry.addViewController("/hello").setViewName("/hello");
}
}
通过重写WebMvcConfigurer 的addViewControllers方法,添加四个路由,login界面在下面创建。
到现在,可以运行项目,浏览器输入地址ip:端口/ 或者 ip:端口/home查看界面输出,界面之间和url地址之间可以随意跳转。
2、添加security
我们想控制用户需要登录后才显示hello界面,并输出登录者的用户名。
pom添加如下依赖:
pom.xml
org.springframework.boot
spring-boot-starter-security
然后我们限制重启项目,可以看见控制台会输出一个密码。访问任意界面会显示一个springboot的默认登录界面:
2.1、 设置访问控制
package com.noel.handbook.accesscontroll.config;
import org.springframework.context.annotation.Bean;
impor