2017-09-05 11 views
0
  • 코드에 오류가없는 것 같습니다.
  • 이것은 테스트 앱이며 모든 ID를 사용할 수 있습니다.
  • getToken() 함수에서 getScopes()에 대한 회선 통화를 차단 해제하고 더 시도 할 수 있습니다.
  • 버튼이있는 index.jsp가 있습니다.
  • "oauthorize"버튼을 누르면 코드와 id_token이 생성됩니다.
  • 로그인 할 수 있으며 코드 및 id_token이 생성됩니다.
  • 이 값은 버튼이있는 "authtoken.jsp"에 표시됩니다.
  • 버튼을 /common/oauth2/v2.0/token에 게시합니다.
  • 이 단계에서 Microsoft 페이지에 400 개의 잘못된 요청이 표시됩니다.

은 내가 잘못 무슨 일이 일어나고 있는지 확실하지 않다 :액세스 토큰 용 Outlook API는 Java Spring에서 400 개의 잘못된 요청을 반환합니다.

import java.util.UUID; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpSession; 
import javax.servlet.http.HttpServletResponse; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.util.UriComponentsBuilder; 


@Controller 
public class IndexController { 

    //all oauth2 urls 
    private static final String authority = "https://login.microsoftonline.com"; 
    private static final String authorizeUrl = authority + "/common/oauth2/v2.0/authorize"; 
    private static final String tokenUrl = authority + "/common/oauth2/v2.0/token"; 
    private static final String redirectUrl = "http://localhost:8080/OutlookProfiles/authtoken"; 
    private static final String reTokenUrl = "http://localhost:8080/OutlookProfiles/showToken"; 

    //credentials 
    private static final String appId = "7414b3a3-26f1-4928-9d0b-7060d01dd41c"; 
    private static final String appPassword = "cQg9F0EaxuaErNp2YEgYaz8"; 

    private static final String[] scopes = { 
       "openid", 
       "offline_access", 
       "profile", 
       "User.Read", 
       "Contacts.Read", 
       "Mail.Read" 
       }; 


    @RequestMapping(value = "/index", method = RequestMethod.GET) 
    public String index(Model model, HttpServletRequest request, HttpServletResponse response){ 

     UUID state = UUID.randomUUID(); 
     UUID nonce = UUID.randomUUID(); 

     // Save the state and nonce in the session so we can 
     // verify after the auth process redirects back 

     HttpSession session = request.getSession(); 
     session.setAttribute("expected_state", state); 
     session.setAttribute("expected_nonce", nonce); 

     return "index"; 
    } 

    @RequestMapping(value = "/oauthorize", method = RequestMethod.POST) 
    public void oauthorize(Model model, HttpServletRequest servletRequest, HttpServletResponse servletResponse) { 

     try{ 

     UUID state = UUID.randomUUID(); 
     UUID nonce = UUID.randomUUID(); 

      HttpSession session = servletRequest.getSession(); 
      session.setAttribute("expected_state", state); 
      session.setAttribute("expected_nonce", nonce); 
      session.setAttribute("error", null); 

     UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(authorizeUrl); 
     urlBuilder.queryParam("client_id", appId); 
     urlBuilder.queryParam("redirect_uri", redirectUrl); 
     urlBuilder.queryParam("response_type", "code id_token"); 
     urlBuilder.queryParam("scope", getScopes()); 
     urlBuilder.queryParam("state", state); 
     urlBuilder.queryParam("nonce", nonce); 
     urlBuilder.queryParam("response_mode", "form_post"); 

     String locationUri = urlBuilder.toUriString(); 
     System.out.println(locationUri); 

     servletResponse.sendRedirect(locationUri); 

     }catch(Exception e){ 
      e.printStackTrace(); 
     } 

    } 


    @RequestMapping(value = "/authtoken", method = RequestMethod.POST) 
    public String authorize(
       @RequestParam("code") String code, 
       @RequestParam("id_token") String idToken, 
       @RequestParam("state") UUID state, 
       HttpServletRequest servletRequest, 
       HttpServletResponse servletResponse) { 

     // Get the expected state value from the session 
     HttpSession session = servletRequest.getSession(); 
     UUID expectedState = (UUID) session.getAttribute("expected_state"); 
     UUID expectedNonce = (UUID) session.getAttribute("expected_nonce"); 


     String strState = state.toString().trim().toLowerCase(); 
     String strExState = expectedState.toString().trim().toLowerCase(); 


     // Make sure that the state query parameter returned matches 
     // the expected state 
     if (strState.equals(strExState)){ 
      session.setAttribute("authCode", code); 
      session.setAttribute("idToken", idToken); 
      System.out.println("Expectedstate : NO Error"); 
     }else { 
      session.setAttribute("error", "Unexpected state returned from authority."); 
      System.out.println("\n\nUnexpected state returned from authority."); 
     } 

     return "authtoken"; 
    } 

    @RequestMapping(value = "/getToken", method = RequestMethod.POST) 
    public void getToken(
      HttpServletRequest servletRequest, 
      HttpServletResponse servletResponse) { 

     try{ 

     HttpSession session = servletRequest.getSession(); 
     String strCode = (String) session.getAttribute("authCode"); 

     UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(tokenUrl); 
     urlBuilder.queryParam("client_id", appId); 
     urlBuilder.queryParam("client_secret", appPassword); 
     urlBuilder.queryParam("code", strCode); 
     urlBuilder.queryParam("redirect_uri", redirectUrl); 
     urlBuilder.queryParam("grant_type", "authorization_code"); 
     urlBuilder.queryParam("scope", getScopes()); 

     String locationUri = urlBuilder.toUriString(); 
     System.out.println("getToken : " + locationUri); 

     servletResponse.setHeader("Content-Type", "application/x-www-form-urlencoded"); 

     servletResponse.sendRedirect(locationUri); 

     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
    } 

    @RequestMapping(value = "/showToken", method = RequestMethod.POST) 
    public String showToken(
      @RequestParam("token_type") String code, 
      @RequestParam("expires_in") String idToken, 
      @RequestParam("access_token") String accessToken, 
      //@RequestParam("scope") String paramScope, 
      HttpServletRequest servletRequest, 
      HttpServletResponse servletResponse) { 

     return "getToken"; 

    } 

    @RequestMapping("/logout") 
    public String logout(HttpServletRequest request) { 
     HttpSession session = request.getSession(); 
     session.invalidate(); 
     return "index"; 
    } 

    private static String getScopes() { 
      StringBuilder sb = new StringBuilder(); 
      for (String scope: scopes) { 
       sb.append(scope + " "); 
      } 

      String strscope = sb.toString().trim(); 
      System.out.println(strscope); 

      return strscope; 
    } 
} 

400 오류가 아무 이유없이 내 머리를 엉망으로되어있다. 액세스 토큰에 대한

+1

난 당신의 코드에서 스윙의 사용을 볼 수 없습니다 ... 작업 코드입니다. 봄을 의미 했습니까? – pcarter

+0

감사합니다. Swing에서 Spring으로 오타를 수정했습니다. –

답변

0
  • 마이크로 소프트 아웃룩 API 엔드 포인트 : https://login.microsoftonline.com/common/oauth2/v2.0/token 는 양식 기반 POST 즉 응용 프로그램/x-www-form-urlencoded를 기대하고있다. 모든 입력 매개 변수를 기반 양식하고 안 의미
  • 코드 대신 JSON을 기반으로 사용하거나 HttpClient를 사용하여 기반 접근 방식을 형성한다 UriComponentsBuilder
  • 코드를 사용하여 잘못 그래서 기술적으로
  • 을 추가하고 HttpPost 또는 OKHttp3 기반을 사용하여 URL OKHttpClient 및 RequestBody.

곧 작업 코드를 게시합니다.

는 ... 여기

import java.util.List; 
import java.util.ArrayList; 
import java.util.UUID; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpSession; 
import javax.servlet.http.HttpServletResponse; 

import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.HttpClients; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.util.EntityUtils; 
import org.json.JSONArray; 
import org.json.JSONObject; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.util.UriComponentsBuilder; 


@Controller 
public class IndexController { 

    //all oauth2 urls 
    private static final String authority = "https://login.microsoftonline.com"; 
    private static final String authorizeUrl = authority + "/common/oauth2/v2.0/authorize"; 
    private static final String tokenUrl = authority + "/common/oauth2/v2.0/token"; 
    private static final String redirectUrl = "http://localhost:8080/OutlookProfiles/authtoken"; 
    private static final String reTokenUrl = "http://localhost:8080/OutlookProfiles/showToken"; 

    //credentials 
    private static final String appId = "7414b3a3-26f1-4928-9d0b-7060d01dd41c"; 
    private static final String appPassword = "cQg9F0EaxuaErNp2YEgYaz8"; 

    private static final String[] scopes = { 
       "openid", 
       "offline_access", 
       "profile", 
       "User.Read", 
       "Contacts.Read", 
       "Mail.Read" 
       }; 


    @RequestMapping(value = "/index", method = RequestMethod.GET) 
    public String index(Model model, HttpServletRequest request, HttpServletResponse response){ 

     UUID state = UUID.randomUUID(); 
     UUID nonce = UUID.randomUUID(); 

     // Save the state and nonce in the session so we can 
     // verify after the auth process redirects back 

     HttpSession session = request.getSession(); 
     session.setAttribute("expected_state", state); 
     session.setAttribute("expected_nonce", nonce); 

     return "index"; 
    } 

    @RequestMapping(value = "/oauthorize", method = RequestMethod.POST) 
    public void oauthorize(Model model, HttpServletRequest servletRequest, HttpServletResponse servletResponse) { 

     try{ 

     UUID state = UUID.randomUUID(); 
     UUID nonce = UUID.randomUUID(); 

      HttpSession session = servletRequest.getSession(); 
      session.setAttribute("expected_state", state); 
      session.setAttribute("expected_nonce", nonce); 
      session.setAttribute("error", null); 

     UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(authorizeUrl); 
     urlBuilder.queryParam("client_id", appId); 
     urlBuilder.queryParam("redirect_uri", redirectUrl); 
     urlBuilder.queryParam("response_type", "code id_token"); 
     urlBuilder.queryParam("scope", getScopes()); 
     urlBuilder.queryParam("state", state); 
     urlBuilder.queryParam("nonce", nonce); 
     urlBuilder.queryParam("response_mode", "form_post"); 

     String locationUri = urlBuilder.toUriString(); 
     System.out.println(locationUri); 

     servletResponse.sendRedirect(locationUri); 

     }catch(Exception e){ 
      e.printStackTrace(); 
     } 

    } 


    @RequestMapping(value = "/authtoken", method = RequestMethod.POST) 
    public String authorize(
       @RequestParam("code") String code, 
       @RequestParam("id_token") String idToken, 
       @RequestParam("state") UUID state, 
       HttpServletRequest servletRequest, 
       HttpServletResponse servletResponse) { 

     // Get the expected state value from the session 
     HttpSession session = servletRequest.getSession(); 
     UUID expectedState = (UUID) session.getAttribute("expected_state"); 
     UUID expectedNonce = (UUID) session.getAttribute("expected_nonce"); 


     String strState = state.toString().trim().toLowerCase(); 
     String strExState = expectedState.toString().trim().toLowerCase(); 


     // Make sure that the state query parameter returned matches 
     // the expected state 
     if (strState.equals(strExState)){ 
      session.setAttribute("authCode", code); 
      session.setAttribute("idToken", idToken); 
      System.out.println("Expectedstate : NO Error"); 
     }else { 
      session.setAttribute("error", "Unexpected state returned from authority."); 
      System.out.println("\n\nUnexpected state returned from authority."); 
     } 

     return "authtoken"; 
    } 

    @RequestMapping(value = "/getToken", method = RequestMethod.POST) 
    public void getToken(
      HttpServletRequest servletRequest, 
      HttpServletResponse servletResponse) { 

     try{ 

     HttpSession session = servletRequest.getSession(); 
     String strCode = (String) session.getAttribute("authCode"); 

     HttpClient httpClient = HttpClients.createDefault(); 
     HttpPost httpPost = new HttpPost(tokenUrl); 
     httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); 
      List <BasicNameValuePair> params = new ArrayList<>(); 
      params.add(new BasicNameValuePair("client_id", appId)); 
      params.add(new BasicNameValuePair("client_secret", appPassword)); 
      params.add(new BasicNameValuePair("redirect_uri", redirectUrl)); 
      params.add(new BasicNameValuePair("code", strCode)); 
      params.add(new BasicNameValuePair("grant_type", "authorization_code")); 

      httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); 
      httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      org.apache.http.HttpEntity entity = httpResponse.getEntity(); 
      //String theString = IOUtils.toString(entity.getContent(), "UTF-8"); 
      String strResponse = EntityUtils.toString(entity, "UTF-8"); 
      System.out.println(strResponse); 
      strResponse = "{\"response\":["+strResponse+"]}"; 
      System.out.println(strResponse); 

      JSONObject result = new JSONObject(strResponse); //Convert String to JSON Object 
      JSONArray tokenList = result.getJSONArray("response"); 
      JSONObject objJson = tokenList.getJSONObject(0); 
      String accessToken = objJson.getString("access_token"); 
      System.out.println(accessToken); 

      session.setAttribute("accessToken", accessToken); 

     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
    } 

    @RequestMapping(value = "/showToken", method = RequestMethod.POST) 
    public String showToken(
      @RequestParam("token_type") String code, 
      @RequestParam("expires_in") String idToken, 
      @RequestParam("access_token") String accessToken, 
      //@RequestParam("scope") String paramScope, 
      HttpServletRequest servletRequest, 
      HttpServletResponse servletResponse) { 

     return "getToken"; 

    } 

    @RequestMapping("/logout") 
    public String logout(HttpServletRequest request) { 
     HttpSession session = request.getSession(); 
     session.invalidate(); 
     return "index"; 
    } 

    private static String getScopes() { 
      StringBuilder sb = new StringBuilder(); 
      for (String scope: scopes) { 
       sb.append(scope + " "); 
      } 

      String strscope = sb.toString().trim(); 
      System.out.println(strscope); 

      return strscope; 
    } 
}