簡體   English   中英

如何修復 Spring Security 中的角色?

[英]How to fix role in Spring Security?

我試圖在我的項目中使用 Spring Security,這是代碼:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // TODO Auto-generated method stub
    //super.configure(auth);
    //auth.inMemoryAuthentication().withUser("admin").password("1111").roles("USER");
    auth
        .jdbcAuthentication()
            .dataSource(dataSource)
            .usersByUsernameQuery("select username, password, 1 from users where username=?")
            .authoritiesByUsernameQuery("select users_username, roles_id  from roles_users where users_username=?")
            .rolePrefix("ROLE_");
}   

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable();      
    http
        .httpBasic();
    http
        .authorizeRequests()
            .anyRequest().authenticated();
    http
        .authorizeRequests()
            .antMatchers("/users/all").hasRole("admin")
            .and()
        .formLogin();
    http
        .exceptionHandling().accessDeniedPage("/403");
}

這是問題所在:

想象一下,我們的數據庫中有兩個用戶(一個具有user角色,另一個具有admin角色),一個是管理員,第二個是用戶,問題是當我以用戶身份(只有user角色)連接時,它可以訪問管理資源(這不是預期的行為)。

我認為這個查詢中的問題:

"select username, password, 1 from users where username=?" 

根據那個username是主鍵?

如果有人知道我如何解決這個問題?

您的第一個匹配器anyRequest()始終被應用,因為匹配器的順序很重要,請參閱HttpSecurity#authorizeRequests

請注意,匹配器是按順序考慮的。 因此,以下內容無效,因為第一個匹配器匹配每個請求並且永遠不會到達第二個映射:

 http.authorizeRequests().antMatchers("/**").hasRole("USER").antMatchers("/admin/**") .hasRole("ADMIN")

您修改和簡化的配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()      
        .httpBasic()
            .and()
        .authorizeRequests()
            .antMatchers("/users/all").hasRole("admin")
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .and()
        .exceptionHandling().accessDeniedPage("/403");
}

問題在於配置HttpSecurity時規則的順序。 發生的事情是當請求進來並擊中

authorizeRequests().anyRequest().authenticated() 

並且由於用戶已通過身份驗證,因此它永遠不會進入

.antMatchers("/users/all").hasRole("admin")

以下是如何配置它的示例:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()      
        .httpBasic()
        .and()
    .authorizeRequests()
        .antMatchers("/public").permitAll()
        .antMatchers("/user").hasRole("USER")
        .antMatchers("/admin").hasRole("ADMIN")
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .and()
    .exceptionHandling().accessDeniedPage("/403");
}

它使用責任鏈模式。 它將遍歷規則鏈,直到找到匹配的規則。 永遠不會到達匹配規則之后的任何規則。 通常在為經過身份驗證的請求編寫規則時,更具體的規則將首先出現。

暫無
暫無

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

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