2017-05-23 26 views
-1
@RestController 
public class AccountController { 

    @PermitAll 
    @RequestMapping(value = "/test") 
    public ResponseEntity<String> test() { 
     // ... 
    } 

    @RolesAllowed("ROLE_ADMIN) 
    @RequestMapping(value = "/products") 
    public ResponseEntity<List<Product>> products() { 
     // ... 
    } 
} 

如何配置Spring引導到能夠訪問「/測試」沒有認證,但「/產品」認證和檢查權限/角色?保護端點由權利/角色

在配置中可能沒有提及@PermitAll的路徑(如「/ test」)嗎?

+1

您是否嘗試過做定製_WebSecurityConfigurerAdapter_? –

+0

沒有。你有一個例子嗎? – Romper

回答

-1

你可以做它提供下一個配置類。在這種情況下,一切都可以訪問,如果不受註釋的限制。

@EnableWebSecurity 
@EnableGlobalMethodSecurity(securedEnabled = true) 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
       .authorizeRequests().anyRequest().permitAll(); 
    } 

} 

檢查SecurityConfig class here瞭解更多配置選項。

+0

驗證過程如何,您可以提供身份驗證和@ PermitAll/@ RolesAllowed示例嗎?謝謝。 – Romper

+0

你能描述一下你的認證是什麼意思嗎?通過這個配置,您可以使用'@ Secured'註釋來控制訪問。要獲得更完整的安全配置(使用自定義UserDetailsS​​erviceImp),請檢查答案中的鏈接(https://stackoverflow.com/questions/43861189/what-is-the-best-practice-to-salt-a-password-with- spring-security-in-spring-boot/43875887#43875887) – dimuha

-1

問題:春天引導到能夠訪問 「/測試」 沒有認證,但 「/產品」 身份驗證
解決方案

http.authorizeRequests().antMatchers("/test").permitAll() 
.antMatchers("/products").hasRole("ADMIN").anyRequest().authenticated().and().httpBasic(); 

注意:默認情況下,當你添加spring安全性,它要求對所有url進行身份驗證,並且您需要指定您不需要身份驗證的身份驗證。例如/登錄應該是permitAll。

Click here for Source code of security configuration

參考樣品HttpSecurity樣本如下更多的匹配例如,

Refer

有關詳細信息:https://docs.spring.io/spring-security/site/docs/current/reference/html/jc.html

+0

在配置中是否可能沒有提及@PermitAll的路徑(如「/ test」)?我不想在控制器和配置中兩次提及「/ test」。 – Romper

+0

如果您在WebSecurityConfig中爲路徑配置HttpSecurity,則不需要在控制器部分添加任何內容。 –

+0

即使@RequestMapping?那麼春天怎麼會知道要調用什麼方法? – Romper