帮我敲一个springboot登录验证的代码
时间: 2023-03-19 16:22:19 浏览: 70
好的,下面是一个简单的Spring Boot登录验证代码示例:
首先,需要在pom.xml中添加Spring Boot Web和Spring Boot Security的依赖:
```xml
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
```
然后,创建一个SecurityConfig类来配置Spring Security:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.permitAll();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
上面的代码配置了Spring Security的登录页面、注销、用户认证和权限控制等相关信息。
然后,创建一个UserDetailsServiceImpl类来实现UserDetailsService接口,用于获取用户的详细信息:
```java
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
}
}
```
最后,创建一个UserController类来处理登录相关的请求:
```java
@RestController
public class UserController {
@GetMapping("/")
public String index() {
return "欢迎访问首页!";
}
@GetMapping("/login")
public String login() {
return "请登录!";
}
@GetMapping("/home")
public String home() {
return "欢迎回来!";
}
}
```
上面的代码处理了首页、登录和主页的请求。
以上就是一个简单的Spring Boot登录验证代码示例,希望能对你有所帮助!