簡體   English   中英

如何使用Spring安全保護URL?

[英]How to secure URLs using Spring security?

我正在使用Spring MVC + Spring Security開發一個Web應用程序,我有以下URL:

/*this URL should be accessible by any User, i.e. users should be able to see other users' profiles*/
/users/someUserId/profile

/* all the following URLs should be accessed only by the current authenticated user */
/users/someUserId/profile/edit
/users/someUserId/picture/edit
/users/someUserId/notifications
/users/someUserId/friends

我需要它們如前所述得到保護。

我的配置方法如下:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .regexMatchers("/users/[\\w]+/profile").authenticated()
                .antMatchers("/users/[\\w]/**").access("principal.name == regexGroupMatch")
                .anyRequest().authenticated()               
            .and()
                .jee().mappableRoles("Admin", "User");
    }

我想知道是否有可能實現這樣的目標:

.antMatchers("/heroes/[\\w]/**").access("principal.name == regexGroupMatch")

通過這樣做,我只願用戶user1能夠訪問URL:

/users/user1/profile/edit
/users/user1/picture/edit
/users/user1/notifications

因此, user2必須無法訪問之前提到的URL,但必須能夠訪問:/ users / user1 / profile / edit / users / user1 / picture / edit / users / user1 / notifications

以及:

/users/user1/profile
/users/user2/profile
/users/user3/profile
etc...

是否可以使用Spring Security實現這一目標?

不,沒有功能可以在正則表達式中提取匹配組並將它們與用戶名進行比較。 另請注意,ant模式根本不支持regex表達式。

在任何情況下依賴復雜​​的URL模式都不是一個好主意。 對於類似這樣的事情,您最好在控制器級別或某些服務接口上使用方法安全性,您可以在其中按名稱引用方法參數。 例如,啟用方法安全表達式后,您可以編寫

@PreAuthorize("#user.name == authentication.name")
public void editUser(User user) {
  ....
}

或者,正如Misha所說,你可以直接編寫規則,如果事情變得比簡單表達式更復雜,那么這是更好的選擇。

Spring Security將確保訪問這些端點的客戶端經過身份驗證,但您需要確保端點僅返回允許用戶查看的數據。 想一想 - Spring Security如何知道每個用戶可以看到應用程序中的哪些數據?

您可能已經有一個如下所示的控制器方法:

@RequestMapping(value = "/users/{user}/profile/edit", method = RequestMethod.GET)
public ModelAndView edit(
    HttpServletRequest request, 
    @PathVariable("user") String,
    EditRequest edit) {

    // Accept or reject the request if the user variable and authenticated
    // user match up as required.
}

在這里,您需要以編程方式區分經過身份驗證的用戶(可從請求對象檢索)和上下文所聲明的用戶。 如果上下文中的用戶是經過身份驗證的用戶,則您可以接受該請求,因為可能允許用戶修改他們自己的配置文件。 否則,您可以拋出某種授權異常 - 或者更好的是,返回一個很好的視圖,解釋為什么該頁面不可訪問。

請注意,這也可以重寫為過濾器,因為您沒有在請求正文中使用任何信息。 該過濾器確實會插入Spring Security。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM