Popular Searches
Popular Course Categories
Popular Courses

Managing CORS, CSRF, and Unauthorized Access

Managing CORS, CSRF, and Unauthorized Access

Spring Security and Secure REST APIs

Managing CORS, CSRF, and Unauthorized Access in Java

Course: Advanced Java Training

Topic: Managing CORS, CSRF, and Unauthorized Access

Course Link: Advanced Java Training at JustAcademy

Demo Link: Register for a Course Demo

Website: Visit JustAcademy


1. Introduction to Web Application Security

Web application security is the practice of protecting applications, APIs, user accounts, and sensitive data from unauthorized access and malicious requests. Java applications built with Spring Boot and Spring Security commonly require protection against cross-origin access issues, cross-site request forgery, and unauthorized requests.

CORS, CSRF, and unauthorized access are related to security, but each addresses a different problem. CORS controls how browsers allow web pages from different origins to access resources. CSRF protection prevents attackers from tricking an authenticated browser into submitting unwanted requests. Authentication and authorization mechanisms establish who a user is and what that user can access.

Learning Objectives

  • Understand CORS and the browser's same-origin policy.
  • Configure CORS in Spring Boot applications.
  • Understand CSRF attacks and CSRF token validation.
  • Configure CSRF protection using Spring Security.
  • Distinguish authentication from authorization.
  • Handle unauthorized and forbidden responses correctly.
  • Apply security best practices to REST APIs and web applications.

2. Understanding CORS

2.1 What Is CORS?

CORS stands for Cross-Origin Resource Sharing. It is a browser-enforced mechanism that allows a server to specify which origins can access its resources through browser-based cross-origin requests.

An origin consists of a scheme, hostname, and port. If any of these components differs, the origins are different.

Example:

Frontend: http://localhost:3000
Backend:  http://localhost:8080

Although both applications run on localhost, their ports differ. Therefore, they have different origins. When the frontend requests data from the backend, the browser may require the backend to return appropriate CORS headers.

2.2 Why Is CORS Required?

  • Allows approved frontends to communicate with backend APIs.
  • Controls which origins browser-based JavaScript can access.
  • Supports applications hosted on separate domains or ports.
  • Allows servers to specify permitted HTTP methods and request headers.
  • Can permit credentialed requests when configured correctly.

Important: CORS is not an authentication mechanism or a replacement for API authorization. Non-browser clients are not generally restricted by browser CORS enforcement.

2.3 Understanding the Same-Origin Policy

The same-origin policy is a browser security rule that restricts scripts from freely reading resources from another origin. CORS provides a controlled way for servers to relax certain cross-origin restrictions.

Frontend Origin Backend Origin Same Origin?
http://localhost:3000 http://localhost:3000 Yes
http://localhost:3000 http://localhost:8080 No
https://example.com https://api.example.com No
http://example.com https://example.com No

3. How CORS Works

When a browser sends a cross-origin request, the server must provide the appropriate response headers for the browser to expose the response to frontend JavaScript.

3.1 Simple Requests

Some cross-origin requests can be sent without a preflight request. The browser checks the server's CORS response headers before allowing the requesting script to read the response.

3.2 Preflight Requests

For requests that do not qualify as simple requests, the browser generally sends an HTTP OPTIONS preflight request first. The preflight asks the server whether the intended origin, method, and headers are permitted.

OPTIONS /api/products HTTP/1.1
Origin: http://localhost:3000
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type, Authorization

The server may respond with headers such as:

Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization

If the preflight response does not permit the intended request, the browser blocks the cross-origin request from proceeding as requested.

3.3 Common CORS Headers

Header Purpose
Access-Control-Allow-Origin Specifies which origin may access the response.
Access-Control-Allow-Methods Lists permitted HTTP methods.
Access-Control-Allow-Headers Lists request headers that the browser may send.
Access-Control-Allow-Credentials Indicates whether credentialed cross-origin requests are allowed.
Access-Control-Expose-Headers Identifies response headers that frontend JavaScript may read.
Access-Control-Max-Age Controls how long a preflight result may be cached.
Origin Identifies the requesting page's origin.

4. Configuring CORS in Spring Boot

4.1 Configure CORS Using Spring MVC

Spring MVC allows developers to configure CORS globally or for individual controllers. The following example allows a specific frontend origin to call selected API methods.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("Content-Type", "Authorization")
                .allowCredentials(false)
                .maxAge(3600);
    }
}

Explanation:

  • addMapping("/api/**") applies the configuration to matching API paths.
  • allowedOrigins() specifies the approved frontend origin.
  • allowedMethods() defines the permitted HTTP methods.
  • allowedHeaders() restricts which request headers are allowed.
  • allowCredentials(false) indicates that cross-origin credentials are not enabled by this configuration.
  • maxAge(3600) allows a compatible preflight result to be cached for up to 3,600 seconds.

4.2 Configure CORS with Spring Security

When Spring Security is enabled, configure CORS as part of the security filter chain. This is particularly important because browser preflight requests must be handled before authentication requirements interfere with them.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity http) throws Exception {

        http
            .cors(Customizer.withDefaults())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/**").permitAll()
                .anyRequest().authenticated()
            );

        return http.build();
    }
}

This example enables Spring Security's CORS integration. A valid CORS configuration must also be available, such as a suitable CorsConfigurationSource bean or compatible MVC CORS configuration. The public endpoint is accessible without authentication, while other requests require authentication.

4.3 Configure CORS Using a CorsConfigurationSource Bean

import java.util.List;
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;

@Configuration
public class ApiCorsConfiguration {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowedOrigins(
            List.of("http://localhost:3000")
        );
        config.setAllowedMethods(
            List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")
        );
        config.setAllowedHeaders(
            List.of("Content-Type", "Authorization")
        );
        config.setAllowCredentials(false);
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source =
            new UrlBasedCorsConfigurationSource();

        source.registerCorsConfiguration("/api/**", config);
        return source;
    }
}

Best practice: Use explicit trusted origins in production. If credentialed requests are needed, enable them only for trusted origins and never combine credentialed CORS with a wildcard allowed origin.

5. Understanding CSRF

5.1 What Is CSRF?

CSRF stands for Cross-Site Request Forgery. It is an attack in which a malicious website tricks a user's browser into submitting an unwanted request to another website where the user is already authenticated.

Browsers may automatically attach cookies to requests. If an application relies on a session cookie to authenticate requests without verifying that the request was intentionally initiated by the application, an attacker may be able to trigger an action using the victim's authenticated session.

5.2 Example of a CSRF Attack

Suppose a user is logged in to a banking application. The application uses a session cookie to identify the user. The user then visits a malicious website that causes the browser to submit an unwanted transfer request to the banking application.

<form action="https://bank.example/transfer" method="POST">
  <input type="hidden" name="amount" value="5000">
  <input type="hidden" name="recipient" value="attacker">
</form>

This simplified example illustrates the risk; a real attack depends on the target application's request handling, cookie settings, and security controls. If the application accepts the request using only automatically attached authentication cookies, the action may succeed unless adequate defenses are present.

5.3 Effects of CSRF Attacks

  • Unauthorized changes to user profile information.
  • Unwanted financial or account transactions.
  • Changes to account passwords or email addresses.
  • Unauthorized creation or deletion of application resources.
  • Abuse of administrative actions performed through a logged-in browser.

6. CSRF Protection Techniques

6.1 CSRF Tokens

A CSRF token is an unpredictable value associated with a user's session or security context. The application requires the token to be included in a state-changing request and validates it before processing the action.

A common token-based flow is:

  1. The server establishes the user's session or security context.
  2. The application makes a CSRF token available through a protected mechanism.
  3. The frontend includes the token in an expected request field or header.
  4. The server validates the token when processing the request.
  5. The server rejects requests that fail CSRF validation.

CSRF tokens must be difficult to guess and handled according to the application's framework and session design. Merely placing a token in a cookie is not sufficient unless the application also validates the appropriate submitted value.

6.2 SameSite Cookies

The SameSite cookie attribute controls when a browser sends a cookie in cross-site contexts.

Setting General Behavior
Strict Restricts cookie sending in cross-site contexts more strongly.
Lax Allows cookies in certain cross-site top-level navigations while restricting many other cross-site requests.
None Allows cross-site cookie use when other browser requirements are satisfied; normally requires Secure.

SameSite cookies provide useful defense in depth, but they should not automatically be treated as a replacement for CSRF tokens in applications that need token-based protection.

6.3 Validate Request Methods

Use appropriate HTTP methods and avoid performing state-changing operations through GET requests. GET should be safe and should not create, update, or delete important application data.

6.4 Origin and Referer Validation

Where appropriate, servers can validate the Origin header and use the Referer header as an additional signal. These checks should complement, not casually replace, the application's primary CSRF defenses.

7. Configuring CSRF Protection in Spring Security

7.1 Default CSRF Protection

Spring Security enables CSRF protection by default for many standard servlet-based configurations. For applications that use session-based authentication, retaining CSRF protection is generally important.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity http) throws Exception {

        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/login", "/register").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(form -> form.permitAll());

        return http.build();
    }
}

Because CSRF protection is not disabled here, Spring Security applies its default CSRF behavior. State-changing requests must satisfy the framework's CSRF requirements. Login and registration pages being public does not mean every state-changing request to those endpoints is exempt from CSRF checks.

7.2 Sending a CSRF Token from a Frontend

In a server-rendered Spring application, a form can include the CSRF token exposed by Spring Security's request processing.

<form method="post" action="/profile/update">
  <input type="hidden"
         name="_csrf"
         value="TOKEN_RENDERED_BY_THE_SERVER">
  <input type="text" name="displayName">
  <button type="submit">Update Profile</button>
</form>

The placeholder must be replaced by the actual token generated and made available by the application. Do not use a fixed token value in a real application.

7.3 CSRF Protection for REST APIs

Whether CSRF protection is required depends on how the API authenticates requests, not merely on whether the application is called a REST API.

  • Session cookies: Keep CSRF protection enabled for state-changing requests because the browser may automatically attach the session cookie.
  • Bearer tokens supplied explicitly in an Authorization header: CSRF risk is generally lower when credentials are not automatically attached by the browser. The full authentication design must still be reviewed.
  • Cookie-based access or refresh tokens: Evaluate CSRF defenses carefully because the browser may send these cookies automatically.

Some APIs using stateless, non-cookie bearer authentication may disable CSRF protection for the relevant security chain. This should only be done after verifying that browser-managed credentials cannot silently authenticate cross-site requests.

7.4 Disabling CSRF Protection: Use Caution

// Example only for a security chain where CSRF
// protection is demonstrably unnecessary.
http.csrf(csrf -> csrf.disable());

Disabling CSRF globally without understanding the authentication mechanism can expose users to attacks. Prefer retaining the default protection for cookie-authenticated web applications and designing narrowly scoped security chains when an application has different authentication requirements.

8. Understanding Unauthorized Access

8.1 What Is Unauthorized Access?

Unauthorized access occurs when a user or client attempts to access a protected resource without the required authentication or permissions. The application must determine whether the request comes from an authenticated identity and whether that identity is allowed to perform the requested action.

8.2 Authentication vs. Authorization

Feature Authentication Authorization
Meaning Verifies identity. Determines permitted actions.
Question Who are you? What may you access?
Examples Login, session, token validation. Role checks, permissions, ownership checks.
Typical failure Missing or invalid credentials. Insufficient permissions.
Common HTTP status 401 Unauthorized. 403 Forbidden.

Although the HTTP status name is “Unauthorized,” a 401 response usually indicates that valid authentication credentials are missing or unacceptable. A 403 response generally means the server understood the request but refuses to authorize it.

8.3 Common Causes of Unauthorized Access

  • Missing or expired access tokens.
  • Invalid usernames, passwords, or authentication credentials.
  • Incorrect role or authority assignments.
  • Missing endpoint authorization rules.
  • Improperly validated JWT claims.
  • Broken object-level authorization, such as accessing another user's record.
  • Misconfigured security filters or overly permissive endpoints.

9. Handling Unauthorized and Forbidden Requests in Spring Security

9.1 Configure Endpoint Authorization

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class ApiSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity http) throws Exception {

        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .requestMatchers("/api/user/**").hasAnyRole("USER", "ADMIN")
                .anyRequest().authenticated()
            );

        return http.build();
    }
}

Explanation:

  • permitAll() allows access without authentication for matching endpoints.
  • hasRole("ADMIN") requires the corresponding role authority, conventionally ROLE_ADMIN.
  • hasAnyRole("USER", "ADMIN") allows either role.
  • authenticated() requires a valid authenticated identity.

Endpoint authorization should be combined with appropriate authentication configuration, such as form login, HTTP Basic for controlled environments, or bearer-token authentication for APIs. The exact configuration depends on the application.

9.2 Configure a Custom Authentication Entry Point

A custom authentication entry point can return a consistent JSON response when an API request requires authentication.

import java.io.IOException;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationEntryPoint
        implements AuthenticationEntryPoint {

    @Override
    public void commence(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException authException)
            throws IOException, ServletException {

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(
            "{\"error\":\"unauthorized\","
            + "\"message\":\"Authentication is required.\"}"
        );
    }
}

Register the entry point in the relevant security configuration:

http.exceptionHandling(exceptions ->
    exceptions.authenticationEntryPoint(customAuthenticationEntryPoint)
);

Inject the CustomAuthenticationEntryPoint into the configuration class before using this example. For a production API, use a consistent error schema and avoid returning internal exception details.

9.3 Handle Access Denied Responses

An access-denied handler is useful when an authenticated user lacks permission to access a resource.

import java.io.IOException;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

@Component
public class CustomAccessDeniedHandler
        implements AccessDeniedHandler {

    @Override
    public void handle(
            HttpServletRequest request,
            HttpServletResponse response,
            AccessDeniedException exception)
            throws IOException, ServletException {

        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(
            "{\"error\":\"forbidden\","
            + "\"message\":\"You do not have permission to access this resource.\"}"
        );
    }
}

Register the handler with:

http.exceptionHandling(exceptions ->
    exceptions.accessDeniedHandler(customAccessDeniedHandler)
);

Inject the handler into the security configuration. For cookie-authenticated applications, a CSRF validation failure may also produce an access-denied response, so diagnostics should distinguish CSRF failures from missing roles or permissions.

10. Using Method-Level Security

Method-level security allows developers to protect business operations in addition to URL endpoints. This is valuable when several controllers call the same service method.

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

@Service
public class ReportService {

    @PreAuthorize("hasRole('ADMIN')")
    public String generateSensitiveReport() {
        return "Sensitive report generated";
    }
}

Enable method security on a configuration class:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;

@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig {
}

The annotation restricts the method to users with the required role. In real applications, also check record ownership and resource-level permissions where necessary. A user having a general role does not automatically mean they may access every record.

11. CORS vs. CSRF vs. Unauthorized Access

Aspect CORS CSRF Unauthorized Access
Main concern Browser cross-origin access. Forged authenticated requests. Identity and permissions.
Primary defense Explicit origin and request rules. CSRF tokens and complementary defenses. Authentication and authorization.
Typical issue Browser reports a CORS error. State-changing request fails token validation or succeeds without adequate protection. Request receives 401 or 403.
Does it replace the others? No. No. No.

12. Practical Example: Secure an Employee Management API

Consider an employee management application with a frontend hosted at http://localhost:3000 and a Spring Boot backend at http://localhost:8080.

Step 1: Define Public and Protected Endpoints

GET  /api/public/info
GET  /api/employees
POST /api/employees
GET  /api/admin/reports

Step 2: Configure Cross-Origin Access

Allow only the intended frontend origin and the HTTP methods required by the application. Avoid broad wildcard rules in production.

Step 3: Protect the Endpoints

Require authentication for employee operations and an administrator role for sensitive reports.

Step 4: Decide on CSRF Protection

If the application uses session cookies, retain CSRF protection and ensure state-changing requests provide valid tokens. If it uses explicitly supplied bearer tokens, assess the complete token-storage and browser-authentication design before deciding whether CSRF protection is necessary.

Step 5: Handle Security Failures

  • Return 401 when valid authentication is required but absent or invalid.
  • Return 403 when the authenticated user lacks the necessary permissions.
  • Handle CSRF validation failures clearly and securely.
  • Log security events without exposing passwords, tokens, or sensitive personal data.

Step 6: Test the Application

  • Send a request from the approved frontend origin.
  • Test a request from an unapproved origin in a browser.
  • Test OPTIONS preflight behavior for non-simple requests.
  • Test protected endpoints without authentication.
  • Test administrator endpoints using a regular user account.
  • Test state-changing cookie-authenticated requests without a valid CSRF token.

13. Common Errors and Troubleshooting

Problem Possible Cause Solution
CORS error in browser Origin or requested method is not allowed. Review server CORS configuration and response headers.
OPTIONS request returns 401 Preflight request is intercepted by authentication rules. Configure Spring Security CORS integration and ensure preflight requests are processed correctly.
Credentialed request fails Credentials are not allowed or origin configuration is invalid. Configure trusted origins and credential settings consistently.
403 on form submission CSRF token is missing or invalid, or permissions are insufficient. Inspect the security logs and identify the actual rejection reason.
401 on protected API Authentication is missing, expired, or invalid. Verify login/session state or bearer-token validation.
Regular user cannot access admin API User lacks the required role. Verify role mapping and authorization rules.
CSRF protection breaks frontend requests Frontend does not obtain or submit the expected token. Configure the framework's CSRF token delivery and submission mechanism.
API exposes another user's data Resource ownership checks are missing. Validate access to each requested resource on the server.

14. Security Best Practices

  • Use HTTPS for production applications.
  • Allow only trusted origins and required HTTP methods.
  • Never rely on CORS as the sole access-control mechanism.
  • Retain CSRF protection for applications authenticated through browser-managed cookies unless a carefully assessed design makes it unnecessary.
  • Use strong password storage and established authentication mechanisms.
  • Validate JWT signatures, expiry, issuer, and audience where applicable.
  • Apply the principle of least privilege to roles and permissions.
  • Validate resource ownership for user-specific records.
  • Keep dependencies and Spring Security versions up to date.
  • Do not expose stack traces, secrets, session identifiers, or tokens in error responses and logs.
  • Test positive and negative authorization cases.
  • Review security settings separately for browser sessions, REST APIs, and service-to-service communication.

15. Practical Exercises

  1. Create a Spring Boot REST API with public and protected endpoints.
  2. Configure CORS to permit one frontend origin and reject unapproved browser origins.
  3. Test preflight requests for PUT and DELETE methods.
  4. Enable CSRF protection in a session-based application and test requests with and without a valid token.
  5. Configure role-based access for USER and ADMIN roles.
  6. Implement JSON responses for authentication failures and access-denied errors.
  7. Write tests for missing authentication, insufficient permissions, and resource ownership.

16. Interview Questions and Answers

Q1. What is CORS?

Answer: CORS is a browser-enforced mechanism through which servers specify which origins may access responses to cross-origin requests.

Q2. What is a CORS preflight request?

Answer: It is an OPTIONS request sent by the browser before certain cross-origin requests to check whether the intended origin, method, and headers are allowed.

Q3. What is CSRF?

Answer: CSRF is an attack that tricks an authenticated user's browser into submitting an unwanted request to a target application.

Q4. How does a CSRF token help?

Answer: It provides an additional value that the server validates before accepting a state-changing request, helping verify that the request was initiated through an expected application flow.

Q5. Should CSRF protection always be disabled for REST APIs?

Answer: No. The decision depends on how the API authenticates requests. Cookie-authenticated APIs may remain vulnerable to CSRF, while APIs using explicitly supplied bearer tokens may have lower CSRF exposure.

Q6. What is the difference between HTTP 401 and 403?

Answer: HTTP 401 indicates that valid authentication is required or has failed. HTTP 403 indicates that the server refuses access, commonly because the authenticated user lacks permission.

Q7. Does CORS protect an API from unauthorized clients?

Answer: No. CORS primarily governs browser access to cross-origin responses. APIs still require authentication, authorization, input validation, and other security controls.

Q8. Why can a valid user receive a 403 response?

Answer: The user may lack the required role or resource permission, or the request may fail CSRF validation.

Q9. How can Spring Security restrict admin endpoints?

Answer: Use authorization rules such as hasRole("ADMIN") or method-level annotations such as @PreAuthorize("hasRole('ADMIN')").

Q10. What is the principle of least privilege?

Answer: It means giving users and services only the permissions needed to perform their assigned tasks.

17. Quick Revision Checklist

  • Understand the same-origin policy and CORS response headers.
  • Know when and why browsers send OPTIONS preflight requests.
  • Configure CORS for trusted frontend origins.
  • Understand CSRF risks in cookie-authenticated applications.
  • Retain suitable CSRF token validation for state-changing requests.
  • Distinguish authentication from authorization.
  • Handle 401 and 403 responses appropriately.
  • Apply role-based and resource-level authorization.
  • Test security behavior in browsers and automated tests.
  • Use HTTPS and follow least-privilege principles.

18. Conclusion

Managing CORS, CSRF, and unauthorized access is an essential part of building secure Java web applications. CORS provides controlled browser-based cross-origin access, CSRF protection reduces the risk of forged authenticated requests, and authentication and authorization ensure that users can access only the resources and operations permitted to them.

By combining Spring Security configuration, CSRF token validation where appropriate, explicit CORS rules, role-based authorization, secure error handling, and thorough testing, developers can build more reliable Spring Boot applications and REST APIs.


Learn More with JustAcademy

Explore the Advanced Java Training Course to continue learning Java application development and security concepts.

Interested in learning more? Register for a Course Demo to explore the training options.

Visit the JustAcademy website for more courses and learning resources.

Previous Next
whatsapp