简体   繁体   English

如何在 Micronaut 中从我的 controller 调用另一个 rest api

[英]How to call another rest api from my controller in Micronaut

From this artcle , I have implemented calling another rest API from my REST API method in micronaut gradle application. From this artcle , I have implemented calling another rest API from my REST API method in micronaut gradle application. Since my REST API expects jwt token I am sending the same token I received with in current request.由于我的 REST API 需要 jwt 令牌,因此我发送的令牌与我在当前请求中收到的令牌相同。 I am seeing Unauthorized error even token is being passed.我看到未经授权的错误,即使令牌正在传递。 Can anyone help in this regard.任何人都可以在这方面提供帮助。 Below is my code.下面是我的代码。

import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpStatus;
import io.appter.clientmgmt.models.ClientContact;
import io.appter.clientmgmt.repositories.IClientContactRepository;
import io.micronaut.http.uri.UriTemplate;
import io.micronaut.security.annotation.Secured;
import io.micronaut.security.authentication.Authentication;
import io.micronaut.security.rules.SecurityRule;
import io.micronaut.http.annotation.*;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;
import io.reactivex.Flowable;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import javax.validation.constraints.NotNull;
import java.security.Security;
import java.util.List;


@Controller("/clientcontact")
//@Secured(SecurityRule.IS_ANONYMOUS)
public class ClientContactController {
    private static final Logger LOG = LoggerFactory.getLogger(ClientContactController.class);
    private IClientContactRepository clientContactRepository;
    private final RxHttpClient httpClient;

    public ClientContactController(IClientContactRepository clientContactRepository,
                                   @Client("http://appterauthsvc-env.g2yapp2kcp.us-east-1.elasticbeanstalk.com") RxHttpClient httpClient) {
        this.clientContactRepository = clientContactRepository;
        this.httpClient = httpClient;
    }

    @Get("/")
    public HttpStatus index() {
        return HttpStatus.OK;
    }

    @Post("/")
    @Secured(SecurityRule.IS_AUTHENTICATED)
    public ClientContact createClientContact(@Body ClientContact clientContact,
                                             Authentication authentication,
                                             @Header("Authorization") String authorization) {
        try {
            List<ClientContact> existingClientContacts = clientContactRepository.getClientContactByClientId(clientContact.getClientId());
            LOG.info("current contacts count for the client " + clientContact.getClientId() + " is " + existingClientContacts.size());
            if (existingClientContacts.isEmpty()) {

                User userObj = new User();
                Long clientId = new Long(clientContact.getClientId());
                userObj.setClientId(clientId);
                userObj.setFirstName(clientContact.getFirstName());
                userObj.setLastName(clientContact.getLastName());
                userObj.setEmailId(clientContact.getEmailAddress());
                userObj.setPhoneNo(clientContact.getContactNumber());
                userObj.setIsActive(true);

                LOG.info("User Email set is: "+userObj.getEmailId());
                LOG.info("authorization token is: "+authorization);
                HttpRequest<?> request = HttpRequest.POST("/user", userObj).bearerAuth(authorization);

                String response = httpClient.toBlocking().retrieve(request);
                LOG.info("Request Object: "+ request.toString());
                LOG.info("Response Object: "+ response.toString());
                LOG.info("User API executed.. ");
            }


            return clientContactRepository.createClientContact(clientContact);
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
            return null;
        }
    }
}

Thanks in advance.提前致谢。

Likely because @Header("Authorization") String authorization is returning something like Bearer xyz... and the bearerAuth method is adding Bearer to the string so you are sending Bearer Bearer xyz...可能是因为@Header("Authorization") String authorization正在返回类似Bearer xyz...的内容,而bearerAuth方法正在将Bearer添加到字符串中,因此您正在发送Bearer Bearer xyz...

So just do .header(HttpHeaders.AUTHORIZATION, authorization)所以只要做.header(HttpHeaders.AUTHORIZATION, authorization)

Also as a side note you really shouldn't be doing blocking HTTP calls in this method.另外作为旁注,您真的不应该在此方法中阻止 HTTP 调用。 It's not the end of the world since in this case you're blocking an IO thread, however this type of code should be avoided.这不是世界末日,因为在这种情况下您会阻塞 IO 线程,但是应该避免使用这种类型的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM