security依赖
时间: 2023-11-25 17:51:53 浏览: 29
在Spring Boot项目中,我们可以通过添加Spring Security的起步依赖来引入Security依赖。具体步骤如下:
1.在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2.在Spring Boot的主类上添加`@EnableWebSecurity`注解,开启Web安全性配置。
3.创建一个继承自`WebSecurityConfigurerAdapter`的配置类,并重写`configure(HttpSecurity http)`方法,配置安全策略。
例如,以下是一个简单的Spring Security配置类:
```java
@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")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout()
.logoutSuccessUrl("/");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}admin").roles("ADMIN")
.and()
.withUser("user").password("{noop}user").roles("USER");
}
}
```
上述配置中,我们定义了两个用户,一个是admin,一个是user,分别具有不同的角色。我们还定义了访问/admin/**路径需要ADMIN角色,访问/user/**路径需要ADMIN或USER角色,其他路径需要认证后才能访问。