用java写一个spring boot 的token验证
时间: 2023-05-22 18:01:18 浏览: 68
可以使用Spring Security框架来实现Token验证。首先,需要在pom.xml文件中添加Spring Security依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
然后,在Spring Boot应用程序的主类上添加@EnableWebSecurity注释,以启用Spring Security:
```
@SpringBootApplication
@EnableWebSecurity
public class MyApp {
// ...
}
```
接下来,创建一个继承自WebSecurityConfigurerAdapter的配置类,并覆盖configure(HttpSecurity http)方法,以配置安全性:
```
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.and()
.addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
```
在上面的配置中,我们禁用了CSRF保护,并配置了一个基于JWT的身份验证过滤器。接下来,我们需要实现JwtAuthenticationFilter类,以验证Token:
```
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = extractToken(request);
if (token != null && validateToken(token)) {
Authentication auth = new UsernamePasswordAuthenticationToken(token, null, Collections.emptyList());
SecurityContextHolder.getContext().setAuthentication(auth);
}
filterChain.doFilter(request, response);
}
private String extractToken(HttpServletRequest request) {
// 从请求头中提取Token
String header = request.getHeader("Authorization");
if (header != null && header.startsWith("Bearer ")) {
return header.substring(7);
}
return null;
}
private boolean validateToken(String token) {
// 验证Token的有效性
// ...
return true;
}
}
```
最后,我们需要在控制器中使用@PreAuthorize注释来限制访问:
```
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
@PreAuthorize("hasAuthority('ROLE_USER')")
public String hello() {
return "Hello, World!";
}
}
```
在上面的示例中,我们使用@PreAuthorize注释来限制只有具有ROLE_USER权限的用户才能访问/hello端点。