请给出一个简单的spring security示例程序
时间: 2023-07-18 11:32:18 浏览: 48
好的,下面是一个简单的Spring Security示例程序:
1.首先,需要在pom.xml文件中添加Spring Security依赖,例如:
```xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.5.1</version>
</dependency>
```
2.然后,需要创建一个Spring Security配置类,例如:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}password").roles("USER", "ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").hasAnyRole("USER", "ADMIN")
.and()
.formLogin()
.and()
.logout().logoutSuccessUrl("/");
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
```
3.在上述配置类中,我们指定了两个用户,一个是普通用户,一个是管理员用户。我们还定义了两个URL模式,其中/admin/**模式的URL需要管理员权限才能访问,而其他URL需要用户或管理员权限才能访问。最后,我们配置了一个简单的登录表单和注销功能。
4.在上述配置类中,我们使用了一个InMemoryUserDetailsManager来存储我们的用户信息。在实际应用中,你可以使用其他的用户存储方式,例如数据库。
这是一个非常简单的Spring Security示例程序,它可以让你开始了解Spring Security的基本概念和用法。