这几天对json的序列化和反序列化特别感兴趣,死磕spring boot的接口返回数据和接收参数。然后在折腾的过程中无意间发现一个问题,从这个问题出发不断的死磕,拓宽了一些知识面,很开心,所以在这分享一下。
问题背景:我基于spring boot写的rest接口,权限这一块使用的是spring security oauth2,然后api文档使用swagger2。这三块配合的都挺好的,在swagger文档页面使用用户名和密码获取token,然后swagger会自动在访问接口的时候把token加在header里面,从而实现接口调用。
然而就在我把spring boot序列化数据的框架从jackson切换到fastjson之后,就出现了一个问题,swagger文档页正常登陆后无法访问接口,显示需要认证。
我开始很纳闷,为啥我登录成功了之后调用接口还是显示未认证呢,还重复登录了几次。但是后面我一看curl的情况,发现header里面就没有token的信息,那肯定是未认证啊。
于是我用postman模拟登录,获取token,发现返回值变成了下面这样
顿时就反应过来是怎么回事儿了,使用默认的jackson序列化登录返回的token是下面这样的
现在明白了,swagger取token值的时候是按照access_token
这个key来取的,但是使用fastjson之后,token值的key变成value
了,所以swagger取不到了,就无法调用接口了。
那为啥会两个框架得到的结果不一样呢?我们先去看看Oauth2AccessToken
这个接口
@org.codehaus.jackson.map.annotate.JsonSerialize(using = OAuth2AccessTokenJackson1Serializer.class)
@org.codehaus.jackson.map.annotate.JsonDeserialize(using = OAuth2AccessTokenJackson1Deserializer.class)
@com.fasterxml.jackson.databind.annotation.JsonSerialize(using = OAuth2AccessTokenJackson2Serializer.class)
@com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = OAuth2AccessTokenJackson2Deserializer.class)
public interface OAuth2AccessToken {
public static String BEARER_TYPE = "Bearer";
public static String OAUTH2_TYPE = "OAuth2";
/**
* The access token issued by the authorization server. This value is REQUIRED.
*/
public static String ACCESS_TOKEN = "access_token";
/**
* The type of the token issued as described in Section 7.1. Value is case insensitive.
* This value is REQUIRED.
*/
public static String TOKEN_TYPE = "token_type";
/**
* The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will
* expire in one hour from the time the response was generated. This value is OPTIONAL.
*/
public static String EXPIRES_IN = "expires_in";
/**
* The refresh token which can be used to obtain new access tokens using the same authorization grant as described
* in Section 6. This value is OPTIONAL.
*/
public static String REFRESH_TOKEN = "refresh_token";
/**
* The scope of the access token as described by Section 3.3
*/
public static String SCOPE = "scope";
/**
* The additionalInformation map is used by the token serializers to export any fields used by extensions of OAuth.
* @return a map from the field name in the serialized token to the value to be exported. The default serializers
* make use of Jackson's automatic JSON mapping for Java objects (for the Token Endpoint flows) or implicitly call
* .toString() on the "value" object (for the implicit flow) as part of the serialization process.
*/
Map getAdditionalInformation();
Set getScope();
OAuth2RefreshToken getRefreshToken();
String getTokenType();
boolean isExpired();
Date getExpiration();
int getExpiresIn();
String getValue();
}
上面的四个注解指定了token序列化和反序列化对应的类,我们需要查看的是databind
包下的序列化类OAuth2AccessTokenJackson2Serializer
public final class OAuth2AccessTokenJackson2Serializer extends StdSerializer {
public OAuth2AccessTokenJackson2Serializer() {
super(OAuth2AccessToken.class);
}
@Override
public void serialize(OAuth2AccessToken token, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonGenerationException {
jgen.writeStartObject();
jgen.writeStringField(OAuth2AccessToken.ACCESS_TOKEN, token.getValue());
jgen.writeStringField(OAuth2AccessToken.TOKEN_TYPE, token.getTokenType());
OAuth2RefreshToken refreshToken = token.getRefreshToken();
if (refreshToken != null) {
jgen.writeStringField(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue());
}
Date expiration = token.getExpiration();
if (expiration != null) {
long now = System.currentTimeMillis();
jgen.writeNumberField(OAuth2AccessToken.EXPIRES_IN, (expiration.getTime() - now) / 1000);
}
Set scope = token.getScope();
if (scope != null && !scope.isEmpty()) {
StringBuffer scopes = new StringBuffer();
for (String s : scope) {
Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + "");
scopes.append(s);
scopes.append(" ");
}
jgen.writeStringField(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1));
}
Map additionalInformation = token.getAdditionalInformation();
for (String key : additionalInformation.keySet()) {
jgen.writeObjectField(key, additionalInformation.get(key));
}
jgen.writeEndObject();
}
}
代码很简单,我就不写注释带着大家看了。
看到这就明白了,使用jackson的时候,token的序列化是经过特殊处理的。而使用fastjson的时候,token的序列化没有特殊处理,就直接把token对象序列化为json数据了。
那现在如何解决上面那个问题呢?我想了两种方案。
第一种方案: 配置fastjson处理Oauth2AccessToken类的序列化。
第二种方案: 写一个类包装Oauth2AccessToken,然后配置该类的序列化方式。
在网上查了一些资料,并且阅读了一些fastjson的文档,我选择了第二种解决方案(主要是第一种没有搞定,fastjson的配置这一块我还不太熟悉)。下面说一下解决方案,贴一下代码。
//因为此类没有自己的属性,所以设置includes为空就过滤了父类的所有字段
@JSONType(includes = {""})
public class MyToken extends DefaultOAuth2AccessToken {
public MyToken(OAuth2AccessToken accessToken) {
super(accessToken);
}
@JSONField(name = "access_token", ordinal = 1)
public String getAccessTokenValue() {
return super.getValue();
}
@JSONField(name = "token_type", ordinal = 2)
public String getTokenTypeValue() {
return super.getTokenType();
}
@JSONField(name = "refresh_token", ordinal = 3)
public String getRefreshTokenValue() {
return super.getRefreshToken().getValue();
}
@JSONField(name = "expires_in", ordinal = 4)
public int getExpiresInValue() {
return super.getExpiresIn();
}
@JSONField(name = "scope", ordinal = 5)
public String getScopeValue() {
return String.join(",", super.getScope());
}
}
现在登录接口返回就变成了下面这样
和jackson序列化的结果一模一样了。现在swagger的功能正常了。