티스토리 뷰

개인공부/Spring

Spring Security - WebSecurity, HttpSecurity

날따라해봐요요롷게 2022. 5. 12. 22:37

스프링 시큐리티를 적용하면서 직접 시큐리티를 커스텀 설정한다.

 

Spring @EnableWebSecurity vs @EnableGlobalMethodSecurity

Protecting Our Endpoints -->  @EnableWebSecurity

With Spring Security on the classpath, Spring Boot Security Auto-Configuration‘s WebSecurityEnablerConfiguration activates @EnableWebSecurity for us.

AD

This applies Spring's default security configuration to our application.

Default security activates both HTTP security filters and the security filter chain and applies basic authentication to our endpoints.

(기본 보안은 HTTP 보안 필터와 보안 필터 체인을 모두 활성화하고 엔드포인트에 기본 인증을 적용합니다.)

 

@EnableWebSecurity
public class MySecurityConfigurer extends WebSecurityConfigurerAdapter {
}

By extending the adapter, we get the benefits of Spring Security's other defenses while also being able to add customizations.

(어댑터를 확장하면 Spring Security의 다른 방어 기능을 활용하는 동시에 사용자 지정을 추가할 수 있습니다.)

-> 어댑터를 사용하여 커스텀을 진행한다.

 

==

 

@Override
protected void configure(HttpSecurity http) {
    http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
    http.formLogin();
    http.httpBasic();
}

 

Protect Our Endpoints Using Annotations --> @EnableGlobalMethodSecurity

Require Users to Have an Appropriate Role Using Security Annotations

Now let's use method annotations to configure our security to allow only ADMIN users to access our /admin endpoint and our USER users to access our /protected endpoint.

(이제 메서드 주석을 사용하여 관리자만 /admin 끝점에 액세스할 수 있도록 보안을 구성하고 사용자만 /protected 끝점에 액세스할 수 있도록 하겠습니다.)

 

Enforce All Public Methods Have Security

When we use annotations as our way of implementing security, we may forget to annotate a method. This would inadvertently create a security hole.

To safeguard against this, we should deny access to all methods that don't have authorization annotations.

 


 

WebSecurity vs HttpSecurity

Configuring HTTPSecurity vs WebSecurity

WebSecurity is considered to be above HttpSecurity, when we areignoring any enpoints in WebSecurity then they are not considered in HttpSecurity.

(WebSecurity는 HttpSecurity보다 위에 있는 것으로 간주되며, WebSecurity에서 enpoint를 무시하면 HttpSecurity에서 고려되지 않습니다.)

 

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/health", "/health/**");
}
@Override
public void configure(HttpSecurity http) throws Exception {
     http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/health", "/health/**").permitAll()
        .anyRequest().authenticated();
}

Let’s consider the below code, we can ignore the authentication for the /health endpoint using WebSecurity and HttpSecurity as shown below

(/health 엔드포인트에 대해서 인가를 무시한다.)

 

  • configure(WebSecurity web) Endpoints specified in this method will be ignored by Spring Security, meaning it will by-pass the Spring Security Filter Chain and no security context will be set.

-> WebSecurity web의 엔드포인트는 Spring Security 필터 체인을 바이패스하고 보안 컨텍스트가 설정되지 않음을 의미하며, Spring Security에서 무시됩니다.

 

  • configure(HttpSecurity http) Endpoint used in this method ignores the authentication for endpoints used in antMatchers. Requests will be allowed to be accessed from the Spring Security Filter Chain.

-> HttpSecurity http에 사용된 엔드포인트는 antMatcher에 사용된 엔드포인트에 대한 인증을 무시합니다. 스프링 보안 필터 체인에서 요청에 액세스할 수 있습니다.

 

So using HttpSecurity and try to permitAll(), is costly as the requests are passed through Spring Security Filter Chain

-> HttpSecurity를 사용하고 permitAll()을 사용하면 요청이 Spring Security 필터 체인을 통해 전달되기 때문에 비용이 많이 듭니다

 

Use configure(HttpSecurity http) if you need any endpoint that requires defense against common vulnerabilities.

: 일반적인 취약성에 대한 방어가 필요한 엔드포인트가 필요한 경우 configure(Http Security http)를 사용합니다.

 

Use configure(WebSecurity web) if you wish to ignore certain requests for authentication purposes.

: 인증 목적으로 특정 요청을 무시하려면 configure(WebSecurity 웹)를 사용

 

WebSecurity ignoring() bypasses spring security entirely and HttpSecurity permitAll() allows anonymous access to the configured endpoint.

-> WebSecurity ignore()는 스프링 보안을 완전히 무시하고 HttpSecurity permitAll()은 구성된 엔드포인트에 익명 액세스를 허용합니다.

 

Typically use case of ignoring certian endpoints from Spring Security is login pages, public pages, health APIs , as you don’t need any Authentication/Authorization to be in place for these endpoints.

-> 일반적으로 Spring Security에서 특정 엔드포인트를 무시하는 사용 사례는 로그인 페이지, 공용 페이지, 상태 API입니다. 이러한 엔드포인트에 대해 인증/권한이 필요하지 않기 때문입니다.

 

WebSecurity

antMatchers에 파라미터로 넘겨주는 endpoints는 Spring Security Filter Chain을 거치지 않기 때문에 '인증' , '인가' 서비스가 모두 적용되지 않는다.

또한 Security Context를 설정하지 않고, Security Features(Secure headers, CSRF protecting 등)가 사용되지 않는다.

Cross-Site-Scripting(XSS), content-sniffing에 대한 endpoints 보호가 제공되지 않는다.

 

-> 따라서 토큰 재발급을 해주는 api는 webSecurity 설정을 사용하여 인증, 인가를 적용되지 않도록 하였다.

 

HttpSecurity

antMatchers에 있는 endpoint에 대한 '인증'을 무시한다.

Security Filter Chain에서 요청에 접근할 수 있기 때문에(요청이 security filter chain 거침) 인증, 인가 서비스와

Secure headers, CSRF protection 등 같은 Security Features 또한 사용된다.

취약점에 대한 보안이 필요할 경우 HttpSecurity 설정을 사용해야 한다.

 


@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/h2-console/**")
                .antMatchers("/member/reissue"); }

api "/member/reissue" 를 WebSecurity 에 설정을 한 이유는 Spring Security Filter Chain 을 거치지 않고 인증, 인가 서비스를 적용하지 않기 위해서이다.

 


출처 : https://www.baeldung.com/spring-enablewebsecurity-vs-enableglobalmethodsecurity

 

Spring @EnableWebSecurity vs. @EnableGlobalMethodSecurity | Baeldung

Spring Security in Spring Boot allows a couple of different approaches for setting access rights for our endpoints. We explore both the standard web security module and the JSR--250 approach that can be applies to methods deeper than the controller.

www.baeldung.com

https://ravthiru.medium.com/springboot-security-configuration-using-httpsecurity-vs-websecurity-1a7ec6a23273

 

SpringBoot : Security Configuration using HTTPSecurity vs WebSecurity

In this article, we’ll have a look at customizing Security Configuration and when to use HTTPSecurity vs WebSecurity configurations.

ravthiru.medium.com

 

'개인공부 > Spring' 카테고리의 다른 글

스프링2  (0) 2022.05.12
면접 준비 - spring framework  (0) 2022.05.11
스프링1  (0) 2022.05.09
CRUD 구현  (0) 2021.11.02
설정 - ORACLE DB  (0) 2021.09.15
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함