Spring Boot Sercurity配置方法
时间: 2024-02-22 21:51:55 浏览: 118
以下是Spring Boot Security的配置方法:
1.添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2.配置安全性
在application.properties文件中添加以下配置:
```properties
# 禁用CSRF保护
security.enable-csrf=false
# 配置登录页面
spring.security.login-page=/login
# 配置登录处理接口
spring.security.login-processing-url=/doLogin
# 配置退出登录接口
spring.security.logout-url=/logout
# 配置退出登录成功后跳转的页面
spring.security.logout-success-url=/
```
3.创建用户
在SecurityConfig类中创建用户:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("password")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
4.配置访问权限
在SecurityConfig类中配置访问权限:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/doLogin")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("password")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
5.测试
启动应用程序并访问受保护的页面,将会自动跳转到登录页面。输入正确的用户名和密码后,将会跳转回原始请求的页面。
阅读全文