package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
import java.util.List;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins(
"http://localhost:3000",
"https://myapp.com"
)
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Authorization", "X-Total-Count")
.allowCredentials(true)
.maxAge(3600);
}
// Alternative: Bean-based configuration for Spring Security integration
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList(
"http://localhost:3000",
"https://myapp.com"
));
configuration.setAllowedMethods(Arrays.asList(
"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"
));
configuration.setAllowedHeaders(List.of("*"));
configuration.setExposedHeaders(Arrays.asList(
"Authorization",
"X-Total-Count"
));
configuration.setAllowCredentials(true);
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", configuration);
return source;
}
}
package com.example.demo.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
@CrossOrigin(
origins = {"http://localhost:3000", "https://myapp.com"},
methods = {RequestMethod.GET, RequestMethod.POST},
allowedHeaders = "*",
exposedHeaders = {"X-Total-Count"},
allowCredentials = "true",
maxAge = 3600
)
public class UserController {
@GetMapping
public ResponseEntity<List<User>> getUsers() {
// Method inherits CORS configuration from class level
return ResponseEntity.ok(users);
}
// Override CORS for specific endpoint
@CrossOrigin(origins = "*")
@GetMapping("/public")
public ResponseEntity<String> publicEndpoint() {
return ResponseEntity.ok("Public data");
}
}
CORS (Cross-Origin Resource Sharing) controls which domains can access APIs. Browsers enforce same-origin policy by default. I configure allowed origins, methods, headers, and credentials. @CrossOrigin enables CORS per controller or method. Global configuration via WebMvcConfigurer applies to entire application. Preflight requests (OPTIONS) verify permissions before actual requests. Credentials require allowCredentials and specific origins—wildcards don't work. Exposed headers make custom headers accessible to JavaScript. Max age caches preflight responses. Proper CORS prevents security issues while enabling legitimate cross-domain communication. Production environments restrict allowed origins to known frontends. Development often allows all origins for convenience.
Related snips
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
createdAt: String!
GraphQL API with Spring Boot
package com.example.starter.config;
import com.example.starter.properties.CustomProperties;
import com.example.starter.service.CustomService;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
Custom Spring Boot starters
#!/usr/bin/env bash
set -euo pipefail
export VAULT_ADDR="https://vault.internal:8200"
export VAULT_TOKEN="${VAULT_TOKEN:?missing VAULT_TOKEN}"
Secrets management with environment isolation and Vault
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";
const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";
JWT access + refresh token rotation (conceptual)
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
Share this code
Here's the card — post it anywhere.