개발기술/Spring

Spring Security 전체개념

bsh6226 2024. 9. 9. 14:11

데이터 유출의 위험성

Attackers can gain access to a Wi-Fi network/router and control or monitor the data that flows through it in several ways.

 

How Interception Happens

  • a. Man-in-the-Middle (MitM) Attack: The attacker positions themselves between the user and the server, either by controlling a network device (like a router) or through a compromised Wi-Fi network (e.g., an insecure public Wi-Fi hotspot).
  • b. Packet Sniffing : involves capturing and analyzing packets of data as they travel across a network. This can be done by an attacker using software tools designed to monitor network traffic.

How Impersonation (Spoofing) Attacks:

  • a. IP Spoofing: The attacker forges the IP address in the packets they send, making it appear as though the request comes from a trusted IP address.
  • b. Session Hijacking: The attacker gains access to a valid session ID (e.g., by intercepting a session cookie) and uses it to impersonate a legitimate user.
  • c. Cross-Site Request Forgery (CSRF): The attacker tricks a legitimate user into making an unintended request to a server where they are authenticated, effectively sending a protocol as if they were the client.

 

이러한 위험성때문에 기본적으로 1. 제3의 인물이 서버, 클라이언트 간의 통신을 모니터링 하고 있다는 전제하에서 2. 제3의 인물이 클라이언트로 모방하여 Request를 보낼수 있다는 전제하에서 보안성을 생각하여 개발을 진행해야한다. 

 

 

어플리케이션 Security의 핵심개념

어플리케이션 개발자는 어플리케이션 레벨에서의 보안만 집중하면되며, 어플리케이션 레벨에서는 아래와 같은 5가지 핵심요소가존재한다.

 

1. Authentication(인증) :  Client만 응답할 수있는 key로 Client의 신분을 확인하는 과정

- Knowledge Authentication : PW, Pin Code, 비밀질문 등 사전에 서로 알고있는 지식으로 인증함.

장점 : 간단하게 구현가능 단점 :  해당 지식이 노출되면 Impersonification에 취약함.

- Posession Based : SMS문자인증, KEYCard인증

2. Authorization(권한) : 해당 Client가 실행을 요청하는 데이터/행동이 Client의 권한에 적합한 것인지 확인하는 과정

3. Principal : 현재 인증절차를 거쳐 로그인 상태인 유저

4. Authority : client가 무엇을 할 수 있는지의 사전셋팅

5. Role : group of authority

 

 

스프링 Security 동작방식

Security 관리방식은 크게 두가지 방식으로 나뉜다. Stateless이냐 혹은 Session-Based이냐. Statless는 이전의 상태를 기억하지 못한다는 뜻으로 매 request마다 JWT Authentication을 거쳐야한다. 반면 Session-Based는 https 헤더의 세션 항목에 JWT Authentification을 거친 후, SecurityContext에 대한 정보가 암호화되어 저장되어 JWT auth를 여러번 할 필요가 없다. 다시 말해, Session Based는 JWT와 같은 Userspecific한 정보를 서버에서 관리하는 반면, Satelss 방식에서는 서버에서 관리하지 않아 좀 더 resource 절약이 가능하다. 

1. Session-Based Authentication:

Concept:

  • Session Creation: When a user logs in, the server creates a session to store the user's authentication information (like user ID, roles, etc.). This session is usually stored in a server-side session store (in-memory, database, etc.).
  • Session ID: The server generates a unique session ID and sends it to the client in a cookie. This session ID is the key that allows the server to retrieve the session data associated with the user.
  • Subsequent Requests: On every subsequent request, the client automatically sends the session ID cookie to the server. The server uses this session ID to fetch the session data, which includes information about the authenticated user.
  • Session State: The session is stateful, meaning the server maintains session data between requests. The server is responsible for session management, including creating, maintaining, and invalidating sessions.

Pros:

  • Centralized Control: The server has full control over the session and can easily invalidate it if needed (e.g., user logout, session timeout, security concerns).
  • Security: Since the server manages the session, it can implement security features like session expiration, secure cookie attributes (e.g., HttpOnly, Secure), and CSRF protection.
  • Ease of Implementation: Many frameworks and tools support session-based authentication out of the box, making it easier to implement.

Cons:

  • Scalability: Sessions are typically stored on the server, which can become a bottleneck in terms of memory usage and can complicate horizontal scaling (e.g., load balancing across multiple servers).
  • Stateful: The server must track the state of each session, which can lead to challenges in managing large numbers of sessions.

2. Stateless JWT-Based Authentication:

Concept:

  • JWT Token: Upon successful authentication, the server generates a JWT (JSON Web Token) that contains the user's authentication information (like user ID, roles, etc.). This token is signed by the server to ensure its integrity.
  • No Server-Side State: Unlike session-based authentication, the server does not store any session data. Instead, all necessary information is encoded in the JWT itself.
  • Subsequent Requests: The client must include the JWT in the Authorization header (typically using the Bearer scheme) with every request. The server verifies the JWT's signature and extracts the user's information directly from the token.
  • Stateless: The server is stateless with respect to authentication, meaning it does not maintain any session data between requests. Each request is authenticated independently using the JWT.

Pros:

  • Scalability: Stateless JWT-based authentication is highly scalable because the server does not need to store or manage sessions. This is ideal for distributed systems or applications with microservices architecture.
  • Decentralization: JWTs can be used across different domains or services without needing a centralized session store. This is useful for APIs and microservices that need to share authentication data.
  • Flexibility: JWTs can be easily passed between different services, making them suitable for single sign-on (SSO) implementations and API authentication.

Cons:

  • Security Challenges: JWTs are typically long-lived, and once issued, they remain valid until they expire. If a JWT is compromised, it can be used by an attacker until it expires unless additional mechanisms (like a token blacklist) are implemented.
  • Token Revocation: Unlike sessions, where the server can easily invalidate a session, revoking a JWT before its expiration is more complex and often requires additional infrastructure.
  • Token Size: JWTs can be larger than session IDs because they contain more information. This can add overhead to every request, particularly in cases where many small, frequent requests are made.

 

스프링 Security의 기본동작

Spring Security Dependency를 추가하면 아래와 같이 바로 default 동작이 실행된다.

 

SpringSecurity Default Behavior

1. Add Mandatory authentication for all URL

2. adds login form page, handles login error

3. 개발자가 별도로 정하지 않을시 서버를 실행시킬때마다 ID와 PW를 생성한다.( ID:user, PW: 로그창에 자동생성)

properties - spring.security.user.name = ID / spring.security.user.name =PW

 

 

스프링 Security Authentication 전체구조

 

애플리케이션은 사용자가 자신이 주장하는 사람인지 확인할 필요가 있습니다. 이는 일반적으로 **사용자 이름(username)**과 비밀번호(password) 확인을 통해 이루어집니다. 사용자가 애플리케이션에 인증을 요청하면, 해당 요청은 Authentication 관련 필터에 도달하게 됩니다. 이 필터는 AuthenticationManager(주로 ProviderManager가 사용됨)에게 authenticate() 메소드를 호출하여 인증을 요청합니다.

AuthenticationManager는 적절한 AuthenticationProvider를 찾아 해당 요청을 위임(delegation)하여 처리합니다. 이 과정에서 AuthenticationProvider는 주어진 인증 전략에 따라 사용자 인증을 수행합니다. 여러 가지 AuthenticationProvider가 존재할 수 있으며, 각 AuthenticationProvider는 특정 인증 방법(예: 사용자 이름/비밀번호 인증, OTP 인증 등)에 대해 특화되어 있습니다. AuthenticationManager는 요청된 인증 방법에 적합한 AuthenticationProvider에게 인증 요청을 위임합니다. 인증이 성공적으로 완료되면, Authentication 객체가 반환됩니다. 이 객체는 인증과 관련된 정보를 담고 있는 DTO(Data Transfer Object)입니다. 인증이 완료되기 전에는 credentials(예: 비밀번호)을 포함하고 있으며, 인증이 완료된 후에는 인증된 사용자의 정보를 담고 있는 principal(예: 사용자 이름, 권한 등)을 포함하게 됩니다. 이 principal은 보통 UserDetails 객체로 표현되며, 이는 인증된 사용자의 주요 정보를 포함하는 역할을 합니다. 최종적으로, UserDetails라는 사용자에 대한 공통적인 속성을 가지는 객체가 Principal 정보로 반환됩니다. 이 객체에는 사용자의 권한(roles), 계정 상태(활성화 여부, 계정 만료 여부 등), 사용자 이름, 비밀번호 등이 포함됩니다. 인증이 완료된 후, 이 Authentication 객체는 SecurityContext에 저장되어 이후의 요청에서 사용자의 인증 상태를 확인하는 데 사용됩니다.

 

스프링 Security Filter

Filter동작방식

Springsecurity는 Dispatcher Servelet으로 가기전에 통과해야하는 Chain of Filter을 말한다. (이 필터를 통해서 서블릿으로 들어가는 모든 request에 대해서  Intercept하여  승인, 거절 혹은 그 외의 처리를 해준다.) 기본적으로 표준 서블릿컨테이너는 자체 표준으로 사용하는 필터를 등록할 수 있다.

Spring Security는 표준 서블릿 컨테이너의 필터 외에도 Spring Bean으로 구현한 모든 필터를 등록할 수 있다. FilterChainProxy는 여러 SecurityFilterChain을 관리하며, 요청 URL에 따라 적절한 SeculirtyFilter을 실행하는 MVC패턴에서의 Dispatcher역할을 한다. 서블릿컨테이너는 서블릿에서 지원하는 DelegatingFilterProxy를 통해서 FilterChainProxy에게 Filter호출을 위임하고, 이를 통해서 Spring 컨텍스트 내에서 관리되는 필터 빈에 요청을 위임한다.

 

 

FilterChainProxy:

  • This is a special proxy filter that acts as the main entry point for Spring Security's filter chain. It delegates the actual work of processing security filters to one or more filter chains based on the request.

FilterStack

  • The SecurityContextPersistenceFilter : one of the first filters in the Spring Security filter chain. Its primary job is to manage the SecurityContext for each request.
  • JWT Authentication Filter: a custom filter or Spring Security's built-in filter would typically check for the presence of a JWT in the request . The filter extracts the token, validates it, and, if valid, creates an Authentication object and stores it in the SecurityContext.
  • CSRF Filter :  helps protect against CSRF attacks by ensuring that every state-changing request (like POST, PUT, DELETE). When a user accesses a form or page that can change state on the server, Spring Security generates a CSRF token and includes it in the response (usually as a hidden input in forms). When the user submits the form, this token is sent back to the server.
  • UsernamePasswordAuthenticationFilter :  a filter in Spring Security that handles the form-based 'default' login process, where users provide their username and password. The filter, through the AuthenticationManager and typically a DaoAuthenticationProvider, uses UserDetailsService to load the user's details. Without UserDetailsService, the filter would not know how to retrieve the necessary data for authentication.

 

스프링 Security Context

한번 Jwt인증을 통해서 Authentication 객체를 SecurityContext에 넣었다고 한다면, 더이상 해당 request는 Authentication 과정을 거치지 않아도 된다. 그리고 이 인증은 thread localvariable에 저장되어서 thread의 생명주기가 끝날때까지 다시 Authentication과정을 거치지 않아도 된다. 특히, method 별로 권한을 설정하였을 경우 다시 Authentication을 통해 role을 parsing할 필요가 없어진다. 

 

 

스프링 Userdetails

the UserDetailsService interface is considered a core part of Spring Security, largely because it is integral to the authentication process, particularly when using standard authentication mechanisms like the UsernamePasswordAuthenticationFilter.