金融网站建设报价方案,好网站建设公司哪里好,网站建设参数,设计师一般放作品的网站前言
Spring Security是Spring框架下的一个用于身份验证和授权的框架#xff0c;它可以帮忙管理web应用中的用户认证、授权以及安全性问题。本文将介绍如何使用Spring Security实现用户登录功能#xff0c;本文主要包括以下内容#xff1a;
环境准备Spring Security核心概…前言
Spring Security是Spring框架下的一个用于身份验证和授权的框架它可以帮忙管理web应用中的用户认证、授权以及安全性问题。本文将介绍如何使用Spring Security实现用户登录功能本文主要包括以下内容
环境准备Spring Security核心概念实现基本登录功能添加Spring Security的数据库认证
环境准备
在开始写Spring Security之前我们需要配置好以下环境
JDK 1.8或以上Maven 3.0或以上Spring Boot 2.1.4或以上IDE推荐使用IntelliJ IDEA
在完成以上步骤后我们可以开始编写代码。
Spring Security核心概念
在使用Spring Security时需要了解一些核心概念
Authentication: 安全认证对象包括用户名、密码以及权限等信息。Authorization: 安全授权对象授权某个用户拥有访问某个资源的权限。Filter: 安全过滤器过滤请求并传递继续处理请求的权限。Provider: 安全认证提供者获取认证信息并返回持久化信息等内容。
实现基本登录功能
添加依赖
首先需要添加Spring Security的依赖到项目中:
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-security/artifactIdversion${spring-boot.version}/version
/dependency开启Spring Security
在Spring Boot启动类上添加EnableWebSecurity、Configuration注解并继承WebSecurityConfigurerAdapter。
Configuration
EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {//...
}添加用户信息
我们需要添加两个用户信息一个是普通用户一个是管理员用户。
Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {// 普通用户auth.inMemoryAuthentication().withUser(user).password(123456).roles(USER);// 管理员用户auth.inMemoryAuthentication().withUser(admin).password(123456).roles(USER, ADMIN);
}配置授权规则
我们需要在配置类中配置哪些路径需要哪些权限才能访问以及哪些路径不需要进行安全认证。
Override
protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers(/admin).hasAnyRole(ADMIN).antMatchers(/user).hasAnyRole(USER, ADMIN).anyRequest().authenticated().and().formLogin();
}其中
/admin路径需要ADMIN权限。/user路径需要USER和ADMIN权限。其他请求需要通过认证后才能访问。添加**formLogin()**方法开启默认登录界面。
运行程序
现在我们已经完成了一个简单的登录功能可以运行程序并使用添加的用户进行登录操作。
添加Spring Security的数据库认证
在上面的例子中我们将用户信息存储在了内存中但在实际应用中用户信息往往是存储在数据库中的。
首先我们要创建一张用户表来存储用户信息。
创建用户表
在数据库中创建一个名为 users 的数据表表的结构如下
CREATE TABLE users (id int(11) NOT NULL AUTO_INCREMENT,username varchar(45) NOT NULL,password varchar(255) DEFAULT NULL,enabled tinyint(1) DEFAULT 1,PRIMARY KEY (id)
);在该表中字段含义如下
id自增主键。username用户用户名。password用户密码使用BCrypt加密。enabled标记用户是否启用1为启用0为禁用。
添加依赖
我们需要添加Spring Security的数据库认证依赖到项目中:
dependencygroupIdorg.springframework.security/groupIdartifactIdspring-security-web/artifactIdversion${spring-security.version}/version
/dependency
dependencygroupIdorg.springframework.security/groupIdartifactIdspring-security-config/artifactIdversion${spring-security.version}/version
/dependency添加配置
我们需要添加以下配置
数据源配置UserDetailsService配置PasswordEncoder配置AuthenticationProvider配置HttpSecurity配置
Configuration
EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {Autowiredprivate DataSource dataSource;Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());}Beanpublic UserDetailsService userDetailsService() {return new JdbcUserDetailsManager(dataSource);}Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers(/admin/**).hasRole(ADMIN).antMatchers(/user/**).hasAnyRole(USER, ADMIN).anyRequest().authenticated().and().formLogin().loginPage(/login).permitAll().and().logout().permitAll();}Beanpublic AuthenticationProvider authenticationProvider() {DaoAuthenticationProvider provider new DaoAuthenticationProvider();provider.setUserDetailsService(userDetailsService());provider.setPasswordEncoder(passwordEncoder());return provider;}
}在代码中userDetailsService()方法返回一个JdbcUserDetailsManager对象该对象用于从数据库中加载用户信息。
PasswordEncoder是用于加密密码的我们使用了BCryptPasswordEncoder来加密密码。
最后我们还需要配置一个AuthenticationProvider用于处理认证请求。
添加用户信息到数据库
我们需要向数据库中添加一些测试用的用户信息可以使用以下代码
Autowired
private DataSource dataSource;Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {auth.jdbcAuthentication().dataSource(dataSource).withUser(user).password(passwordEncoder().encode(password)).roles(USER).and().withUser(admin).password(passwordEncoder().encode(password)).roles(USER, ADMIN);
}运行程序
现在我们已经完成了数据库认证功能可以运行程序并使用添加的用户进行登录操作Spring Security会从数据库中读取用户信息并进行认证。
总结
Spring Security是一个非常好用的身份认证和授权框架可以有效保证应用的安全性。本文介绍了如何使用Spring Security实现基本的登录功能和数据库认证希望这篇文章能够帮助到你。 。