본문 바로가기

Spring 정리ver2

[baeldung] Spring Security Basic Authentication

728x90

 

 

The Spring Security Configuration

 

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter {

    @Autowired private MyBasicAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user1")
          .password(passwordEncoder().encode("user1Pass"))
          .authorities("ROLE_USER");
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/securityNone")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic()
            .authenticationEntryPoint(authenticationEntryPoint);
        http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
        return http.build();
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

SecurityFilterChain  내부에 기본 인증을 정의하기 위해 httpBasic() 요소를 사용하고 있다

 

 

 

 

Consuming the Secured Application

The curl command is our go-to tool for consuming the secured application.

 

안 자격 증명을 제공하지 않고 /homepage.html 을 요청하면

curl -i http://localhost:8080/spring-security-rest-basic-auth/api/foos/1

 

get back the expected 401 Unauthorized and the Authentication Challenge:

HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=E5A8D3C16B65A0A007CFAACAEEE6916B; Path=/spring-security-mvc-basic-auth/; HttpOnly
WWW-Authenticate: Basic realm="Spring Security Application"
Content-Type: text/html;charset=utf-8
Content-Length: 1061
Date: Wed, 29 May 2013 15:14:08 GMT

 

에러를 반환한다

 

 

액세스할 수 있는 자격 증명 도 제공하게 되면

curl -i --user user1:user1Pass 
  http://localhost:8080/spring-security-rest-basic-auth/api/foos/1

결과적으로 서버의 응답은 쿠키 와 함께 200 OK 가 뜬다

브라우저에서 정상적으로 사용할 수 있다.

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=301225C7AE7C74B0892887389996785D; Path=/spring-security-mvc-basic-auth/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
Content-Length: 90
Date: Wed, 29 May 2013 15:19:38 GMT

 

 

 

Further Configuration – the Entry Point

 

기본적으로 Spring Security에서 제공하는 BasicAuthenticationEntryPoint는 401 Unauthorized 응답 에 대한 전체 페이지를 클라이언트에 다시 반환한다. 만약 json 으로 값을 받고 싶거나 REST API 를 사용할 경우에는 다른 방식을 쓰는게 좋다

 

 

@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) 
      throws IOException, ServletException {
        response.addHeader("WWW-Authenticate", "Basic realm="" + getRealmName() + """);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = response.getWriter();
        writer.println("HTTP Status 401 - " + authEx.getMessage());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("Baeldung");
        super.afterPropertiesSet();
    }
}복사

HTTP 응답에 직접 작성함으로써 이제 응답 본문의 형식을 완전히 제어할 수 있다.

 

 

 

 

The Maven Dependencies

The Maven dependencies for Spring Security have been discussed before in the Spring Security with Maven article. We will need both spring-security-web and spring-security-config available at runtime.

728x90