Accessing Spring Security Endpoints from Frontend or Third‐Party Clients - Nandu-Chopade/Spring-security-complete-guide GitHub Wiki

🌐 Accessing Spring Security Endpoints from Frontend or Third-Party Clients

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).


📦 Project Prerequisites

  • 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.


🔑 Option 1: Session-Based Login (Good for Web Forms)

1. ✳️ Enable CORS

@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);
        }
    };
}

2. ✅ Use Spring Security Login

http.formLogin().loginProcessingUrl("/api/auth/login")
    .permitAll();

3. 🌐 Frontend Call Example (React using Axios)

axios.post('http://localhost:8080/api/auth/login', {
  username: '[email protected]',
  password: 'password123'
}, {
  withCredentials: true
}).then(res => console.log(res));

4. 🎯 Access Protected Endpoint

axios.get('http://localhost:8080/api/user/data', {
  withCredentials: true
});

🔒 Option 2: JWT Token-Based Login (Recommended for APIs)

1. 🔐 Generate JWT Token on Login

Use a custom login endpoint that issues JWT tokens.

2. 📥 Frontend Login

axios.post('http://localhost:8080/api/auth/login', {
  email: '[email protected]',
  password: 'password123'
}).then(res => {
  localStorage.setItem('token', res.data.token);
});

3. 🔄 Frontend Request to Secure Endpoint

const token = localStorage.getItem('token');

axios.get('http://localhost:8080/api/user/data', { headers: { 'Authorization': Bearer ${token} } });


🔁 Backend JWT Filter (Example Snippet)

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);
  }
}

🧪 Testing Tools

  • Postman: Add Authorization: Bearer <JWT> in Headers.

  • Browser: Use session-based or JWT in localStorage.


✅ Best Practices

  • 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.


📝 Summary

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!

⚠️ **GitHub.com Fallback** ⚠️