身份验证Microsoft OneDrive REST服务Java/ionic 2



我正在尝试向Microsoft OneDrive进行身份验证,并在我的应用程序中使用REST服务,使用Java进行后端和Ionic2。如果我直接从Chrome调用我的服务,则身份验证现在可以使用。我发布代码:

private static final String REDIRECT_URI = "http://localhost:8080/CloudToCloud/onedrive/getToken";
@RequestMapping(value = { "/getAccess" }, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public void authorizationFlow(HttpServletRequest request, HttpServletResponse response)
        throws IOException, InterruptedException {
    try {
        String authURL = "https://login.live.com/oauth20_authorize.srf?client_id=" + CLIENT_ID
                + "&scope=wl.signin%20wl.basic%20wl.offline_access%20wl.skydrive_update&response_type=code&redirect_uri="
                + REDIRECT_URI;
        response.sendRedirect(authURL);
    } catch (Exception e) {
        logger.severe(e.getMessage());
    }
}
@RequestMapping(value = { "/getToken" }, params = { "code" }, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<JSONObject> getToken(@RequestParam("code") String code)
        throws IOException, InterruptedException, ParseException {
    JSONObject json = null;
    try {
        logger.info("Auth CODE: " + code);
        String url = "https://login.live.com/oauth20_token.srf";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        String urlParameters = "client_id=" + CLIENT_ID + "&" + "redirect_uri=" + REDIRECT_URI + "&"
                + "client_secret=" + SECRET + "&" + "code=" + code + "&" + "grant_type=authorization_code";
        logger.info(url + urlParameters);
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        logger.info("REQUEST SENT. Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        String risposta = response.toString();
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(risposta);
        String token = json.get("access_token").toString();
        FileWriter file = new FileWriter(DATA_STORE_DIR);
        file.write(json.toJSONString());
        logger.info("nTOKEN:n" + token);
        file.flush();
        file.close();
        return new ResponseEntity<JSONObject>(json, HttpStatus.OK);
    } catch (Exception e) {
        logger.info("ERRORE: " + e.getMessage());
        return new ResponseEntity<JSONObject>(HttpStatus.BAD_REQUEST);
    }
}

我致电第一个服务,我得到了一个代码,然后在第二个服务上重定向,这为我提供了带有令牌的JSON,用于所有其他呼叫。为此,一切都起作用。问题是使用离子2。我发布代码:

服务:

getAuthOneDrive(){
  var url = 'http://localhost:8080/CloudToCloud/onedrive/getAccess';
  var response = this.http.get(url).map(res => res.json());
  return response;
}

组件:

getAuthOneDrive(){
  this.cloudServiceAuthentication.getAuthOneDrive().subscribe(
    err => {
      console.log(err);
    },
    () => console.log('getAuthOneDrive Complete')
  );
}

和我的代理,我在ionic.config.json中配置了:

{
  "name": "C2C",
  "app_id": "c6203dd8",
  "v2": true,
  "typescript": true,
  "proxies": [
    {
      "path": "/",
      "proxyUrl": "http://localhost:8080/"
    }
  ]
}   

如果我尝试调用相同的服务(http://localhost:8080/cloudtocloud/oneedrive/getAcces),从ionic2中的应用程序单击一个按钮,我会收到此错误。

>
XMLHttpRequest cannot load http://localhost:8080/CloudToCloud/onedrive/getAccess. Redirect from 'http://localhost:8080/CloudToCloud/onedrive/getAccess' to 'https://login.live.com/oauth20_authorize.srf?client_id=ae9573ba-6bc0-4a87-8…ype=code&redirect_uri=http://localhost:8080/CloudToCloud/onedrive/getToken' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

我真的尝试了一切。如果有人能给我帮助,我将感谢。谢谢!;)

编辑:

这是我尝试做的:1-添加"'Access-Control-Allow-Origin','*'标题,我有一个错误:

XMLHttpRequest cannot load http://localhost:8080/CloudToCloud/onedrive/getAccess. Redirect from 'http://localhost:8080/CloudToCloud/onedrive/getAccess' to 'https://login.live.com/oauth20_authorize.srf?client_id=ae9573ba-6bc0-4a87-8…ype=code&redirect_uri=http://localhost:8080/CloudToCloud/onedrive/getToken' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

2-请勿使用响应。在第一份服务中进行索引,而是通过httpsurlconnection或spring restTemplate满足请求;3-尝试直接从Ionic致电Microsoft服务;4-使用弹簧注释@Crossorigin,但我有同样的错误。

出于安全原因,浏览器限制了交叉原始请求。查看HTTP访问控制(CORS),以详细说明其工作原理。

设置以下标题应允许您解决开发问题:

Access-Control-Allow-Origin: *

只需确保在生产部署中删除此标头(或至少将其限制在'*'之外)即可。

i通过修改第一个服务/getAccess,添加标头访问控制和使用我的redirect_uri,并且不再给出问题。

@CrossOrigin(origins = "*")
@RequestMapping(value = { "/getAccess" }, method = RequestMethod.GET)
public void authenticate() throws IOException {
    try {
        OneDriveSDK sdk = OneDriveFactory.createOneDriveSDK(CLIENT_ID, SECRET, REDIRECT_URI,
                OneDriveScope.READWRITE);
        String url = sdk.getAuthenticationURL();
        logger.info(url);
        openWebpage(url);
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Access-Control-Allow-Origin", "*");
        con.setDoOutput(true);
        int responseCode = con.getResponseCode();
        logger.info("REQUEST SENT. Response Code : " + responseCode);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

最新更新