> For the complete documentation index, see [llms.txt](https://tech.x2bee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tech.x2bee.com/dev-guide/dev-start/markdown/xss.md).

# XSS 방지 처리

다음은 XSS 방지 처리에 대한 설명입니다.

XSS 방지 기능의 경우 XssSanitizer 커스텀 어노테이션 및 XssProtectUtils Class 함수를 제공하고 있습니다.

***

## xss-rule.yml

(경로 : resources/config/xss-rule.yml)

다음은 예시 xss-rule.yml 설정입니다:

```yaml
# XSS Rule setting ###########################################
xss:
  direction: response #request(요청시에만), response(응답시에만), both(요청,응답 모두) XSS필터링이 적용됨
  allowElements: -> 허용할 Element 작성
    - a
    - img
    - div
    - ul
    - li
    - link
    - input
  allowAttributes: -> 허용할 Element의 허용할 Attribute 작성
    img:
      - alt
      - align
      - title
      - img
    div:
      - class
      - id
      - style
  allowUrls: -> 허용할 URL 목록과 각 URL에 허용할 Attribute 작성 (allowElements와 allowAttributes도 포함하여 적용됨)
    - url: /api/display/samples/xss2
      allowElements:
        - button
      allowAttributes:
    - url: /api/display/**/url -> ** 패턴 사용가능
      allowElements:
        - a
      allowAttributes:
        img:
          - alt
          - align
          - title
          - img
```

※ 해당 기능을 사용하기 위해서는 먼저 resources/config/xss-rule.yml 파일에 White List 기법으로 작성해줘야 됩니다.

* `direction` 속성은 필터링을 적용할 방향을 작성 합니다.
  * 세가지 옵션(`request`,`response`,`both`) 이 존재하며 request는 요청시에만, response는 응답시에만, both는 요청시와 응답시 모두 필터링이 적용됩니다.
* `allowElements`에는 허용할 Element를 작성 합니다.
* `allowAttributes`에는 허용할 Element에서 허용할 Attribute를 작성 합니다.
  * 만약에 allowElements에는 작성했지만 allowAttributes에는 작성하지 않았다면 해당 Element는 모두 허용하게 됩니다.
* `allowUrls`에는 특정 URL에서 별도로 허용해주고자 하는 Element와 Attribute를 명시합니다. (상위 `allowElements`와 `allowAttributes`의 속성들을 상속받습니다)
  * `url` 속성을 List 형태로 작성해야 하며 `url` 속성 하위에는 `allowElements`과 `allowAttributes` 를 작성합니다.
  * `url` 은 고정 URL과 URL-Pattern 모두 사용 가능합니다. 예시의 `/api/display/**/url` 와 같이 작성하면 /api/display/**test1**/url 또는 /api/display/**test1/test2/test3**/url 와 같은 URL들을 모두 필터링합니다.
  * `allowElements` 속성은 필수로 작성해야 하며 상위 `allowElements` 에 존재하는 Element의 `allowAttributes` 를 추가로 작성하고자 한다면 동일한 Element를 명시하고 `allowAttributes` 를 작성합니다.
  * `allowAttributes` 속성에 Attribute를 작성하면 해당 Attribute만 허용되며 빈칸으로 두면 `allowElements` 에 명시된 Element에서 사용가능한 모든 Attribute를 허용합니다.

## XssSanitizer 커스텀 어노테이션

예시 모델 클래스:

```java
@Alias("sampleRequest")
@Getter
@Setter
public class SampleRequest extends BaseCommonEntity {
    private Long id;
    private String name;
    @XssSanitizer
    private String description;
    private LocalDateTime localDateTime;
    private LocalDate localDate;
    private LocalTime localTime;
}
```

반환할 모델의 필드에 `@XssSanitizer` 어노테이션을 붙여주면 해당 필드는 MessageConverter에서 JSON Serialize할 경우에 XssProtectUtils Class의 `getHtmlSanitizer` 함수를 통하여 허용된 값들만 남기고 반환하게 됩니다.

<figure><img src="/files/u6nVklNTJriAEInNnK4P" alt=""><figcaption></figcaption></figure>

## 비즈니스 로직에서 XssProtectUtils 함수 사용

예시 컨트롤러 코드:

```java
private final XssProtectUtils xssProtectUtils;

@GetMapping("/xss2")
public ResponseEntity<Response> x22(@RequestBody @Valid Optional<SampleRequest> sampleRequest) {
    // 데이터와 함께
    log.info("sampleRequest: {}", sampleRequest.isPresent() ? sampleRequest.get() : "");
    String test = XssProtectUtils.getInstance().getHtmlSanitizer(sampleRequest.get().getDescription());
    String test2 = xssProtectUtils.getHtmlSanitizer(sampleRequest.get().getDescription());
    Response body = Response.builder()
        .payload(sampleRequest.get())
        .build();
    return ResponseEntity.ok().body(body);
}
```

일반 비즈니스 로직에서 다음과 같이 의존성 주입 및 싱글톤 방식으로 함수를 사용합니다.

<figure><img src="/files/mGVJvAW7pQmn7BIAa50s" alt=""><figcaption></figcaption></figure>

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tech.x2bee.com/dev-guide/dev-start/markdown/xss.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
