Spring Security 简单实现用户登陆

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()
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值