如何使用spring security代码的简单实现
时间: 2023-09-21 07:11:25 浏览: 43
以下是使用Spring Security代码的简单实现步骤:
1. 添加Spring Security依赖
在项目的pom.xml文件中添加Spring Security依赖:
```
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
```
2. 配置Spring Security
创建一个配置类,用于配置Spring Security。
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").permitAll()
.and()
.formLogin()
.and()
.logout()
.logoutSuccessUrl("/")
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}password").roles("ADMIN");
}
}
```
该配置类:
- 继承自WebSecurityConfigurerAdapter类,该类是Spring Security提供的一个方便的实现类;
- 通过@EnableWebSecurity注解启用Spring Security;
- 在configure()方法中配置访问控制规则;
- 在configureGlobal()方法中配置用户认证信息。
3. 运行应用程序
运行应用程序,访问受保护的URL时,应该会看到登录页面。使用上面配置的用户名和密码进行登录。如果用户名和密码正确,则可以访问被授权的URL。
至此,使用Spring Security代码的简单实现就完成了。