Spring boot 使用自定义登录控制器调用oauth/token

Spring boot 使用自定义登录控制器调用oauth/token,spring-boot,spring-security,spring-security-oauth2,Spring Boot,Spring Security,Spring Security Oauth2,我正在使用springboot2用spring安全性实现oauth2 当我直接调用oauth/token时,我就能得到结果。。。很好 我需要在我的自定义登录控制器中使其工作相同,从那里我可以将请求重定向到oauth/token以生成令牌。原因是我需要在数据库中存储访问令牌和登录时间 @RequestMapping(value = "/login", method = { RequestMethod.OPTIONS, RequestMethod.POST }) public Object logi

我正在使用springboot2用spring安全性实现oauth2

当我直接调用oauth/token时,我就能得到结果。。。很好

我需要在我的自定义登录控制器中使其工作相同,从那里我可以将请求重定向到oauth/token以生成令牌。原因是我需要在数据库中存储访问令牌和登录时间

@RequestMapping(value = "/login", method = { RequestMethod.OPTIONS, RequestMethod.POST })
public Object login(HttpServletRequest  request, HttpServletResponse     
            response, @RequestParam Map<String, String> params) {

//Here I want to make a call to oauth/token.

    }
@RequestMapping(value=“/login”,method={RequestMethod.OPTIONS,RequestMethod.POST})
公共对象登录(HttpServletRequest、HttpServletResponse
响应,@RequestParam映射参数){
//在这里,我想调用oauth/token。
}
请在这方面提供帮助。提前感谢。

RestTemplate RestTemplate=new RestTemplate();
RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "YOUR_BASIC");
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    String authURL = "YOUR_URL/oauth/token?grant_type=YOUR_GRANT_TYPE&username=" + YOUR_USERNAME + "&password=YOUR_PASSWORD&scope=ui";
    ResponseEntity<String> responseEntity = restTemplate.postForEntity(authURL, entity, String.class);
    JSONObject jsonObj = new JSONObject(responseEntity.getBody());
    jsonObj.get("access_token").toString();
HttpHeaders=新的HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set(“授权”、“您的基础”); HttpEntity=新的HttpEntity(“,标题); String authURL=“您的\ URL/oauth/token?授权类型=您的\授权类型和用户名=“+您的\用户名+”&密码=您的\密码和范围=用户界面”; ResponseEntity ResponseEntity=restTemplate.postForEntity(authURL,entity,String.class); JSONObject jsonObj=新的JSONObject(responseEntity.getBody()); jsonObj.get(“访问令牌”).toString();
依赖关系:

 <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180130</version>
</dependency>

org.json
json
20180130

请不要只是将代码作为答案发布,解释它的作用以及它解决问题的原因。这就是我们的自定义方法调用auth server的方式。在这里,我们可以记录令牌/时间等。