一、Spring Security简介
Spring Security 是 Spring 家族中的一个安全管理框架,主要用于 Spring 项目组中提供安全认证服务,该框架主要的核心功能有认证、授权和攻击防护。
二、Spring Security入门
默认登录
pom配置
<dependencies>
<!--thymeleaf-->
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
</dependencies>
一般只要配置了SpringSecurity之后,即pom导入配置后,只要一访问控制器的接口,都会被拦截,自动跳转到SpringSecurity自定义的登录界面
Security自定义的账号是user,密码则是由控制台生成
输入账号和密码即可登录成功,并跳转到一开始输入要访问的页面
自定义表单登录
如果配置了SpringSecurity,Security会有自己的登录页面,并且会拦截任何页面
用自定义的表单登录,只需要自己做一下配置即可
创建配置类
package com.hello.config;
import org.springframework.boot.SpringBootConfiguration;
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;
@SpringBootConfiguration
@EnableWebSecurity
public class HelloConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/index.html").permitAll()
.anyRequest().authenticated();
http.formLogin().loginPage("/index.html");
http.formLogin().loginProcessingUrl("/user/login")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/success.html",true);
http.csrf().disable();
}
}
运行并访问主页index,会被拦截并且跳到自定义表单
输入账户密码跳转到登录成功的页面