无需身份验证即可从Spring控制器调用安全方法

时间:2017-07-14 17:52:06

标签: spring spring-mvc spring-security

我使用Spring Boot 1.5.4,Spring Data REST,Spring Security。我创建了一个@Controller映射到一个不需要身份验证的特定路径,因为它从短信网关用于报告传入文本。

所以我只是创建一个控制器来读取这些参数,然后将文本保存在db上。这里有问题。为了存储数据,我使用了安全的存储库,而在控制器中,我没有任何安全性(实际上我不能要求提供商保护其调用)。

我尝试以编程方式设置身份验证上下文,但似乎无效:

@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也公开了这种方法,我不希望任何人都可以使用它。

1 个答案:

答案 0 :(得分:0)

您正在寻找AccessDecisionManager的RunAsManager。以下是可以帮助您解决此问题的链接: http://www.baeldung.com/spring-security-run-as-auth

快乐编码!!!

相关问题