Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 362
iduniq Avatar asked Jan 09 '23 04:01

iduniq


1 Answers

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.

like image 54
Jigish Avatar answered Jan 15 '23 14:01

Jigish