Search code examples
javaspring-bootbasic-authentication

spring BOOT: basic auth only for some urls and db auth for others in spring BOOT


Hi i am stuck on this issue for really long time now. i want some rest apis to have basic authentication and some rest apis having db authententication.

I tried adding separate WebSecurityConfigurerAdapter, but its not working. How can this be achieved in spring Boot?


Solution

  • The security Filter was rejecting the Basic auth Urls..so i made those URLs open Url in Spring security.(no auth Urls)

    So that when these Urls will come into Basic Auth Filter they will be authenticated.

    So i created a FilterRegistrationBean for Basic Auth with Lowest_Precedence.

    @Bean
      public FilterRegistrationBean registerBasicAuthFilter(BasicAuthFilter filter) {
          FilterRegistrationBean reg = new FilterRegistrationBean(filter);
          reg.setOrder(Ordered.LOWEST_PRECEDENCE);
          return reg;
      }
    

    If you want your own Filter to go after Spring Security's you can create your own registration for Spring Security's filter and specify the order.

    Sharing the Basic Auth Java class - Spring BOOT

    • This includes authentication of user from db.(helps to rotate the user creds on the fly).

    https://gist.github.com/kad9/b595910e1a659f91d199b910f699a2d2

    This made my work simple to maintain.