【问题标题】:How to communicate with jwt enable service in microservice微服务中如何与jwt使能服务通信
【发布时间】:2018-02-23 06:58:41
【问题描述】:

我是 Spring Boot 微服务的新手,能够成功设置微服务项目。但是我尝试在有效的 Auth-Service 上实现 JWT,并且

@RestController
@RequestMapping("/token")
public class JwtController {
    @Autowired
    private JwtTokenGenerator jwtGenerator;

    //constructor
    public JwtController(JwtTokenGenerator jwtGenerator) {
        this.jwtGenerator = jwtGenerator;
    }

    @PostMapping
    public String generate(@RequestBody final JwtUser jwtUser) {

        return jwtGenerator.generate(jwtUser);

    }
}

可以从邮递员那里调用它

允许我访问服务页面

但是当我尝试访问相同的服务时

@RestController
@RequestMapping("/secure/logon")
public class LogOnController {

    @GetMapping
    public String logOn() {
        return "You are logon successfully";
    }
}

从 Eureka 发现服务到 Eureka Server

@SuppressWarnings("deprecation")
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "fallback", groupKey = "Hello",
            commandKey = "hello",
            threadPoolKey = "helloThread")
    @PostMapping(value = "/index")
    public String token() {
        String url = "http://user-service/token";
        return restTemplate.getForObject(url, String.class);
    }

        @GetMapping(value = "/logon")
        public String index() {
            String url = "http://user-service/secure/logon";
            return restTemplate.getForObject(url, String.class);
        }

        public String fallback(Throwable hystrixCommand) {
            return "User-Service Failed ";
        }
    }

我收到错误

请问通过 Eureka-discovery 服务访问 auth-service 的最佳方式是什么。

【问题讨论】:

    标签: java spring spring-boot netflix-eureka


    【解决方案1】:

    也许你的代码

    @PostMapping(value = "/index")
    public String token() {
        String url = "http://user-service/token";
        return restTemplate.getForObject(url, String.class);
    }
    

    应该改为

    @PostMapping(value = "/index")
    public String token(@RequestBody final JwtUser jwtUser) {
        String url = "http://user-service/token";
        return restTemplate.postForObject(url, jwtUser, String.class);
    }
    

    因为服务/token是一个PostRequest,所以你应该使用postForObject()。

    【讨论】:

    • 感谢您的回复。因此,根据您所做的更正,我的 Eureka 代理中也需要有 JwtUser 类,因为我的身份验证服务中已经有了它。
    猜你喜欢
    • 2017-12-31
    • 1970-01-01
    • 2020-08-19
    • 2023-01-30
    • 2022-10-02
    • 2018-05-07
    • 2019-03-26
    • 2019-11-23
    相关资源
    最近更新 更多