spring-boot:使用spring security实现用户登录注册(二)configuration配置

本文介绍如何在Spring Boot项目中使用Spring Security进行用户登录注册的配置,包括HttpSecurity对象的设置,如URL规则、登录登出行为及登录状态的管理。通过自定义配置类并继承WebSecurityConfigurerAdapter,实现对URL访问权限、登录页面和登出行为的定制。
摘要由CSDN通过智能技术生成

项目地址:https://github.com/lizhibin205/simple_web_v2

如果不适用spring boot security的默认配置,必须创建一个配置类继承org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

在开发中,我们可以重载特定的方法,实现不同的配置:

方法名 作用 默认配置
protected void configure(HttpSecurity http) throws Exception 配置需要权限验证的url规则

适用httpbasic验证

所有url均验证权限

public UserDetailsService userDetailsService() 自定义用户验证规则 使用默认账号密码(密码在控制台中输出)
     

HttpSecurity对象

HttpSecurity允许我们配置那些url是需要权限验证的,已

Spring Boot 项目中使用 Spring Security,需要添加 spring-boot-starter-security 依赖。以下是一个简单的配置示例: 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置权限 在 Spring Security 中,权限(Authority)是指用户可以执行的操作。可以通过配置权限来限制用户的访问。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("ADMIN", "USER") .antMatchers("/**").permitAll() .and().formLogin() .and().logout().logoutSuccessUrl("/login?logout"); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{noop}admin123").roles("ADMIN") .and() .withUser("user").password("{noop}user123").roles("USER"); } } ``` 在上面的配置中,我们定义了三个权限: - /admin/**:只有 ADMIN 角色的用户可以访问 - /user/**:只有 ADMIN 或 USER 角色的用户可以访问 - /**:所有用户都可以访问 最后,我们使用 inMemoryAuthentication() 方法来定义两个用户和它们的角色。 3. 配置登录和退出 在上面的配置中,我们使用 formLogin() 方法来配置登录页面和处理登录请求的 URL。同时,我们也使用 logout() 方法来配置退出登录的 URL 和成功退出后的跳转页面。 ``` .and().formLogin() .and().logout().logoutSuccessUrl("/login?logout"); ``` 这里我们配置了退出登录后跳转到登录页面,并添加了一个参数表示已经退出登录。 4. 配置 CSRF 在 Spring Security 中,默认开启了 CSRF(Cross-site Request Forgery)保护,可以有效防止跨站点攻击。如果你的应用程序不需要 CSRF 保护,可以通过以下配置关闭: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); } } ``` 5. 配置 HTTPS 在 Spring Security 中,可以通过以下配置开启 HTTPS 支持: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requiresChannel() .anyRequest().requiresSecure(); } } ``` 以上就是使用 spring-boot-starter-security 进行 Spring Security 配置的示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值