> For the complete documentation index, see [llms.txt](https://ysfang82.gitbook.io/development-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ysfang82.gitbook.io/development-notes/programming-langauges/java/spring-boot/spring-security.md).

# Spring Security

**Key concepts**

* Config with `@EnableWebSecurity` and extends `WebSecurityConfigurerAdapter`
* Authority of `antMatchers` can be delegated with `has(Any)Role`, `has(Any)Authority`.
  * Order of `antMatcher` matters, specific path should be defined first.
  * In Pojo Enum design, can set up permission enum as the `Set` attribute of role enum
  * Authority can either be set up with `@EnableGlobalMethodSecurity` in config and `@PreAuthorize` in controllers.
* To load users for AA, creating a service (with `@Service`) that implements `UserDetailsService`, and overrides `loadUserByUsername()`
* Authentication
  * Basic
    * Using header to send based64-encoded username:password so HTTPS is recommended
    * Simple and fast, but cannot logout
  * Form-based
    * Using form to send username, password to get sessionid back and then store in cookies
    * Can logout
    * Session id can be stored to external DBs. like: Redis
* CSRF
  * Turned on by default, and a token issued by Spring Security would be kept in browser cookies. And POST / PUT / PATCH / DELETE requests must carry the token.
  * If the client is not a browser, turn CSRF protection off.
