2017-08-24 131 views
0

在以下延續WebSecurityConfigurerAdapter的類中,我覆蓋了configure(HttpSecurity)方法。彈簧安全性WebSecurityConfigurerAdapter配置問題

@Configuration 
@EnableGlobalMethodSecurity(securedEnabled = true) 
public class SecurityConfig extends WebSecurityConfigurerAdapter{ 

@Autowired 
public void configureAuth(AuthenticationManagerBuilder auth) throws Exception { 
    auth 
      .inMemoryAuthentication() 
      .withUser("fabio") 
      .password("123") 
      .roles("ADMIN") 
     .and() 
      .withUser("joe") 
      .password("123") 
      .roles("GUEST"); 

} 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
      .authorizeRequests() 
       .antMatchers("/post/list").permitAll() 
       .antMatchers("/admin/**").hasRole("ADMIN") 
       .anyRequest().authenticated() 
      .and() 
      .formLogin() 
      .and() 
      .logout(); 
} 
} 

有了這個,我應該能夠得到localhost:8080/post/list頁面,而無需承諾一個用戶登錄,因爲它有.permitAll(),但是當我試圖進入它,它總是先提示登錄頁面後,才我輸入以前的憑證,我可以查看它。我怎樣才能解決這個問題 ?

控制器類

@RestController 
@RequestMapping("/post") 
public class HomeController { 

    @Secured("ROLE_GUEST") 
    @RequestMapping("/list") 
    public String list(){ 
    return "list..."; 
    } 

    @Secured("ROLE_USER") 
    @RequestMapping("/drafts") 
    public String drafts(){ 
     return "drafts..."; 
    } 

    @Secured({"ROLE_ADMIN","ROLE_USER"}) 
    @RequestMapping("/add") 
    public String add(){ 
     return "adding..."; 
    } 

} 
+0

嘗試使用'.antMatchers(「/ post/list **」)。permitAll()' –

+0

它不起作用 – MrSir

回答

0

按照@RequestMapping定義有衝突,因爲它是由註釋@Secured("ROLE_GUEST")擔保,而且你需要.permitAll()配置來訪問它。

選項1:刪除@Secured("ROLE_GUEST")以便讓.permitAll()完成工作。

選項2:在@RequestMapping("/list")上使用@Secured("ROLE_ANONYMOUS")而不是@Secured("ROLE_GUEST")。你可以看到在Spring Documentation


它將取決於/post/list之後的路徑值ROLE_ANONYMOUS定義。請參閱以下關於如何根據路徑值定義antMatchers的示例。

localhost:8080/post/list = .antMatchers("/post/list").permitAll()

localhost:8080/post/list/stuff = .antMatchers("/post/list/**").permitAll()

localhost:8080/post/listlocalhost:8080/post/list1234

= .antMatchers("/post/list**").permitAll()

有關詳細信息訪問AnthPathMatcher文檔和HttpSecurity

+0

就是這個'localhost:8080/post/list',是不是應該與我的代碼一起工作? – MrSir

+0

是的,它是如何工作的,只要確定某件事情,如何聲明'@ RequestMapping'處理程序的路徑?你能提供嗎?也訪問這個帖子https://stackoverflow.com/questions/29721098/enableglobalmethodsecurity-vs-enablewebsecurity#29721230 –

+0

我編輯了@RequestMapping s的帖子 – MrSir