如何与jwt通信在微服务中启用服务

时间:2018-02-23 06:58:42

标签: java spring spring-boot netflix-eureka

我是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);

    }
}

能够从邮递员那里调用它

enter image description here

允许我访问服务页面

enter image description here

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

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

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

从Eureka发现服务到Eureka服务器

@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 ";
        }
    }

我收到错误

enter image description here

请通过Eureka-discovery服务访问身份验证服务的最佳方式是什么。

1 个答案:

答案 0 :(得分:0)

也许你的代码

@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);
}

因为服务/令牌是PostRequest,所以你应该使用postForObject()。