DEV Community

Manikanta Yarramsetti
Manikanta Yarramsetti

Posted on

Understanding Okta Tokens

What are Okta Tokens?

Okta tokens are digital credentials that prove your identity when accessing applications. Think of them like a secure badge that shows who you are and what you can access, without needing to show your password every time.

Three Types of Tokens

Access Token

Used to access APIs and protected resources. Valid for 1 hour by default.

ID Token

Contains your basic profile information like name and email.

Refresh Token

Used to get new access tokens without logging in again. Valid for 90 days.

Token Structure

Tokens use JWT format with three parts:

header.payload.signature
Enter fullscreen mode Exit fullscreen mode

Example:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.Signature
Enter fullscreen mode Exit fullscreen mode

Quick Setup in Spring Boot

Add dependency:

<dependency>
    <groupId>com.okta.spring</groupId>
    <artifactId>okta-spring-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Configure in application.properties:

okta.oauth2.issuer=https://your-domain.okta.com/oauth2/default
okta.oauth2.client-id=your-client-id
okta.oauth2.client-secret=your-client-secret
Enter fullscreen mode Exit fullscreen mode

Secure Your APIs

Basic security configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2.jwt());
        return http.build();
    }
}
Enter fullscreen mode Exit fullscreen mode

Get User Information from Token

@RestController
@RequestMapping("/api")
public class UserController {

    @GetMapping("/user")
    public Map<String, Object> getUserInfo(@AuthenticationPrincipal Jwt jwt) {
        Map<String, Object> info = new HashMap<>();
        info.put("userId", jwt.getSubject());
        info.put("email", jwt.getClaim("email"));
        info.put("name", jwt.getClaim("name"));
        return info;
    }
}
Enter fullscreen mode Exit fullscreen mode

Protect Endpoints by Role

@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @GetMapping("/dashboard")
    @PreAuthorize("hasAuthority('SCOPE_admin')")
    public String adminDashboard() {
        return "Admin Dashboard Data";
    }
}
Enter fullscreen mode Exit fullscreen mode

Common Token Claims

Claim What It Contains
sub User ID
email User email
name User full name
exp When token expires
iss Who issued the token
groups User roles

Token Lifetimes

Token Type How Long It Lasts
Access Token 1 hour
ID Token 1 hour
Refresh Token 90 days

Check Token Expiration

@GetMapping("/token-status")
public String checkToken(@AuthenticationPrincipal Jwt jwt) {
    long secondsLeft = Duration.between(
        Instant.now(), 
        jwt.getExpiresAt()
    ).getSeconds();

    return "Token expires in " + secondsLeft + " seconds";
}
Enter fullscreen mode Exit fullscreen mode

Handle Token Errors

@ControllerAdvice
public class TokenErrorHandler {

    @ExceptionHandler(JwtException.class)
    public ResponseEntity<String> handleInvalidToken(JwtException ex) {
        return ResponseEntity
            .status(HttpStatus.UNAUTHORIZED)
            .body("Invalid or expired token");
    }
}
Enter fullscreen mode Exit fullscreen mode

Best Practices

Always use HTTPS. Never store tokens in localStorage, use httpOnly cookies instead. Validate tokens on every API request. Refresh tokens before they expire. Use appropriate scopes for different user roles. Log token errors for security monitoring.

Quick Summary

Okta tokens are secure credentials that authenticate users. Access tokens let you call APIs. ID tokens give you user info. Refresh tokens get new access tokens. Spring Boot makes it easy to use Okta tokens with just a few lines of configuration.

When Token Expires

When an access token expires, use the refresh token to get a new one automatically. This keeps users logged in without asking for their password again.

Testing Your Setup

Test protected endpoint:

curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     http://localhost:8080/api/user
Enter fullscreen mode Exit fullscreen mode

Top comments (0)