基于SpringSecurity的登录
时间: 2023-07-25 18:17:28 浏览: 41
Spring Security 是一个强大的框架,可以帮助我们实现身份验证和授权的功能。下面是基于 Spring Security 的登录步骤:
1. 添加 Spring Security 依赖和配置文件
首先,在 pom.xml 中添加 Spring Security 依赖:
```
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
```
然后,创建一个 Spring Security 的配置类,继承自 WebSecurityConfigurerAdapter 类,并覆盖 configure() 方法:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/").permitAll()
.and()
.logout().permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
2. 创建 UserDetailsService 接口和实现类
创建一个 UserDetailsService 接口和实现类,用于查询用户信息和权限信息。
```
@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("User not found");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
getAuthorities(user.getRoles()));
}
private Collection<? extends GrantedAuthority> getAuthorities(Set<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
}
```
3. 创建 LoginController
创建一个 LoginController 类,并添加 login() 方法,用于处理登录请求。
```
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null) {
model.addAttribute("error", "Your username and password is invalid.");
}
if (logout != null) {
model.addAttribute("message", "You have been logged out successfully.");
}
return "login";
}
}
```
4. 创建登录页面
最后,创建一个登录页面(login.html),用于用户输入用户名和密码。
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<div th:if="${error}" class="alert alert-danger">
Invalid username or password.
</div>
<div th:if="${message}" class="alert alert-success">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required="required"/>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password" required="required"/>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</body>
</html>
```
以上就是基于 Spring Security 的登录步骤。需要注意的是,这只是一个简单的示例,实际应用中还需要考虑更多的安全性问题。