본문 바로가기

Spring 정리ver2/Security

[baeldung] Intro to Spring Security Expressions

728x90

 

 

 

Configuration

Java configuration 

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan("com.baeldung.security")
public class SecurityJavaConfig {
    ...
}

 

XML configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans ...>
    <global-method-security pre-post-annotations="enabled"/>
</beans:beans>

 

밑에 XML 예제는 안씀..

 

 

 

 

 

 

Web Security Expressions

Now let's explore the security expressions:

  • hasRole, hasAnyRole
  • hasAuthority, hasAnyAuthority
  • permitAll, denyAll
  • isAnonymous, isRememberMe, isAuthenticated, isFullyAuthenticated
  • principal, authentication
  • hasPermission

 

hasRole, hasAnyRole

애플리케이션에서 특정 URL 및 메소드에 대한액세스 제어 또는 권한 부여 결정

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    ...
    .antMatchers("/auth/admin/*").hasRole("ADMIN")
    .antMatchers("/auth/*").hasAnyRole("ADMIN","USER")
    ...
}

ADMIN 역할일 때 접근 가능  /auth/admin/ 

USER 또는 ADMIN 역할일 때 접근 가능 /auth/ 

 

 

 

hasAuthority, hasAnyAuthority

Roles and authorities는 비슷한 의미지만

Spring Security 4 부터는 'ROLE_' 을 이용하여 자동 추가 된다

hasAuthority('ROLE_ADMIN')는 ' ROLE_ ' 접두사가 자동으로 추가되기 때문에 hasRole('ADMIN') 과 유사하다

ROLE_ 접두사를 전혀 사용할 필요가 없는 장점이 있다.

 

defining users with specific authorities:

roles를 부여해준다

@Bean
public InMemoryUserDetailsManager userDetailsService() {
    UserDetails admin = User.withUsername("admin")
        .password(encoder().encode("adminPass"))
        .roles("ADMIN")
        .build();
    UserDetails user = User.withUsername("user")
        .password(encoder().encode("userPass"))
        .roles("USER")
        .build();
    return new InMemoryUserDetailsManager(admin, user);
}

 

authorities expressions:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    ...
    .antMatchers("/auth/admin/*").hasAuthority("ADMIN")
    .antMatchers("/auth/*").hasAnyAuthority("ADMIN", "USER")
    ...
}

 

 

 

Spring 5 부터는, PasswordEncoder bean이 필요함

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

 

 

permitAll, denyAll

서비스의 일부 URL에 대한 액세스를 허용하거나 거부한다

 

모든 사용자(anonymous and logged in) 모두 접근할 수 있는 권한 부여

...
.antMatchers("/*").permitAll()
...

 

 

모든 사용자(anonymous and logged in) 모두 접근권한 거부

...
.antMatchers("/*").denyAll()
...

 

 

isAnonymous, isRememberMe, isAuthenticated, isFullyAuthenticated

사용자의 로그인 상태에 대한 표현

 

승인되지 않은 모든 사용자가 기본 페이지에 액세스

...
.antMatchers("/*").anonymous()
...

 

 

웹사이트를 사용하는 모든 사람이 로그인하도록 웹사이트를 보호하려면 isAuthenticated() 메서드 를 사용

...
.antMatchers("/*").authenticated()
...

 

 

 

isRememberMe()  isFullyAuthenticated()라는 두 가지 추가 표현식이 있다

쿠키 사용을 통해 Spring은 기억하기 기능을 활성화하므로 매번 시스템에 로그인할 필요가 없다. 

Remember (https://www.baeldung.com/spring-security-remember-me)

 

Spring Security Remember Me | Baeldung

Cookie Remember Me example with Spring Security.

www.baeldung.com

 

Remember me 기능으로 로그인한 사용자에게 액세스 권한을 부여하려면 다음을 사용할 수 있다.

...
.antMatchers("/*").rememberMe()
...

 

 

이미 로그인한 경우에도 사용자를 다시 인증해야하는 경우가 있다.

사용자가 설정이나 결제 정보를 변경하려고 하는 경우에는  수동 인증을 요청하는 것이 좋다

anonymous or remember-me user 가 아닌 경우 true를 반환한다

...
.antMatchers("/*").fullyAuthenticated()
...

 

 

principal, authentication

현재 인증된(또는 익명의) 사용자를 나타내는 주체 개체와 SecurityContext  현재 인증 개체에 각각 액세스할 수 있다

principal을 사용하여 로그인한 사용자가 액세스할 수 있는 사용자의 이메일, 아바타 또는 기타 데이터를 로드할 수 있다.

인증은 부여된 권한과 함께 전체 인증 개체에 대한 정보를 제공한다.

 

 

https://delightpip.tistory.com/235

 

 

 

 

 

hasPermission API

이 표현은 문서화되어 있으며 표현 시스템과 Spring Security의 ACL 시스템 사이의 브리지 역할을 하여 추상 권한을 기반으로 개별 도메인 개체에 대한 권한 부여 제약 조건을 지정할 수 있다

 

저자가 제안한 기사를 출판해야 하는지를 결정하는 주 편집자와 협력하여 기사 작성을 허용하는 서비스가 있다면

서비스의 사용을 허용하기 위해 액세스 제어 방법으로 다음 방법을 만들 수 있다.

@PreAuthorize("hasPermission(#article, 'isEditor')")
public void acceptArticle(Article article) {
   …
}

인증된 사용자만 이 메서드를 호출할 수 있으며 서비스에서 isEditor 권한이 있어야 한다

또한 애플리케이션 컨텍스트에서 PermissionEvaluator를 명시적으로 구성해야 한다

여기서 customInterfaceImplementation은 PermissionEvaluator를 구현하는 클래스가 된다

 

@Override
protected MethodSecurityExpressionHandler expressionHandler() {
    DefaultMethodSecurityExpressionHandler expressionHandler = 
      new DefaultMethodSecurityExpressionHandler();
    expressionHandler.setPermissionEvaluator(new CustomInterfaceImplementation());
    return expressionHandler;
}
728x90