Springboot token登录的简单代码
时间: 2024-05-14 18:19:12 浏览: 119
以下是一个简单的 Spring Boot token 登录的代码示例:
1. 定义 User 实体类
```java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
// getters and setters
}
```
2. 定义 UserRepository 接口
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}
```
3. 定义 JwtTokenUtil 工具类
```java
@Component
public class JwtTokenUtil {
private static final String SECRET_KEY = "my_secret_key";
private static final long EXPIRATION_TIME = 864_000_000; // 10 days
public String generateToken(User user) {
Map<String, Object> claims = new HashMap<>();
claims.put("username", user.getUsername());
return Jwts.builder()
.setClaims(claims)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
return false;
}
}
public String getUsernameFromToken(String token) {
Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
return claims.get("username").toString();
}
}
```
4. 定义 AuthenticationController 类
```java
@RestController
@RequestMapping("/auth")
public class AuthenticationController {
private final UserRepository userRepository;
private final AuthenticationManager authenticationManager;
private final JwtTokenUtil jwtTokenUtil;
public AuthenticationController(UserRepository userRepository, AuthenticationManager authenticationManager, JwtTokenUtil jwtTokenUtil) {
this.userRepository = userRepository;
this.authenticationManager = authenticationManager;
this.jwtTokenUtil = jwtTokenUtil;
}
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthenticationRequest authenticationRequest) {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword()));
} catch (BadCredentialsException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
}
User user = userRepository.findByUsername(authenticationRequest.getUsername()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
String token = jwtTokenUtil.generateToken(user);
return ResponseEntity.ok(new AuthenticationResponse(token));
}
}
```
5. 定义 AuthenticationRequest 和 AuthenticationResponse 类
```java
public class AuthenticationRequest {
private String username;
private String password;
// getters and setters
}
public class AuthenticationResponse {
private String token;
public AuthenticationResponse(String token) {
this.token = token;
}
// getters and setters
}
```
6. 配置 Spring Security
```java
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final UserRepository userRepository;
private final JwtTokenUtil jwtTokenUtil;
public SecurityConfiguration(UserRepository userRepository, JwtTokenUtil jwtTokenUtil) {
this.userRepository = userRepository;
this.jwtTokenUtil = jwtTokenUtil;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(username -> userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found")));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenUtil), UsernamePasswordAuthenticationFilter.class);
}
}
```
7. 定义 JwtAuthenticationFilter 类
```java
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenUtil jwtTokenUtil;
public JwtAuthenticationFilter(JwtTokenUtil jwtTokenUtil) {
this.jwtTokenUtil = jwtTokenUtil;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
String token = authorizationHeader.substring(7);
if (jwtTokenUtil.validateToken(token)) {
String username = jwtTokenUtil.getUsernameFromToken(token);
UserDetails userDetails = User.builder().username(username).password("").authorities(Collections.emptyList()).build();
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
}
```
以上就是一个简单的 Spring Boot token 登录的代码示例。
阅读全文