1
2
3
4
5
6
7
8
9
10
11
12
13 package org.springframework.security.oauth2.common;
14
15 import java.io.IOException;
16 import java.util.Date;
17 import java.util.Map;
18 import java.util.Set;
19
20 import org.springframework.util.Assert;
21
22 import com.fasterxml.jackson.core.JsonGenerationException;
23 import com.fasterxml.jackson.core.JsonGenerator;
24 import com.fasterxml.jackson.databind.SerializerProvider;
25 import com.fasterxml.jackson.databind.ser.std.StdSerializer;
26
27
28
29
30
31
32
33
34
35
36 public final class OAuth2AccessTokenJackson2Serializer extends StdSerializer<OAuth2AccessToken> {
37
38 public OAuth2AccessTokenJackson2Serializer() {
39 super(OAuth2AccessToken.class);
40 }
41
42 @Override
43 public void serialize(OAuth2AccessToken token, JsonGenerator jgen, SerializerProvider provider) throws IOException,
44 JsonGenerationException {
45 jgen.writeStartObject();
46 jgen.writeStringField(OAuth2AccessToken.ACCESS_TOKEN, token.getValue());
47 jgen.writeStringField(OAuth2AccessToken.TOKEN_TYPE, token.getTokenType());
48 OAuth2RefreshToken refreshToken = token.getRefreshToken();
49 if (refreshToken != null) {
50 jgen.writeStringField(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue());
51 }
52 Date expiration = token.getExpiration();
53 if (expiration != null) {
54 long now = System.currentTimeMillis();
55 jgen.writeNumberField(OAuth2AccessToken.EXPIRES_IN, (expiration.getTime() - now) / 1000);
56 }
57 Set<String> scope = token.getScope();
58 if (scope != null && !scope.isEmpty()) {
59 StringBuffer scopes = new StringBuffer();
60 for (String s : scope) {
61 Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + "");
62 scopes.append(s);
63 scopes.append(" ");
64 }
65 jgen.writeStringField(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1));
66 }
67 Map<String, Object> additionalInformation = token.getAdditionalInformation();
68 for (String key : additionalInformation.keySet()) {
69 jgen.writeObjectField(key, additionalInformation.get(key));
70 }
71 jgen.writeEndObject();
72 }
73 }