Last active
April 2, 2024 05:41
-
-
Save Suvink/788eecd62f93ff481c655bd6c8d8ac83 to your computer and use it in GitHub Desktop.
Spring Authorization Sample Thread Local Context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MetadataFilter extends OncePerRequestFilter { | |
@Override | |
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) | |
throws ServletException, IOException { | |
try { | |
String tenantId = request.getHeader('X-Tenant-Id'); | |
TenantContextHolder.getContext().setTenantId(tenantId); | |
filterChain.doFilter(request, response); | |
} catch (Exception e) { | |
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); | |
} finally { | |
MetadataContextHolder.clearContext(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Getter | |
@Setter | |
public class TenantContext { | |
private String tenantId = ""; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TenantContextHolder { | |
private static final ThreadLocal<TenantContext> TENANT_CONTEXT = new ThreadLocal<>(); | |
public static TenantContext getContext() { | |
TenantContext context = TENANT_CONTEXT.get(); | |
if (context == null) { | |
context = createEmptyContext(); | |
TENANT_CONTEXT.set(context); | |
} | |
return METADATA_CONTEXT.get(); | |
} | |
public static void setContext(TenantContext context) { | |
METADATA_CONTEXT.set(context); | |
} | |
private static TenantContext createEmptyContext() { | |
return new TenantContext(); | |
} | |
public static void clearContext() { | |
TENANT_CONTEXT.remove(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment