java 写一个 springsecurity登录验证
时间: 2023-07-01 19:15:46 浏览: 51
好的,下面是一个简单的 Spring Security 登录验证的示例:
首先,在 pom.xml 中添加以下依赖:
```
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.4.2</version>
</dependency>
```
接着,在 Spring 配置文件中添加以下配置:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.permitAll();
}
}
```
上述代码中,我们配置了一个名为 SecurityConfig 的类,继承了 WebSecurityConfigurerAdapter 类。其中,我们注入了一个 UserDetailsService 的实现类,用于获取用户信息;并且创建了一个 PasswordEncoder 实例,用于加密密码。
在 configure(AuthenticationManagerBuilder auth) 方法中,我们将我们的 UserDetailsService 和 PasswordEncoder 注入到 AuthenticationManagerBuilder 中,用于验证用户身份。
在 configure(HttpSecurity http) 方法中,我们配置了登录页面、登录成功后跳转的页面等信息。
最后,我们需要实现 UserDetailsService 接口,例如:
```
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
AuthorityUtils.createAuthorityList(user.getRole()));
}
}
```
上述代码中,我们通过 UserDao 找到了指定用户名的 User 对象,并将其转换为 UserDetails 对象返回。这里需要注意的是,我们需要将 User 对象的角色转换为 AuthorityList,以便 Spring Security 进行权限验证。
这样,一个简单的 Spring Security 登录验证就完成了。