Accessing Spring Security Endpoints from Frontend or Third‐Party Clients - Nandu-Chopade/Spring-security-complete-guide GitHub Wiki
This guide explains how to securely access your Spring Security-protected API endpoints from frontend apps (React, Angular, etc.) or third-party clients (mobile, external services).
-
Spring Boot app with Spring Security already configured (refer to main guide).
-
Endpoints are protected — users must login to access them.
-
Cross-Origin Resource Sharing (CORS) and token-based authentication (JWT or Session) are required for external access.
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000") // frontend URL
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true);
}
};
}
http.formLogin().loginProcessingUrl("/api/auth/login")
.permitAll();
axios.post('http://localhost:8080/api/auth/login', {
username: '[email protected]',
password: 'password123'
}, {
withCredentials: true
}).then(res => console.log(res));
axios.get('http://localhost:8080/api/user/data', {
withCredentials: true
});
Use a custom login endpoint that issues JWT tokens.
axios.post('http://localhost:8080/api/auth/login', {
email: '[email protected]',
password: 'password123'
}).then(res => {
localStorage.setItem('token', res.data.token);
});
const token = localStorage.getItem('token');
axios.get('http://localhost:8080/api/user/data', {
headers: {
'Authorization': Bearer ${token}
}
});
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String header = request.getHeader("Authorization");
if (header != null && header.startsWith("Bearer ")) {
String token = header.substring(7);
// Validate and set authentication context
}
filterChain.doFilter(request, response);
}
}
-
Postman: Add
Authorization: Bearer <JWT>
in Headers. -
Browser: Use session-based or JWT in localStorage.
-
Always enable HTTPS in production.
-
Set proper CORS headers (
Access-Control-Allow-Origin
). -
Store JWT in Memory or HttpOnly Cookie for security.
-
Refresh JWT token using refresh-token endpoint.
Use Case | Recommended Auth Method |
---|---|
Browser / Web Form | Session Cookie |
Mobile App / SPA (React) | JWT Token |
External REST Client | JWT Token with CORS |
Let me know if you want the code for JWT implementation end-to-end or a React login page as a demo!