一、Spring Security简介
应用程序的安全性通常体现在两个方面:认证和授权
认证是确认某主题在某系统中是否合法、可用的过程。这里的主题既可以是登录系统的用户,也可以是接入的设备或者其他系统
授权是指当主体通过认证后,是否允许其执行某项操作的过程,认证和授权是应用安全的基本关注点
二、简单Spring Security应用搭建
建立一个Springboot项目,建立以下配置文件类
package com.example.securingweb;
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;
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and().formLogin().loginPage("/myLogin.html")
//登录页面,且不设访问限制
.permitAll()
.and()
.csrf().disable();
}
}
建立static文件夹,建立myLogin.html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆</title>
</head>
<body>
<div class="login">
<h1>LOGIN FORM</h1>
<form action="myLogin.html" method="post">
<input type="text" name="username" placeholder="username"><br>
<input type="password" name="password" placeholder="password"><br>
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
简单的搭一下,不设置css格式了
启动项目后登陆localhost:8080,显示页面如下:
此时被拦截进入登录页面,输入user和Security给出的密码(控制台会打印),点击login登录
即可成功登录
以上是对Spring Security默认安全机制的简单应用,主要是在WebSecurityConfig 的configure配置。但是这里只有一个用户,一种角色,很明显是没办法满足需求的,下一章会再深入介绍