Nana_kums
Nana_kums

Reputation: 33

Springboot REST - Expose same service as secured & non-secured

I want to enable basic authentication for my Spring https REST services(currently unsecured) in springboot application. Multiple clients are consuming these services, while some are ok to move to secured one, some still want to consume the unsecured version for few more months. How can I expose same service as both secured & unsecured in same spring boot application?

Though I had done this for Apache cxf REST services by hosting same service in different ports & securing only one port, don't know how to accomplish this in springboot.

Upvotes: 2

Views: 374

Answers (1)

Romil Patel
Romil Patel

Reputation: 13807

Create RequestMapping with two endPoints as below. Clients who want to use Basic Authentication will be served using /secure/** (can't be accessed without Authentication ) and others who are going to migrate to secure after a few months will be served using /unsecure/** (anyone can access). You can use class level RequestMapping to avoid change in every endPoint at method level

@GetMapping(value= {"/secure/users","/unsecure/users"})
    public ResponseEntity<List<User>> findAllUsers()
    {   
        ...
    }

Now Configure the Security as below. for that, you need Client Roles stored in DB

@Override
    protected void configure(HttpSecurity http) throws Exception{

         http
         .csrf().disable()
         .authorizeRequests()
         .antMatchers("/unsecure/**").permitAll()
         .antMatchers("/secure/**").hasRole("CLIENT_SECURE") 
         .anyRequest().authenticated();

    }

Working Git Example

Secure endPoint: GET http://localhost:8088/secure/users Status 403 enter image description here

UnSecure endPoint: GET: http://localhost:8088/unsecure/users Status 200 enter image description here

Upvotes: 2

Related Questions