写一段 JWT+Spring Security控制接口权限的代码
时间: 2024-11-10 18:13:31 浏览: 22
Spring Boot Security 2.5.8 实现账号、手机号、邮件登录,记住密码等功能
JWT (JSON Web Token) 结合 Spring Security 可以帮助我们管理API的访问权限。以下是一个简单的例子,展示如何在一个Spring MVC控制器中使用JWT验证并限制对特定接口的访问:
首先,你需要添加依赖项到你的`pom.xml`文件中:
```xml
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
然后创建一个JWT生成工具类,例如`JwtUtil.java`:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
public class JwtUtil {
private static final String SECRET_KEY = "your-secret-key"; // 替换为你自己的密钥
public static String generateToken(User user) {
Claims claims = Jwts.claims().setSubject(user.getUsername());
return Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
}
```
接着,在`UserDetailsService`中处理用户信息:
```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("Invalid username or password");
}
return new org.springframework.security.core.userdetails.User(
user.getUsername(), // 用户名
user.getPassword(), // 密码
AuthorityUtils.createAuthorityList("ROLE_USER") // 权限列表
);
}
}
```
在配置`WebSecurityConfigurerAdapter`中添加JWT过滤器:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtUtil jwtUtil;
@Bean
public FilterRegistrationBean jwtAuthenticationFilter() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(new JwtAuthenticationFilter(jwtUtil));
registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); // 设置优先级
registrationBean.addUrlPatterns(HttpMethod.GET.name(), HttpMethod.POST.name()); // 仅对GET和POST请求生效
return registrationBean;
}
//...
}
```
最后,自定义JWT认证过滤器`JwtAuthenticationFilter.java`:
```java
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtUtil jwtUtil;
public JwtAuthenticationFilter(JwtUtil jwtUtil) {
this.jwtUtil = jwtUtil;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
//... 实现JWT验证逻辑,检查请求头中的Authorization字段是否包含有效的JWT
//如果验证通过,设置Principal到HttpServletRequest,继续传递请求
//如果验证失败,返回401 Unauthorized错误
}
}
```
现在,只有持有有效JWT的请求才能访问标注了`@PreAuthorize("hasRole('ROLE_USER')")`等权限注解的接口。
阅读全文