1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.security.oauth.consumer.token;
18
19 import org.springframework.security.core.AuthenticationException;
20 import org.springframework.security.oauth.consumer.OAuthConsumerToken;
21 import org.springframework.security.oauth.consumer.OAuthSecurityContext;
22 import org.springframework.security.oauth.consumer.OAuthSecurityContextHolder;
23
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpSession;
26
27
28
29
30
31
32 public class HttpSessionBasedTokenServices implements OAuthConsumerTokenServices {
33
34 public static final String KEY_PREFIX = "OAUTH_TOKEN";
35
36
37 public OAuthConsumerToken getToken(String resourceId) throws AuthenticationException {
38 HttpSession session = getSession();
39 OAuthConsumerTokenrg/springframework/security/oauth/consumer/OAuthConsumerToken.html#OAuthConsumerToken">OAuthConsumerToken consumerToken = (OAuthConsumerToken) session.getAttribute(KEY_PREFIX + "#" + resourceId);
40 if (consumerToken != null) {
41 Long expiration = (Long) session.getAttribute(KEY_PREFIX + "#" + resourceId + "#EXPIRATION");
42 if (expiration != null && (System.currentTimeMillis() > expiration)) {
43
44 removeToken(resourceId);
45 consumerToken = null;
46 }
47 }
48
49 return consumerToken;
50 }
51
52 public void storeToken(String resourceId, OAuthConsumerToken token) {
53 HttpSession session = getSession();
54 session.setAttribute(KEY_PREFIX + "#" + resourceId, token);
55
56
57 Long expiration = null;
58 String expiresInValue = token.getAdditionalParameters() != null ? token.getAdditionalParameters().get("oauth_expires_in") : null;
59 if (expiresInValue != null) {
60 try {
61 expiration = System.currentTimeMillis() + (Integer.parseInt(expiresInValue) * 1000);
62 }
63 catch (NumberFormatException e) {
64
65 }
66 }
67
68 if (expiration != null) {
69 session.setAttribute(KEY_PREFIX + "#" + resourceId + "#EXPIRATION", expiration);
70 }
71 }
72
73 public void removeToken(String resourceId) {
74 getSession().removeAttribute(KEY_PREFIX + "#" + resourceId);
75 }
76
77 protected HttpSession getSession() {
78 OAuthSecurityContext context = OAuthSecurityContextHolder.getContext();
79 if (context == null) {
80 throw new IllegalStateException("A security context must be established.");
81 }
82
83 HttpServletRequest request;
84 try {
85 request = (HttpServletRequest) context.getDetails();
86 }
87 catch (ClassCastException e) {
88 throw new IllegalStateException("The security context must have the HTTP servlet request as its details.");
89 }
90
91 if (request == null) {
92 throw new IllegalStateException("The security context must have the HTTP servlet request as its details.");
93 }
94
95 HttpSession session = request.getSession(true);
96 if (session == null) {
97 throw new IllegalStateException("Unable to create a session in which to store the tokens.");
98 }
99
100 return session;
101 }
102
103 }