首先简单说一下什么是Spring Security
简单地说,这是一个安全管理框架,主要包括用户认证和用户授权两个部分。
顾名思义,用户认证就是判断当前用户是否被允许访问当前系统,一般通过校验用户名和密码来实现。
用户授权就更容易理解了,一个系统中每个用户的权限都是不同的,比如有的用户可以增删改查,有的用户只允许查。
下面开始项目的构建
一.创建一个SpringBoot项目,并导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
二.创建一个hello.html页面
hello.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>Hello World!!!!!!</h1>
</body>
</html>
三.创建对应的Controller来访问hello.html
MyController.java:
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author: 冒菜咖啡~
* @create: 2020-07-07 16:15
**/
public class MyController {
@RequestMapping("/hello")
public String hello() {
return "hello";
}
}
运行项目并访问 localhost:8080/hello,正常来说会跳转到hello.html页面并显示Hello World,但是因为我们引入了Spring Security依赖,因此会直接跳转到一个默认的登录页面,如图
可以发现URL也发送了变化,我们输入的是 localhost:8080/hello 却变成 localhost:8080/login了。
除了这个页面外,系统还提供了一套默认用户名和密码,用户名为user,密码可以在后端的console窗口找到
输入用户名和密码之后即可跳转到我们需要的页面,显然这个登录验证功能不是我们想要的,因此我们需要对其进行一些修改。
四.创建登录页面 login.html和登陆成功页面 login_success.html,以及登陆失败页面login_fail.html
login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/login" method="post">
<h2>用户登录</h2>
<input type="text" name="username" placeholder="请输入用户名"/>
<input type="password" name="password" placeholder="请输入密码"/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
login_success.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>loginSuccess</title>
</head>
<body>
<h1>登陆成功</h1>
</body>
</html>
login_fail.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login_fail</title>
</head>
<body>
<h1>登陆失败</h1>
</body>
</html>
在Controller中定义对应的login页面访问方法
这里我们没有对表单提交进行处理,因为在后面会有配置
/**
* @Description:访问登陆页面
*/
@RequestMapping("/tologin")
public String toLogin() {
return "login";
}
/**
* @Description:访问登陆成功页面
*/
@RequestMapping("/loginsuccess")
public String loginSuccess() {
return "login_success";
}
/**
* @Description:访问登陆失败页面
*/
@RequestMapping("/loginfail")
public String loginFail() {
return "login_fail";
}
五.自定义一个类 WebSecurityConfig 继承 WebSecurityConfigurerAdapter
放在哪都可以,我建了个security包,放在包里面。
WebSecurityConfig.java:
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;
/**
* @author: 冒菜咖啡~
* @create: 2020-07-07 10:42
**/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin() //开启对登陆表单的配置
.loginPage("/tologin") //为登陆时的请求的跳转接口
.loginProcessingUrl("/login") //post登录接口,验证部分由系统完成
.defaultSuccessUrl("/loginsuccess",true)//登录成功时的跳转接口
.failureUrl("/loginfail") //登陆失败时的跳转接口
.permitAll() //permitAll()表示对以上几个接口的访问不需要验证
.and()
.authorizeRequests()
.anyRequest().authenticated() //除了上方提到的接口,其余接口的访问都要登录验证
.and()
.csrf().disable();
}
}
六.访问测试
可以看到默认被定位到我们设置的登录页面,无法访问其他页面( localhost:8080/hello)
用户名和密码与之前一样,使用系统默认生成的,如果填错了会被定位到我们设置的登陆失败页面
输入正确则显示登录成功,并跳转到指定页面
至此我们就算登录成功了,可访问之前访问不了的 localhost:8080/hello 了
七.自定义用户名和密码
只使用系统给的账号密码肯定是不行的,下面我们来自定义用户名和密码
这里介绍的是硬编码的方式,也就是固定写死的用户名和密码。
第一种方法,补在WebSecurityConfig.java后方:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth
.inMemoryAuthentication()
.withUser("test").password("{noop}123").roles("USER");
}
这样我们就可以使用用户名:test和密码:123进行登录了,roles是该用户的角色,后面会说。
{noop} 是Spring Security版本更新的问题:
在Spring Security 5.0之前,默认值PasswordEncoder是NoOpPasswordEncoder需要纯文本密码。在Spring Security 5中,默认值为DelegatingPasswordEncoder,这需要密码存储格式。
因此需要在密码前面加上{noop},否则会报错。
如果想多加几条用户名和密码方式如下:
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth
.inMemoryAuthentication()
.withUser("test").password("{noop}123").roles("USER")
.and()
.withUser("test2").password("{noop}123456").roles("ADMIN");
}
很简单,就是加个.and(),后面可随意加
第二种方法,区别不大,同样补在WebSecurityConfig.java后方:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("test").password("{noop}123").roles("USER");
}
接下来测试一下:
嗯,没毛病
八.角色身份
每个登录系统的账号都有属于自己的身份,比如USER,ADMIN,这些身份决定了这些账号的不同权限,比如test2账号能访问某页面,而test账号则无法访问,则应该就是用户授权吧?
首先新建一个temp.html文件
temp.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>temp</title>
</head>
<body>
<h1>你访问到我了!!!!</h1>
</body>
</html>
在Controller里添加访问temp页面的方法
@RequestMapping("/temp")
public String temp() {
return "temp";
}
之后修改WebSecurityConfig.java,为这个temp文件设置权限
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin() //开启对登陆表单的配置
.loginPage("/tologin") //为登陆时的请求的跳转接口
.loginProcessingUrl("/login") //post登录接口,验证部分由系统完成
.defaultSuccessUrl("/loginsuccess",true)//登录成功时的跳转接口
.failureUrl("/loginfail") //登陆失败时的跳转接口
.permitAll() //permitAll()表示对以上几个接口的访问不需要验证
.and()
.authorizeRequests()
.antMatchers("/temp").hasRole("ADMIN") //访问/temp接口时,需要有ADMIN身份
.anyRequest().authenticated() //除了上方提到的接口,其余接口的访问都要登录验证
.and()
.csrf().disable();
}
接下来测试一下:
首先以test账号登录,这个账号的角色身份是USER,可以发现其他页面都能正常访问,唯独temp页面无法访问。
接下来以test2账号登录,这个账号的角色身份是ADMIN,访问成功
参考博客:
https://blog.csdn.net/qq_29580525/article/details/79317969