一、介绍
OAuth2是一种授权框架,通常用于提供Web应用程序或服务对持授权的用户数据的访问权限。而JWT(JSON Web Token)则是一种可以跨域传输的安全令牌,是用于身份验证的开放标准。 jwtoauth2是基于OAuth2的标准实现。它使用JWT作为标准的令牌格式,与OAuth2一起来对外部客户端应用程序的访问进行授权。
二、jwtoauth2与oauth2区别
- 令牌的格式 在OAuth2中,令牌通常是一个字符串,该字符串由一组随机字符和一个可选的刷新令牌组成,以及一个可选的过期时间。
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
而在jwtoauth2中,令牌是一个经过哈希处理的JSON对象。它包含所有必要的数据,如令牌类型、颁发者、颁发时间、过期时间和访问权限等。
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTYyMzkzODR9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
- 令牌的加密方式 OAuth2主要使用传输层安全性协议(TLS)来加密令牌,而jwtoauth2则使用JSON Web签名(JWS)或JSON Web加密(JWE)来保证令牌的安全性。
- 令牌的用途 在OAuth2中,令牌主要用于授权访问受保护资源。在jwtoauth2中,令牌不仅可以用于授权访问受保护资源,还可以用于设备身份验证、用户身份验证等多种用途。
三、jwtoauth2示例代码
以下示例介绍了如何通过jwtoauth2在Spring Boot中使用OAuth2。
- 添加依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
- 配置Spring Security
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**").authenticated()
.and().oauth2ResourceServer().jwt();
}
@Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter());
return jwtDecoder;
}
}
@Component
public class UsernameSubClaimAdapter implements Converter<Jwt, Jwt> {
@Override
public Jwt convert(Jwt jwt) {
Map<String, Object> claims = new LinkedHashMap<>(jwt.getClaims());
Object username = jwt.getClaims().get("sub");
claims.put("username", username);
return new Jwt(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), jwt.getHeaders(), claims);
}
}
- 配置OAuth2客户端
@Configuration
public class ClientConfig {
@Bean
ClientRegistrationRepository clientRegistrationRepository() {
List<ClientRegistration> registrations = new ArrayList<>();
registrations.add(gitHubRegistration());
return new InMemoryClientRegistrationRepository(registrations);
}
private ClientRegistration gitHubRegistration() {
return ClientRegistration.withRegistrationId("github")
.clientId("github-client-id")
.clientSecret("github-client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("read:user")
.authorizationUri("https://github.com/login/oauth/authorize")
.tokenUri("https://github.com/login/oauth/access_token")
.userInfoUri("https://api.github.com/user")
.userNameAttributeName("id")
.clientName("GitHub")
.build();
}
}
- 启动应用程序后,可以通过下面的URI进行OAuth2授权:
http://localhost:8080/oauth2/authorization/github
- 在授权后,可以通过下面的URI获取受保护资源:
http://localhost:8080/api/user
四、结论
jwtoauth2是OAuth2协议的补充,它使用JWT代替了OAuth2的令牌格式,更加安全可靠。通过对比,我们可以清晰地认识到它们在令牌格式、令牌加密方式、令牌用途等方面的区别。