下面是详细讲解“SpringBoot集成Auth0 JWT的示例代码”的完整攻略,其中包含两条示例。
1. 准备工作
在开始之前,需要确保以下环境已经完成配置:
- JDK 1.8
- Maven
- IDE(推荐IntelliJ IDEA)
此外,需要在 Auth0 网站上注册并创建一个应用程序,获取应用程序的 Client ID 和 Client Secret。
2. 添加依赖
为了在 Spring Boot 应用程序中使用 JWT,需要引入如下依赖:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>5.3.1</version>
</dependency>
3. 编写验证拦截器
为了验证 JWT,需要编写一个拦截器来检查请求中是否包含 JWT。如果请求中包含有效的 JWT,则允许请求通过,否则将返回错误响应。
@Component
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {
@Value("${auth0.audience}")
private String audience;
@Value("${auth0.issuer}")
private String issuer;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
String token = getToken(request);
Algorithm algorithm = Algorithm.RSA256(null, readPublicKey());
JWTVerifier verifier = JWT.require(algorithm)
.withAudience(audience)
.withIssuer(issuer)
.build();
DecodedJWT jwt = verifier.verify(token);
String userId = jwt.getClaim("sub").asString();
String[] roles = jwt.getClaim("permissions").asArray(String.class);
List<GrantedAuthority> authorities = new ArrayList<>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
Authentication authentication = new UsernamePasswordAuthenticationToken(userId, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (Exception e) {
SecurityContextHolder.clearContext();
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized");
}
filterChain.doFilter(request, response);
}
private String getToken(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
throw new RuntimeException("Invalid token");
}
return header.substring(7);
}
private RSAPublicKey readPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
String publicKey = IOUtils.resourceToString("/publicKey.txt", StandardCharsets.UTF_8);
publicKey = publicKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
byte[] bytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}
}
4. 配置 Spring Security
为了启用 JWT 验证拦截器,需要在 Spring Security 配置文件中进行如下配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.authorizeRequests().anyRequest().authenticated();
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
5. 配置 Auth0
在开始验证 JWT 之前,需要在 Auth0 控制台中进行如下配置:
- 在 Auth0 控制台中创建一个应用程序。
- 配置应用程序的颁发者和受众。
- 为应用程序创建一个自定义的登录页面,方便在验证失败情况下返回合适的错误信息。
示例1:生成 JWT
以下是生成 JWT 的示例代码,这些代码应该在用户成功登录后运行:
String publicKey = IOUtils.resourceToString("/privateKey.txt", StandardCharsets.UTF_8);
Algorithm algorithm = Algorithm.RSA256(null, readPrivateKey(privateKey));
String[] permissions = new String[]{"ROLE_ADMIN", "ROLE_USER"};
String token = JWT.create()
.withIssuer(issuer)
.withAudience(audience)
.withSubject(userId)
.withArrayClaim("permissions", permissions)
.sign(algorithm);
示例2:验证 JWT
以下是验证 JWT 的示例代码,这些代码应该在将请求发送到受保护的 API 之前运行:
String header = "Bearer " + token;
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", header);
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
其中 token
是从前端传递过来的 JWT 字符串,url
是受保护的 API 的 URL,restTemplate
是用于发起 HTTP 请求的 RestTemplate
实例。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot集成Auth0 JWT的示例代码 - Python技术站