2017-07-14 68 views
0

我使用Spring 1.5.4引導,春季數據REST,春季安全。我創建映射到不需要身份驗證,因爲它從報告傳入文本短信網關使用的具體路徑@Controller調用安全方法,無需認證

所以我剛剛創建一個控制器來讀取這些參數,然後保存在數據庫中的文本。這裏有問題。爲了存儲數據,我使用安全的存儲庫,而在控制器中,我沒有任何安全性(事實上,我不能要求提供商確保其呼叫)。

我試圖以編程方式設置的驗證上下文,但似乎不工作:

@Controller 
@RequestMapping(path = "/api/v1/inbound") 
@Transactional 
public class InboundSmsController { 
    private Logger log = LogManager.getLogger(); 

@RequestMapping(method = RequestMethod.POST, path = "/incomingSms", produces = "text/plain;charset=ISO-8859-1") 
public ResponseEntity<?> incomingSms(@RequestParam(name = "Sender", required = true) String sender, 
     @RequestParam(name = "Destination", required = true) String destination, 
     @RequestParam(name = "Timestamp", required = true) String timestamp, 
     @RequestParam(name = "Body", required = true) String body) { 

    log.info(String.format("Text received from %s to %s at %s with content: %s", sender, destination, timestamp, body)); 
    setupAuthentication(); 

    try {      
     int transitsWithSameTextToday = transitCertificateRepository.countByTextAndDate(body, Instant.now()); //This is the method that raises an Auth exception 
.... 
.... 
} finally(){ 
    clearAuthentication(); 
} 


SecurityContext context; 

/** 
* Set in the actual context the authentication for the system user 
*/ 
private void setupAuthentication() { 
    context = SecurityContextHolder.createEmptyContext(); 
    Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_ADMIN"); 
    Authentication authentication = new UsernamePasswordAuthenticationToken("system", "ROLE_ADMIN", authorities); 
    context.setAuthentication(authentication); 
} 

private void clearAuthentication() { 
    context.setAuthentication(null); 
} 

的方法countByTextAndDate@PreAuthorize("isAuthenticated()")

註釋我很驚訝也設置驗證方面我有這個錯誤。難道我做錯了什麼?這是達到我的目標的最佳方式嗎?

我不想用@PermitAll註釋我的方法,因爲Spring Data REST也公開了這個方法,我不想讓任何人都可以使用它。

+0

就設置安全性,你通常會(這樣你有一個認證,一個匿名的一個,但仍然授權)和寫入特定方的安全規則。如'@PreAuthorize( 「isAuthenticated()|| hasIpAddress(<的顯式IP地址的從 - 的-SMS網關>)」)'。 –

回答