TIL

Expression-Based Access Control

스프링 시큐리티는 SpEL 표현식을 사용한다. 표현식 평가는 root object를 사용하여 평가된다. 스프링 시큐리티는 특정 클래스를 루트 객체로 사용하여 기본 제공 표현식을 제공하고 현재와 같은 엑세스 규칙을 제공한다.

Common Built-In Expressions

Expression Description
hasRole(String role) 현재 principal이 지정된 role을 가지고 있으면 true를 반환한다.
hasAnyRole(String…​ roles) 현재 principal이 제공된 역할 중 하나라도 가지고 있으면 true를 반환한다.
hasAuthority(String authority) 현재 principal이 지정된 authority를 가지고 있으면 true를 반환한다.
hasAnyAuthority(String…​ authorities) 현재 principal이 제공된 authority들을 가지고 있으면 true를 반환한다.
principal 현재 사용자를 나타내는 principal 객체에 접근할 수 있다.
authentication SecurityContext에서 가져온 Authentication 객체에 직접 엑세스할 수 있다.
permitAll 항상 true를 반환
denyAll 항상 false를 반환
isAnonymous() 현재 사용자가 익명 사용자면 true를 반환한다.
isRememberMe() 현재 사용자가 remember-me 사용자면 true를 반환한다.
isAuthenticated() 현재 사용자가 익명도이 아니면 true를 반환한다.
isFullyAuthenticated() 현재 사용자가 익명도, rememer-me도 아니면 true를 반환한다.
hasPermission(Object target, Object permission) 사용자가 주어진 권한에 대해 제공된 대상에 접근할 수 있으면 true를 반환한다. ex) hasPermission(domainObject, ‘read’)
hasPermission(Object targetId, String targetType, Object permission) 사용자가 주어진 권한에 대해 제공된 대상에 접근할 수 있으면 true를 반환한다. ex) hasPermission(1, ‘com.example.domain.Message’, ‘read’).

Referring to Beans in Web Security Expressions

public class WebSecurity {
		public boolean check(Authentication authentication, HttpServletRequest request) {
				...
		}
}
http
    .authorizeHttpRequests(authorize -> authorize
        .requestMatchers("/user/**").access(new WebExpressionAuthorizationManager("@webSecurity.check(authentication,request)"))
        ...
    )

Path Variables in Web Security Expressions

public class WebSecurity {
		public boolean checkUserId(Authentication authentication, int id) {
				...
		}
}
http
	.authorizeHttpRequests(authorize -> authorize
		.requestMatchers("/user/{userId}/**").access("@webSecurity.checkUserId(authentication,#userId)")
		...
	);

Method Security Expressions

@Pre and @Post Annotaions

<global-method-security pre-post-annotations="enabled"/>

Access Control using @PreAuthorize and @PostAuthorize

Filtering using @PreFilter and @PostFilter

Built-In Expressions

The PermissionEvaluator interface