2015-03-31 64 views
1

我希望在我的REST服務器中有兩種請求: 那些擁有「/ freerest /」路徑的人可以請求,其他人則需要驗證。URL和用戶的春季安全配置

這是我的代碼:

@Configuration 
@ComponentScan 
@EnableAutoConfiguration 
public class Application { 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 

} 

@Configuration 
class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter { 

    @Autowired 
    UserAccountRepository userAccountRepository; 

    @Override 
    public void init(AuthenticationManagerBuilder auth) throws Exception { 
    auth.userDetailsService(userDetailsService()); 
    } 

    @Bean 
    UserDetailsService userDetailsService() { 
    return new UserDetailsService() { 

     @Override 
     public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { 
     UserAccount account = userAccountRepository.findByEmail(email); 
     if(account != null) { 
      return new User(account.getEmail(), account.getPassword(), true, true, true, true, 
       AuthorityUtils.createAuthorityList("USER")); 
     } else { 
      throw new UsernameNotFoundException("could not find the user '" 
        + email + "'"); 
     } 
     } 

    }; 
    } 
} 

@EnableWebSecurity 
@Configuration 
class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception {  
    http.authorizeRequests().antMatchers("/freerest/**").permitAll().and().authorizeRequests().anyRequest().hasAnyAuthority("USER"); 
    } 
} 

在我的腦海裏hasAnyAuthority( 「USER」)後,應該有一個.permitAll()。但不要。

因此,freerest路徑工作正常,但如果我嘗試了一些用戶,這是對我的數據庫,或者默認Spring的用戶,我得到403

有什麼不對?

回答

1

試試這個。您在antMatch和任何請求之間添加了and()。我認爲這是問題。

並且還添加正確的身份驗證領域,然後添加and(),如下所示。 這裏我使用HTTP基本認證安心

@Configuration 
    @EnableWebSecurity 
    @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true) 
    public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{ 

     ...... 
     ...... 
     ...... 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http.csrf().disable() 
        .authorizeRequests() 
         .antMatchers("/freerest/**").permitAll() 
         .anyRequest().hasAnyAuthority("USER") 
        .and() 
        .httpBasic(); 
     } 

     ...... 
     ...... 
     ...... 

    } 
+0

感謝您的回答!它適用於我向我的用戶請求時,不再返回403.但是,如果我沒有基本認證請求,它也返回200。 像,如果我請localhost:8080 /香蕉沒有基本認證應該返回401或403 ... – 2015-03-31 19:39:33