AdSense

網頁

2019/9/23

Spring Security @EnableGlobalMethodSecurity 用途

Spring Security @EnableGlobalMethodSecurity 用途如下。

@EnableGlobalMethodSecurity用途相當於Spring MVC傳統xml配置的<global-method-security>

@EnableGlobalMethodSecurity用來啟用基於annotation註解如@Security@PreAuthorize@RolesAllowed的服務層安全機制。

@EnableGlobalMethodSecurity本身包含了@Configuration註解,一般都是與Spring Security的配置類放在一起如下。

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableGlobalMethodSecurity(securedEnabled = true)
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    ...
}

@EnableGlobalMethodSecurity有三個屬性值,
securedEnabled設定是否啟用@Secured
prePostEnabled設定是否啟用@PreAuthorize
jsr250Enabled設定是否啟用@RolesAllowed


通過啟用annotation安全性註解,就能在服務層的介面,類別或方法上加掛@Security@PreAuthorize@RolesAllowed來限制存取權限,例如:

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.annotation.security.RolesAllowed;

public interface BankService {

    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public Account getAccount(Long id);

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public List<Account> findAccounts();

    @RolesAllowed({"ROLE_ADMIN"})
    public Account add(Account account, double amount);

}

參考:

沒有留言:

AdSense