2015-10-14 33 views
2

我的用例是驗證&,然後根據@PathVariable參數授權用戶。我需要執行一些自定義代碼來授權委託人。我不知道在這裏採取的辦法 -基於路徑變量的spring-security授權

  1. 我實現了自定義AbstractAuthenticationProcessingFilter &的AuthenticationProvider進行認證,這最終賦予角色的主體。我可以檢查servlet請求中的路徑變量(使用HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE),並將其他權限添加到身份驗證令牌中。然後我可以使用內置的hasRole,hasPermission表達式來實現訪問控制。

  2. 我可以擴展WebSecurityExpressionRoot並實現一個自定義AbstractSecurityExpressionHandler並定義我自己的表達式,以用於攔截url訪問控制表達式。我不確定如何在我的WebSecurityExpressionRoot實現中定義自定義方法時訪問@PathVariables。

哪種方法更可取,還是有另一種方法可以乾淨地做到這一點?

回答

1

我可以想象的一種方式是,在參數中捕獲路徑變量,使用方法級別授權,然後使用hasPermissionThis answer有詳細的如何做到這一點 - 以防萬一它會幫助。

+0

hasPermission api有點限制,例如,如果我需要訪問多個路徑變量或api簽名的其他組件,該怎麼辦?這就是爲什麼我想要定義我自己的方法在表達式中使用。 – Oceanic

2

我確實有一個解決方案。 在配置類

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter 

我能有方法

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
      .authorizeRequests() 
      .antMatchers("/student/{id}/**") 
      .access("@guard.checkUserId(authentication,#id)"); 
} 

而@guard在規劃環境地政司鏈接

@Component 
public class Guard { 
    @Autowired 
    private UserRepository repo; 

    public boolean checkUserId(Authentication authentication, int id) { 
     String name = authentication.getName(); 
     System.out.println(name+" at "+id); 
     User result = repo.findByUsername(name); 
     return result != null && result.getPid() == id; 
    } 
} 

在實踐中,規劃環境地政司的#ID可以得到中提取的值來自上一行中的{id}。您可以在checkUserId中執行任何您想要的操作,並且返回值決定是否允許訪問路徑。