programing

Spring Security - HttpSecurity를 사용한 특정 URL 및 HTTP-Method에 대한 인증 요청

lovejava 2023. 7. 28. 21:42

Spring Security - HttpSecurity를 사용한 특정 URL 및 HTTP-Method에 대한 인증 요청

다음과 같은 정보를 제공할 방법이 있습니까?POST"http-request" "http-request"를 사용하여 org.springframework.security.config.annotation.web.builders.HttpSecurity?

는 중용사를 합니다.HttpSecurity다음과 같이:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
            .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint)
        .and()
            .rememberMe()
            .rememberMeServices(rememberMeServices)
            .key(env.getProperty("jhipster.security.rememberme.key"))
        .and()
            .formLogin()
            .loginProcessingUrl("/api/authentication")
            .successHandler(ajaxAuthenticationSuccessHandler)
            .failureHandler(ajaxAuthenticationFailureHandler)
            .usernameParameter("j_username")
            .passwordParameter("j_password")
            .permitAll()
        .and()
            .logout()
            .logoutUrl("/api/logout")
            .logoutSuccessHandler(ajaxLogoutSuccessHandler)
            .deleteCookies("JSESSIONID")
            .permitAll()
        .and()
            .headers()
            .frameOptions()
            .disable()
            .authorizeRequests()
                .antMatchers("/api/register").permitAll()
                .antMatchers("/api/activate").permitAll()
                .antMatchers("/api/authenticate").permitAll()
                .antMatchers("/api/logs/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/api/subscriptions").permitAll()
                .antMatchers("/api/**").authenticated();
}

다음만 허용합니다.POST"/api/subscription".

여기를 보세요. https://github.com/spring-projects/spring-data-examples/tree/master/rest/security 은 다음과 같은 것들을 가지고 있습니다.

http
  .httpBasic().and()
  .authorizeRequests()
    .antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN")
    .antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN")
    .antMatchers(HttpMethod.PATCH, "/employees/**").hasRole("ADMIN");

TL;DR

Spring 6.0 릴리스 구성 방법 이후 및 는 API에서 제거되었습니다.

여러 맛의 그고여러가맛의지리▁of▁and▁flavors.requestMatchers()메소드가 대체품으로 제공되었습니다.

gh-11939 - Java Configuration에서 사용되지 않는 antMatchers, mvcMatchers, regexMatchers 도우미 메서드를 제거합니다.대신 사용 requestMatchers또는HttpSecurity#securityMatchers.

된 메서드 또한과부하방법된방▁also법▁an,된ed▁method.authorizeHttpRequests() 사용되지authorizeRequests() 않는 제품을 대체하기 위해 도입되었습니다.

프로젝트에서 이전 버전의 Spring을 사용하고 있고 Spring 6으로 곧 업데이트하지 않을 것이라고 해도,antMatchers() 응용 프로그램에 대한 요청을 보호하기 위해 선택할 수 있는 최상의 도구가 아닙니다.

를 하여 보안 규칙을 antMatchers()당신은 매우 조심할 필요가 있습니다. 왜냐하면 당신이 안전하다면 경로라고 합시다."/foo"이러한 제한은 이 경로의 다른 별칭에는 적용되지 않습니다."/foo/","/foo.thml"따라서 보안 규칙을 잘못 구성하고 취약성이 발생하기 쉽습니다(예: 관리자만 액세스할있어야 하는 경로를 인증된 사용자가 사용할 수 있게 됩니다. 위의 답변이에 대한 언급이 없다는 것은 놀라운 일입니다.).

스프링 6.0 -

문서에 따르면, 특정 URL에 대한 액세스를 제한하는 권장 방법은 다음과 같습니다.5.8를 사용하는 것으로, 이전 버전뿐만 아니라 두 가지 맛이 있습니다.

  • 요청 구성을 담당하는 개체(정확하게는 이 긴 이름 클래스의 인스턴스)를 반환하는 매개 변수 없는 버전입니다.그래서 우리는 체인을 할 수 있습니다.requestMatchers()직접 전화를 걸 수 있습니다.

  • 그리고 두 번째 사람은 사건의 예를 기대하고 있습니다.Customizer람다 식을 사용하여 향상된 DSL(도메인별 언어)을 적용할 수 있는 인터페이스입니다. 게시물을 참조하십시오. 오래된 매칭 방법을 사용하지만 구성 옵션을 시각적으로 그룹화하여 구성을 보다 직관적으로 읽을 수 있도록 하며 방법을 사용할 필요가 없는 람다 DSL의 핵심 아이디어를 잘 설명합니다.and().

의 어떤 버전.authorizeHttpRequests()사용하는 것은 스타일적인 선택입니다(둘 다 유효하며 에서 지원됨)6.0).

지금이다requestMatchers()일치 할 수 있는 네 가지 을 가지고 있습니다. 바로 다음과 같습니다.

  • requestMatchers( String ... ) 의 다양한 변수를 예상합니다.String 이전의 SpringMVC합니다.mvcMatchers() 그 래서그패턴은그은./foo는 " 과같이해경모기든별존일다칭치니합과로의다당"와 같은 해당 합니다."/foo","/foo/","/foo.html" 모든 의 의다모든버전requestMatchers()동일한 일치 동작을 가지면 구성이 잘못될 가능성이 사라집니다. 이는 아킬레스건입니다.antMatchers()해당 제한 사항(hasRole(),access()등)는 해당 HttpMethod에 관계없이 모든 일치 요청에 적용됩니다.

예:

.requestMatchers("/foo/*").hasRole("ADMIN") // only authenticated user with role ADMIN can access path /foo/something
.requestMatchers("/bar/*", "/baz/*").hasRole("ADMIN") // only authenticated requests to paths /foo/something and /baz/something  are allowed
  • requestMatchers( HttpMethod ) 을 기대합니다.HttpMethod(해의제한서로당으론()hasRole(),access()의 요청에 됩니다.SecurityFilterChain HttpMethod 지한 경우 정를.null모든 요청이 일치하는 인수로 제공됩니다.

예:

.requestMatchers(HttpMethod.POST, "/bar/**").hasAnyRole("USER", "ADMIN") // any authenticated POST-requests should from an ADMIN or USER are allowed

예:

.requestMatchers(HttpMethod.POST, "/bar/**").hasAnyRole("USER", "ADMIN") // any POST-request should be authenticatd
.requestMatchers(HttpMethod.DELETE, "/baz/**").hasRole( "ADMIN") // only ADMINs can issue DELETE-requests to these paths
  • requestMatchers( RequestMatcher ... ) 마지막 버전은 아마도 가장 유연한 버전일 것이며 임의의 수의 결합 인스턴스를 제공할 수 있습니다.이 인터페이스를 직접 구현할 필요는 없습니다(특별한 필요가 없는 한). 바로 사용할 수 있는 구현은 다음과 같습니다.RegexRequestMatcher 것을 하는 데 할 수 .)regexMatchers()).

예:

.requestMatchers(new RegexRequestMatcher("/foo/bar", "POST")).authenticated()

예제 - 원래 문제 해결

나는 허락하고 싶습니다.POST에만 합니다."/api/subscription" 경로. 경로.

그러기 위해서는 경로에 대한 HTTP-method 및 패턴을 지정할 수 있는 이 버전을 사용해야 합니다."/api/subscription".

알림:WebSecurityConfigureAdapter Spring Security 이후로 더 이상 사용되지 않습니다.5.7 지금은 릴스고지금리그리지금.HttpSecurity를 통해 구성 중입니다. (으)SecurityFilterChain빈으로 정의되어야 합니다.

다음은 스프링 6 및 람다 DSL을 사용하여 질문에 정의된 경로에 대한 요청을 보호하는 방법입니다.

@Configuration
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) {
        
        return http
            // other configuration options
            .authorizeHttpRequests(authCustomizer -> authCustomizer
                .requestMatchers(HttpMethod.POST, "/api/subscriptions").permitAll()
                .requestMatchers(
                    "/api/register", "/api/register", "/api/authenticate"
                ).permitAll()
                .requestMatchers("/api/logs/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .requestMatchers("/api/**").authenticated()
            )
            .build();
    }
}

메모

  • 보안 규칙을 위에서 아래로 평가하고 있으며, 첫 번째 일치 규칙이 적용됩니다.규칙이 올바른 순서로 선언되었는지 확인합니다.

  • 기본적으로 거부 정책을 적용합니다.애플리케이션이 진화하는 동안 새로운 경로가 도입되며, 이러한 변경 과정에서 동료들이 보안 제한 사항을 업데이트하는 것을 잊어버리고 일부 엔드포인트가 보호되지 않는 것처럼 보일 가능성이 있습니다.그것을 피하기 위해 각각.SecurityFilterChain(시스템의 다른 부분을 구성하고 순서를 지정하기 위해이상의 필터 체인을 선언할 수 있음) 마지막 제약 조건으로 이에 의해 제어되는 모든 지정되지 않은 URL을 포함하는 일치자를 도입할 수 있습니다.SecurityFilterChain맘에 들다"/foo/**"( /아래의 ) 중 하나를 authenticated()또는denyAll().그리고.SecurityFilterChain되지 않은 .requestMatchers("/**").denyAll()이 구성을 사용하면 인증되지 않은 액세스와 시스템에서 유효한 경로가 모두 표시되지 않습니다.새로 도입된 엔드포인트에 액세스할 수 없는 경우(: 승인되지 않은 요청에 대해서는 허용되어야 함) 개발 프로세스 중에 즉시 동료에게 명백합니다.열려 있어야 할 항목을 지정하고 다른 모든 항목은 기본적으로 닫아 두는 것이 훨씬 안전합니다.

5.7 및 이전 버전

에서도 처음에 스링버서처도음말했이듯에전에프▁as이말.antMatchers()왜냐하면 그것들을 사용함으로써 당신은 깨진 접근 제어의 가변성을 유도할 수 있기 때문입니다.

관련 링크가 하나 더 있습니다.후행 슬래시 일치를 사용하지 않습니다.

대신 Spring MVC 일치 규칙을 사용하거나 정규식 기반을 사용하는 둘 중 하나를 적용하는 것을 고려하십시오. 둘 다mvcMathcers()그리고.regexMatchers()HTTP 메서드를 지정할 수 있는 오버로드된 버전이 있습니다.

에서는 다음사를질문서 API에보를 하여 질문으로부터 합니다.mvcMathcers()Lambda DSL: 표준 사양 5.2 표준 사양 DSL:

@Configuration
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain securityFilterChain1(HttpSecurity http) {
        
        return http
            // other configuration options
            .authorizeRequests(authCustomizer -> authCustomizer
                .mvcMatchers(
                    "/api/register", "/api/register", "/api/authenticate"
                ).permitAll()
                .mvcMatchers("/api/logs/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .mvcMatchers(HttpMethod.POST, "/api/subscriptions").permitAll()
                .mvcMatchers("/api/**").authenticated()
                .regexMatchers("/**").denyAll()
            )
            .build();
    }
}

이 질문이 좀 오래된 것으로 알고 있지만 csrf 지원을 비활성화하는 것이 허용 가능한 답변이라고 생각하지 않습니다.저도 같은 문제가 있었지만 csrf.disable()을 사용하는 것이 좋지 않습니다.대신 폼 태그 안에 페이지 하단에 다음 행을 추가했습니다.

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

언급URL : https://stackoverflow.com/questions/28907030/spring-security-authorize-request-for-certain-url-http-method-using-httpsecu