Spring Security HttpSecurity config

落花浮王杯 提交于 2020-01-24 17:06:05

问题


I try to understand how the RequestMatcher, AntMatcher and so on are working. I read some posts and understand the basics. Actually I have this simple basic config:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.requestMatchers() //1
        .antMatchers("/login", "/oauth/authorize") //2
        .and() //3
        .authorizeRequests() //4
        .anyRequest() //5
        .authenticated() //6;

I really dont understand the points 1,2 and 3. From my understanding this means requests of /login and /oauth/authorize are mapped and should be authorized requests. All other requests needs a authenticatoin.

Means for an endpoint /user/me I have to be authenticated because its ruled by point 5 and 6? The call to this endpoint is working for me.

In my ohter config I try a different approach:

@Override
protected void configure(HttpSecurity http) throws Exception { // @formatter:off
      http
       .authorizeRequests() //1
        .antMatchers("/login", "/oauth/authorize", "/img/**").permitAll() //2
        .anyRequest() //3
        .authenticated() //4

From my point of view, this should be the same logic than the first config. But actually the endpoint /user/me is not accessable any more.

I would really appreciated for a clarification


Update 1:

This is my config now:

@Override
protected void configure(HttpSecurity http) throws Exception { // @formatter:off
    http
        .requestMatchers()
           .antMatchers("/", "/login", "/oauth/authorize", 
               "/main", "/logout-success", "/single-logout",
               "/password_forgotten", "/enter_new_password", "/img/**",
               "/logout", "/access_denied")
            .and().authorizeRequests()
                .antMatchers("/img/**", "/logout-success", "/password_forgotten",
                    "/enter_new_password", "/access_denied").permitAll()
            .requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()
            .and()
            .authorizeRequests()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .defaultSuccessUrl("/main")
            .permitAll()
            .and()
            .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/logout-success")
            .deleteCookies("JSESSIONID")
            .invalidateHttpSession(true)
            .and()
            .exceptionHandling()
            .accessDeniedPage("/access_denied")
            .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
            .and().csrf().disable();

and if I enter URL \user\me as a not authenticated user I get a 401 and this message:

<oauth>
<error_description>
Vollständige Authentifikation wird benötigt um auf diese Resource zuzugreifen
</error_description>
<error>unauthorized</error>
</oauth>

Which is ok, but means any ohter SecurityFilterChain takes place for this URL, right?


回答1:


requestMatchers() configures if an URL will be processed by that SecurityFilterChain. So if an URL does not match it , the whole SecurityFilterChain will be skipped which means Spring Security will not handle this URL after that. If you do not configure it , the default is to match all URLs.

The authorizeRequests() configures the authorisation stuff for an URL such as things like if it requires to be authenticated or if only certain roles can access it etc. It only has effect for those URLs that are processed by that SecurityFilterChain (i.e. Those URLs that are matched by requestMatchers())

So , back to your 1st example:

  http.requestMatchers() //1
        .antMatchers("/login", "/oauth/authorize") //2
        .and() //3
        .authorizeRequests() //4
        .anyRequest() //5
        .authenticated() //6;

It means this SecurityFilterChain will only has effect on /login and /oauth/authorize. Both URLs are required to be authenticated. All other URLs will not handled by this SecurityFilterChain. So whether /user/me is required to be authenticated or not is nothing to do with Spring Security.

http
       .authorizeRequests() //1
        .antMatchers("/login", "/oauth/authorize", "/img/**").permitAll() //2
        .anyRequest() //3
        .authenticated() //4

It means all URLs will be handled by this SecurityFilterChain (Default value of requestMatchers()). /login , /oauth/authorize and /img/** does not need any authorisation. Other URLs are required to be authenticated.




回答2:


Your first configuration
.requestMtchers() //1

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.requestMatchers() //1
        .antMatchers("/login", "/oauth/authorize") //2
        .and() //3
        .authorizeRequests() //4
        .anyRequest() //5
        .authenticated() //6;

Let me explain your .authorizeRequests() //4

http.authorizeRequests() It's a wild card(/**)(just like filter allows every request)
HttpSecurity configuration will consider only requests with these pattern here you can say

http.authorizeRequests()
//is nothing but equals to
http.antMatcher("/**").authorizeRequests();
//and also equals to
http.requestMatchers()
            .antMatchers("/**")
            .and()
            .authorizeRequests()

if you configure like below

http.antMatcher("/api/**").authorizeRequests();

Rest of the configuration(.hasRole(), .hasAnyRole, .authenticated() or .authenticated()) will only get consulted if incoming request uri matches the configured antmatcher(/api/**)

Consider you have multiple URL's(different pattern) needs to be configured then you can't use simply one antMatcher. You need multiple then you should use requestMatcher as below

http.requestMatchers()
            .antMatchers("/api/**", "employee/**", "/customer/**")
            .and()
            .authorizeRequests()

.antMatchers() //2
Used for configuring RequestMatcherConfigurer return type of .requestMatchers()
or also
Used for configuring ExpressionInterceptUrlRegistry return type of .authorizeRequests()

.and() //3

Return the HttpSecurity for further customizations

.anyRequest() //5

The object that is chained after creating the RequestMatcher

All request matches configured request matcher pattern

.authenticated() //6
Below configuration is self explainatory

.antMatchers("/app/admin/**").hasRole("ADMIN")
//or
.antMatchers("/app/admin/**").hasAnyRole("ADMIN", "USER")
//or
.antMatchers("/app/admin/**").authenticated()
//or
.antMatchers("/app/admin/**").permitAll()

This is rough idea about antMatchers, authorizeRequests, and authenticated. You can refer my answer in this link for sequence of execution in spring security



来源:https://stackoverflow.com/questions/58753001/spring-security-httpsecurity-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!