Spring Security 实现用户登陆
本文仅介绍Spring Security的基本使用。
Spring Security简介
Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。
- 认证(Authentication):“认证”是建立主体(principal)的过程。“主体”通常是指可以在您的应用程序中执行操作的用户、设备或其他系统。
- 授权(Authorization):或称为“访问控制(Access-control)”,“授权”是指决定是否允许主体在应用程序中执行操作。
身份验证技术主要有:
身份验证 | . . . |
---|---|
HTTP BASIC |
单点登陆 |
HTTP Digest |
Remember-Me |
HTTP X.509 |
匿名身份验证 |
LDAP |
Run-as |
基于表单的认证 | JAAS |
OpenID |
JavaEE 容器认证 |
Spring Security 配置
build.gradle
关键代码:
dependencies {
//SpringBoot必要组件和测试组件
implementation('org.springframework.boot:spring-boot-starter-web')
testImplementation('org.springframework.boot:spring-boot-starter-test')
//thymeleaf 模板引擎
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
//Spring Data JPA 持久层支持
compile('org.springframework.boot:spring-boot-starter-data-jpa')
//Mysql 连接驱动
compile('mysql:mysql-connector-java:8.0.11')
//H2 内存数据库
runtime('com.h2database:h2:1.4.193')
//Spring Security 权限管理
compile('org.springframework.boot:spring-boot-starter-security')
//Thymeleaf Spring Security 对Thymeleaf的支持
compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4:3.0.2.RELEASE')
}
完整代码:HERE
SecurityConfig.java
SecurityConfig.java为配置类,继承自org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
类。
用于自定义一些配置。
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Autowired;
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;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 自定义权限配置
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll()// 都可以访问
.antMatchers("/users/**").hasRole("ADMIN")// 需要相应角色权限才能访问
.and().formLogin()// 基于Form表单验证
.loginPage("/login").failureUrl("/login-error");// 自定义登陆界面
http.csrf().disable()