写一个springboot集成SpringSecurity的例子,完成自定义登录与授权
时间: 2024-02-28 16:27:09 浏览: 82
以下是一个简单的SpringBoot集成SpringSecurity的例子,实现自定义登录和授权。
1. 添加依赖
在`pom.xml`文件中添加如下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 配置SpringSecurity
在`application.properties`文件中添加如下配置:
```properties
# 禁用csrf
security.enable-csrf=false
# 配置自定义登录页面
spring.security.login-form=/login
# 配置自定义登录接口
spring.security.login-processing-url=/login
```
3. 创建自定义UserDetailsService实现类
创建一个实现`UserDetailsService`接口的类`CustomUserDetailsService`,用于从数据库中获取用户信息。在该类中,我们需要注入一个`UserRepository`,用于从数据库中获取用户信息。
```java
@Service
public class CustomUserDetailsService 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 with username: " + username);
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
new ArrayList<>());
}
}
```
4. 创建自定义User实体类和Repository接口
创建一个`User`实体类,用于表示用户信息,并创建一个`UserRepository`接口,用于从数据库中获取用户信息。
```java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// getter and setter methods
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
```
5. 创建自定义授权规则
创建一个实现`GrantedAuthority`接口的类`CustomGrantedAuthority`,用于表示用户的授权角色。在该类中,我们需要定义一个`role`属性,表示用户的角色。
```java
public class CustomGrantedAuthority implements GrantedAuthority {
private String role;
public CustomGrantedAuthority(String role) {
this.role = role;
}
@Override
public String getAuthority() {
return role;
}
}
```
6. 创建自定义AuthenticationProvider实现类
创建一个实现`AuthenticationProvider`接口的类`CustomAuthenticationProvider`,用于自定义用户的认证和授权规则。在该类中,我们需要注入`UserDetailsService`和`PasswordEncoder`对象,并实现`authenticate()`方法和`supports()`方法。
```java
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (userDetails == null) {
throw new UsernameNotFoundException("User not found with username: " + username);
}
if (!passwordEncoder.matches(password, userDetails.getPassword())) {
throw new BadCredentialsException("Invalid password");
}
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new CustomGrantedAuthority("ROLE_USER"));
return new UsernamePasswordAuthenticationToken(username, password, authorities);
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
```
7. 创建自定义登录页面和控制器
在`resources/templates`目录下创建一个`login.html`文件,用于自定义登录页面。在`com.example.demo.controller`包下创建一个`LoginController`类,用于处理登录请求。
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h3>Login Page</h3>
<form action="/login" method="post">
<input type="text" name="username" placeholder="Username" required/><br>
<input type="password" name="password" placeholder="Password" required/><br>
<input type="submit" value="Login"/>
</form>
</body>
</html>
```
```java
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/home")
public String home() {
return "home";
}
}
```
8. 创建自定义授权规则配置类
创建一个实现`WebSecurityConfigurerAdapter`类的`CustomWebSecurityConfigurer`类,用于自定义授权规则。在该类中,我们需要注入`CustomAuthenticationProvider`对象,并重写`configure()`方法。
```java
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/home").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
9. 运行程序
启动应用程序后,访问`http://localhost:8080/login`,将跳转到自定义的登录页面。输入正确的用户名和密码,将跳转到自定义的`home`页面。如果输入错误的用户名或密码,将返回错误信息。
阅读全文