0
# Session Token Operations
1
2
Session token management for MFA-protected operations and temporary credential generation for existing IAM users. Session tokens enable secure access to MFA-required operations and provide temporary credentials with the same permissions as the calling user.
3
4
## Capabilities
5
6
### Session Token Generation
7
8
Returns temporary credentials for IAM users, typically used for MFA-protected operations.
9
10
```java { .api }
11
/**
12
* Returns temporary security credentials for IAM users
13
* @param getSessionTokenRequest Request containing optional MFA information and duration
14
* @return Result containing temporary credentials with same permissions as calling user
15
* @throws RegionDisabledException If STS not activated in requested region
16
*/
17
GetSessionTokenResult getSessionToken(GetSessionTokenRequest getSessionTokenRequest);
18
19
/**
20
* Simplified method form for getting session token with default parameters
21
* @return Result containing temporary credentials
22
*/
23
GetSessionTokenResult getSessionToken();
24
```
25
26
**Request and Result Types:**
27
28
```java { .api }
29
public class GetSessionTokenRequest extends AmazonWebServiceRequest {
30
public GetSessionTokenRequest();
31
32
// Optional parameters
33
public Integer getDurationSeconds();
34
public void setDurationSeconds(Integer durationSeconds);
35
public GetSessionTokenRequest withDurationSeconds(Integer durationSeconds);
36
37
public String getSerialNumber();
38
public void setSerialNumber(String serialNumber);
39
public GetSessionTokenRequest withSerialNumber(String serialNumber);
40
41
public String getTokenCode();
42
public void setTokenCode(String tokenCode);
43
public GetSessionTokenRequest withTokenCode(String tokenCode);
44
}
45
46
public class GetSessionTokenResult {
47
public Credentials getCredentials();
48
public void setCredentials(Credentials credentials);
49
}
50
```
51
52
**Usage Examples:**
53
54
```java
55
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
56
import com.amazonaws.services.securitytoken.model.*;
57
58
// Basic session token request
59
GetSessionTokenResult result = stsClient.getSessionToken();
60
Credentials sessionCredentials = result.getCredentials();
61
62
System.out.println("Session Access Key: " + sessionCredentials.getAccessKeyId());
63
System.out.println("Session Secret Key: " + sessionCredentials.getSecretAccessKey());
64
System.out.println("Session Token: " + sessionCredentials.getSessionToken());
65
System.out.println("Expires: " + sessionCredentials.getExpiration());
66
67
// Session token with custom duration
68
GetSessionTokenRequest durationRequest = new GetSessionTokenRequest()
69
.withDurationSeconds(7200); // 2 hours
70
71
GetSessionTokenResult durationResult = stsClient.getSessionToken(durationRequest);
72
73
// Session token with MFA authentication
74
GetSessionTokenRequest mfaRequest = new GetSessionTokenRequest()
75
.withSerialNumber("arn:aws:iam::123456789012:mfa/username")
76
.withTokenCode("123456")
77
.withDurationSeconds(3600); // 1 hour
78
79
GetSessionTokenResult mfaResult = stsClient.getSessionToken(mfaRequest);
80
Credentials mfaCredentials = mfaResult.getCredentials();
81
```
82
83
## Session Token Use Cases
84
85
### MFA-Protected Operations
86
87
Session tokens are primarily used to enable MFA-protected API operations:
88
89
```java
90
/**
91
* Example service that uses session tokens for MFA-protected operations
92
*/
93
public class MFAProtectedService {
94
private final AWSSecurityTokenService stsClient;
95
96
public MFAProtectedService(AWSSecurityTokenService stsClient) {
97
this.stsClient = stsClient;
98
}
99
100
/**
101
* Get session token with MFA for accessing MFA-protected resources
102
*/
103
public Credentials getMFASessionToken(String mfaSerial, String mfaToken) {
104
GetSessionTokenRequest request = new GetSessionTokenRequest()
105
.withSerialNumber(mfaSerial)
106
.withTokenCode(mfaToken)
107
.withDurationSeconds(3600);
108
109
GetSessionTokenResult result = stsClient.getSessionToken(request);
110
return result.getCredentials();
111
}
112
113
/**
114
* Example of using MFA session credentials for sensitive operations
115
*/
116
public void performSensitiveOperation(String mfaSerial, String mfaToken) {
117
// Get MFA session token
118
Credentials mfaCredentials = getMFASessionToken(mfaSerial, mfaToken);
119
120
// Create new service clients with MFA credentials
121
AWSCredentials awsCredentials = new BasicSessionCredentials(
122
mfaCredentials.getAccessKeyId(),
123
mfaCredentials.getSecretAccessKey(),
124
mfaCredentials.getSessionToken()
125
);
126
127
// Now use these credentials for MFA-protected operations
128
// For example: IAM operations, sensitive S3 operations, etc.
129
}
130
}
131
```
132
133
### Temporary Credential Distribution
134
135
Session tokens can be used to provide temporary credentials to applications:
136
137
```java
138
/**
139
* Example application credential manager
140
*/
141
public class ApplicationCredentialManager {
142
private final AWSSecurityTokenService stsClient;
143
144
public ApplicationCredentialManager() {
145
this.stsClient = AWSSecurityTokenServiceClientBuilder.defaultClient();
146
}
147
148
/**
149
* Get temporary credentials for application use
150
*/
151
public Credentials getTemporaryCredentials(int durationSeconds) {
152
GetSessionTokenRequest request = new GetSessionTokenRequest()
153
.withDurationSeconds(durationSeconds);
154
155
GetSessionTokenResult result = stsClient.getSessionToken(request);
156
return result.getCredentials();
157
}
158
159
/**
160
* Refresh credentials before they expire
161
*/
162
public Credentials refreshCredentials(Credentials currentCredentials) {
163
// Check if credentials are close to expiration
164
Date expiration = currentCredentials.getExpiration();
165
Date now = new Date();
166
long timeToExpiration = expiration.getTime() - now.getTime();
167
168
// Refresh if less than 15 minutes remaining
169
if (timeToExpiration < 15 * 60 * 1000) {
170
return getTemporaryCredentials(3600); // 1 hour
171
}
172
173
return currentCredentials; // Still valid
174
}
175
}
176
```
177
178
## Session Duration and Limitations
179
180
### Duration Constraints
181
182
Session token duration depends on the calling credentials:
183
184
- **IAM User credentials**: 900 seconds (15 minutes) to 129,600 seconds (36 hours), default 43,200 seconds (12 hours)
185
- **Root user credentials**: 900 seconds (15 minutes) to 3,600 seconds (1 hour), default 3,600 seconds (1 hour)
186
187
```java
188
// Examples of different duration configurations
189
public class SessionDurationExamples {
190
191
public void demonstrateDurationLimits() {
192
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.defaultClient();
193
194
// Minimum duration (15 minutes)
195
GetSessionTokenRequest minRequest = new GetSessionTokenRequest()
196
.withDurationSeconds(900);
197
198
// Default duration (12 hours for IAM users)
199
GetSessionTokenRequest defaultRequest = new GetSessionTokenRequest();
200
201
// Maximum duration for IAM users (36 hours)
202
GetSessionTokenRequest maxRequest = new GetSessionTokenRequest()
203
.withDurationSeconds(129600);
204
205
// For root users, maximum is 1 hour
206
GetSessionTokenRequest rootMaxRequest = new GetSessionTokenRequest()
207
.withDurationSeconds(3600);
208
}
209
}
210
```
211
212
### Permission Characteristics
213
214
Session tokens have specific permission characteristics:
215
216
1. **Same permissions as calling user** - Session tokens inherit all permissions from the IAM user or root user that called GetSessionToken
217
2. **Cannot call IAM operations** unless MFA authentication is included in the request
218
3. **Can only call specific STS operations** - Only `AssumeRole` and `GetCallerIdentity` are allowed
219
4. **No session policies** - Unlike AssumeRole or GetFederationToken, session tokens cannot be restricted with session policies
220
221
```java
222
/**
223
* Example demonstrating session token permission characteristics
224
*/
225
public class SessionTokenPermissions {
226
227
public void demonstratePermissionLimitations() {
228
// Get session token without MFA
229
GetSessionTokenResult result = stsClient.getSessionToken();
230
Credentials sessionCredentials = result.getCredentials();
231
232
// Create new STS client with session credentials
233
AWSSecurityTokenService sessionStsClient = AWSSecurityTokenServiceClientBuilder.standard()
234
.withCredentials(new BasicSessionCredentials(
235
sessionCredentials.getAccessKeyId(),
236
sessionCredentials.getSecretAccessKey(),
237
sessionCredentials.getSessionToken()
238
))
239
.build();
240
241
try {
242
// This will work - GetCallerIdentity is allowed
243
GetCallerIdentityResult identity = sessionStsClient.getCallerIdentity(
244
new GetCallerIdentityRequest()
245
);
246
System.out.println("Caller ARN: " + identity.getArn());
247
248
// This will work - AssumeRole is allowed
249
AssumeRoleResult assumeResult = sessionStsClient.assumeRole(
250
new AssumeRoleRequest()
251
.withRoleArn("arn:aws:iam::123456789012:role/MyRole")
252
.withRoleSessionName("SessionFromSessionToken")
253
);
254
255
// These operations will NOT work without MFA:
256
// - GetFederationToken
257
// - GetSessionToken
258
// - Most IAM operations
259
260
} catch (Exception e) {
261
System.out.println("Operation failed: " + e.getMessage());
262
}
263
}
264
}
265
```
266
267
### Best Practices
268
269
```java
270
/**
271
* Best practices for session token usage
272
*/
273
public class SessionTokenBestPractices {
274
275
/**
276
* Recommended pattern for MFA-enabled applications
277
*/
278
public class MFAEnabledApplication {
279
private Credentials currentCredentials;
280
private Date credentialsExpiration;
281
282
public void authenticateWithMFA(String mfaSerial, String mfaToken) {
283
GetSessionTokenRequest request = new GetSessionTokenRequest()
284
.withSerialNumber(mfaSerial)
285
.withTokenCode(mfaToken)
286
.withDurationSeconds(3600); // 1 hour for MFA sessions
287
288
GetSessionTokenResult result = stsClient.getSessionToken(request);
289
this.currentCredentials = result.getCredentials();
290
this.credentialsExpiration = result.getCredentials().getExpiration();
291
}
292
293
public boolean needsRefresh() {
294
if (currentCredentials == null) return true;
295
296
Date now = new Date();
297
long timeToExpiration = credentialsExpiration.getTime() - now.getTime();
298
299
// Refresh if less than 5 minutes remaining
300
return timeToExpiration < 5 * 60 * 1000;
301
}
302
303
public AWSCredentials getCredentials() {
304
if (needsRefresh()) {
305
throw new IllegalStateException("Credentials need refresh");
306
}
307
308
return new BasicSessionCredentials(
309
currentCredentials.getAccessKeyId(),
310
currentCredentials.getSecretAccessKey(),
311
currentCredentials.getSessionToken()
312
);
313
}
314
}
315
316
/**
317
* Pattern for long-running applications
318
*/
319
public class LongRunningApplication {
320
private static final int DEFAULT_DURATION = 43200; // 12 hours
321
private static final int REFRESH_THRESHOLD = 1800; // 30 minutes
322
323
private Credentials credentials;
324
private ScheduledExecutorService scheduler;
325
326
public void start() {
327
refreshCredentials();
328
329
// Schedule automatic refresh
330
scheduler = Executors.newScheduledThreadPool(1);
331
scheduler.scheduleAtFixedRate(
332
this::refreshCredentialsIfNeeded,
333
REFRESH_THRESHOLD,
334
REFRESH_THRESHOLD,
335
TimeUnit.SECONDS
336
);
337
}
338
339
private void refreshCredentials() {
340
GetSessionTokenRequest request = new GetSessionTokenRequest()
341
.withDurationSeconds(DEFAULT_DURATION);
342
343
GetSessionTokenResult result = stsClient.getSessionToken(request);
344
this.credentials = result.getCredentials();
345
}
346
347
private void refreshCredentialsIfNeeded() {
348
Date now = new Date();
349
long timeToExpiration = credentials.getExpiration().getTime() - now.getTime();
350
351
if (timeToExpiration < REFRESH_THRESHOLD * 1000) {
352
refreshCredentials();
353
}
354
}
355
356
public void shutdown() {
357
if (scheduler != null) {
358
scheduler.shutdown();
359
}
360
}
361
}
362
}