![](/img/trans.png)
[英]Invoke and load Spring MVC controller request method from Thymeleaf
[英]Invoke secured method from Spring controller without authentication
我正在使用Spring Boot 1.5.4,Spring Data REST,Spring Security。 我創建了一個@Controller
映射到不需要身份驗證的特定路徑,因為它是從sms網關用於報告傳入文本的。
因此,我只是創建一個控制器來讀取這些參數,然后將文本保存在數據庫中。 這就是問題所在。 為了存儲數據,我使用了受保護的存儲庫,而在控制器中卻沒有任何安全性(實際上,我不能要求提供者保護其調用的安全)。
我試圖以編程方式設置身份驗證上下文,但似乎無法正常工作:
@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()")
批注
我很驚訝也將Auth上下文設置為此錯誤。 難道我做錯了什么? 這是實現我的目標的最佳方法嗎?
我不想用@PermitAll
注釋我的方法,因為Spring Data REST也公開了該方法,我不希望任何人都可以使用它。
您正在尋找AccessDecisionManager
的RunAsManager。 這是可以幫助您的鏈接: http : //www.baeldung.com/spring-security-run-as-auth
快樂編碼!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.