Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring REST Security : Enable Basic Authentication only on a specific endpoint

I have configured Spring Security for my REST API (with HeaderHttpSessionStrategy).

My 'WebSecurityConfigurerAdapter' implementation looks as below.

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

        http

            .csrf().disable()

            .authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/**").permitAll()

                .and()
            .requestCache()
                .requestCache(new NullRequestCache())
                .and()

            .httpBasic()
            ;

    }

Now, how can I configure 'HttpSecurity' object so that the basic authentication is only possible with a specific endpoint.

For example:

/user/login : Basic Authentication should only be possible on this end point.After sucessfull authentication x-auth-token header is returned.

/user/create : Client should not be able to authenticate on this endpoint.Should only return 401.Can only be accessed using the 'x-auth-token' created using /user/login endpoint.

like image 209
Ashika Umanga Umagiliya Avatar asked Nov 11 '16 00:11

Ashika Umanga Umagiliya


People also ask

How do you restrict the endpoint of a spring boot?

Run the app using: ./gradlew bootRun . Navigate to the home endpoint, which is open: http://localhost:8080 . And the restricted endpoint, which requires authentication: http://localhost:8080/restricted . When Spring's login form appears, don't forget you can use the default credentials.


2 Answers

You can define multiple WebSecurityConfigurerAdapters. One of higher priority which has a request matcher to restrict applicability to /user/login like: http.requestMatcher(new AntPathRequestMatcher("/user/login")), and another one as a catch-all for the rest. You can omit the requestMatcher to make the http definition unrestricted.

like image 105
sofiaguyang Avatar answered Sep 18 '22 14:09

sofiaguyang


You must always define restrictions from specific to generic. In your case it should be specific URL checks to generic security checks.

  1. You should configure and permit signin / signup URLs.
  2. You should avoid pattern /** to permit all. instead configure static resource URL separately.
  3. You should finally apply more generic restriction like you mentioned on URL, /user/** to be authenticated and having some roles.

      @Override
      protected void configure(HttpSecurity http) throws Exception {
    
    http
    .csrf().disable()
    .authorizeRequests()
    .antMatchers("/user/login, /user/signup, /logout").permitAll()
    .antMatchers("/user/**").hasRole("ADMIN")
    .and()
    .requestCache()
    .requestCache(new NullRequestCache())
    .and()
    
        .httpBasic();
    

    }

like image 40
ScanQR Avatar answered Sep 18 '22 14:09

ScanQR