iduniq
iduniq

Reputation: 61

Spring Security and() method

In spring framework security, there is an example:

http
    .authorizeRequests()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .loginPage("/login") 1
        .permitAll();  

Anyone who knows when is and() be used? It is defined at ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry, not easy to read springs documentation, seems designed to confuse.

Upvotes: 6

Views: 3958

Answers (3)

Douglas Fung
Douglas Fung

Reputation: 11

I interpret the question as why there is a need to add "and()" for some methods and not for others.

For this, my answer is it depends on the return type of the previous method.

No need to add "and()" when return type is HttpSecurity
E.g crsf().disable(): return type HttpSecurity
(I don’t understand why the return type is HttpSecurity, maybe it call the disable function and hence nothing returned?)

Add "and()" for other return types
E.g cors(): return type CorsConfigurer
formLogin(): return type FormLoginConfigurer

Upvotes: 1

Ram Chhabra
Ram Chhabra

Reputation: 441

Basically and() method is used to concatenate multiple configurer of Spring Security You can refer attached image to understand more clearlyusage of and() method

Upvotes: 0

Jigish
Jigish

Reputation: 1784

Think of and() as a way to chain methods together. You typically use an and() method after you're done configuring options on that particular Configurer. So for example,

http
    .someConfigurer
        .<some feature of configurer>()
        .<some feature of configurer>()
        .and()
    .someOtherConfigurer
        .<some feature of someOtherConfigurer>()
        ...
        .and()
     ...

You'll notice that the first level of calls on the http object are Configurers

.formLogin() --> FormLoginConfigurer
.httpBasic() --> HttpBasicConfigurer()
.sessionManagement() --> SessionManagementConfigurer

The next level after the Configurer are properties of that particular configurer that you want to tweak. For e.g.

formLogin()
    .loginPage("/login")
    .permitAll()
    .and()

The and() at the end of this returns a builder (HttpSecurity in our case). And hence we can chain other configurers using the and() method.

The method itself comes from SecurityConfigurerAdapter class. The and() method in ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry in turn calls the above method.

Upvotes: 11

Related Questions