spring boot鉴权实现代码
时间: 2023-08-01 09:14:31 浏览: 97
以下是一个简单的 Spring Boot 鉴权实现代码示例:
1. 定义用户实体类
```java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
// getter 和 setter 方法省略
}
```
2. 定义用户服务接口
```java
public interface UserService {
User findByUsername(String username);
}
```
3. 实现用户服务接口
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
}
```
4. 定义鉴权过滤器
```java
public class AuthFilter extends OncePerRequestFilter {
@Autowired
private UserService userService;
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String header = request.getHeader("Authorization");
String username = null;
String jwt = null;
if (header != null && header.startsWith("Bearer ")) {
jwt = header.substring(7);
username = jwtUtil.extractUsername(jwt);
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
User user = userService.findByUsername(username);
if (jwtUtil.validateToken(jwt, user)) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}
}
```
5. 配置鉴权过滤器
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthFilter authFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/api/authenticate").permitAll().anyRequest().authenticated();
http.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class);
}
}
```
6. 定义 JWT 工具类
```java
@Component
public class JwtUtil {
private final String SECRET_KEY = "my_secret_key";
private final long JWT_EXPIRATION = 604800000L;
public String generateToken(User user) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, user.getUsername());
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION)).signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
}
public boolean validateToken(String token, User user) {
String username = extractUsername(token);
return (username.equals(user.getUsername()) && !isTokenExpired(token));
}
private boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
public Date extractExpiration(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getExpiration();
}
public String extractUsername(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject();
}
}
```
以上代码实现了一个简单的基于 JWT 的 Spring Boot 鉴权机制,具体实现过程中还需要根据具体需求进行调整和扩展。
阅读全文