Hướng dẫn api token python - mã thông báo api python

Chuyển đến nội dung chính

Trình duyệt này không còn được hỗ trợ nữa.

Hãy nâng cấp lên Microsoft Edge để tận dụng các tính năng mới nhất, bản cập nhật bảo mật và hỗ trợ kỹ thuật.

A web app that calls web APIs: Acquire a token for the app

  • Bài viết
  • 06/22/2022
  • 4 phút để đọc

Trong bài viết này

You've built your client application object. Now, you'll use it to acquire a token to call a web API. In ASP.NET or ASP.NET Core, calling a web API is done in the controller:

  • Get a token for the web API by using the token cache. To get this token, you call the Microsoft Authentication Library (MSAL) AcquireTokenSilent method (or the equivalent in Microsoft.Identity.Web).
  • Call the protected API, passing the access token to it as a parameter.

  • ASP.NET Core
  • Asp.net
  • Java
  • Python

Microsoft.identity.Web thêm các phương thức mở rộng cung cấp các dịch vụ tiện lợi để gọi Microsoft Graph hoặc API Web xuôi dòng. Các phương thức này được giải thích chi tiết trong một ứng dụng web gọi API Web: Gọi API. Với các phương pháp trợ giúp này, bạn không cần phải có được mã thông báo theo cách thủ công.

Tuy nhiên, nếu bạn muốn có được mã thông báo theo cách thủ công, mã sau đây hiển thị một ví dụ về việc sử dụng Microsoft.identity.web để làm như vậy trong bộ điều khiển gia đình. Nó gọi Microsoft Graph bằng API REST (thay vì SDK của Microsoft Graph). Nhận mã thông báo để gọi API hạ nguồn, bạn đã tiêm dịch vụ ITokenAcquisition bằng cách tiêm phụ thuộc vào hàm tạo của bộ điều khiển (hoặc hàm tạo trang của bạn nếu bạn sử dụng blazor) và bạn sử dụng nó trong các hành động của bộ điều khiển, nhận mã thông báo cho người dùng (GetAccessTokenForUserAsync ) hoặc cho chính ứng dụng (GetAccessTokenForAppAsync) trong một kịch bản daemon.

Các phương thức điều khiển được bảo vệ bởi thuộc tính [Authorize] mà chỉ đảm bảo người dùng được xác thực mới có thể sử dụng ứng dụng web.

[Authorize]
public class HomeController : Controller
{
 readonly ITokenAcquisition tokenAcquisition;

 public HomeController(ITokenAcquisition tokenAcquisition)
 {
  this.tokenAcquisition = tokenAcquisition;
 }

 // Code for the controller actions (see code below)

}

Dịch vụ ITokenAcquisition được ASP.NET tiêm bằng cách sử dụng tiêm phụ thuộc.

Đây là mã đơn giản hóa cho hành động của

[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public async Task Profile()
{
 // Acquire the access token.
 string[] scopes = new string[]{"user.read"};
 string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);

 // Use the access token to call a protected web API.
 HttpClient client = new HttpClient();
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 string json = await client.GetStringAsync(url);
}
1, có mã thông báo để gọi Microsoft Graph:

[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public async Task Profile()
{
 // Acquire the access token.
 string[] scopes = new string[]{"user.read"};
 string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);

 // Use the access token to call a protected web API.
 HttpClient client = new HttpClient();
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 string json = await client.GetStringAsync(url);
}

Để hiểu rõ hơn về mã cần thiết cho kịch bản này, hãy xem bước Giai đoạn 2 (ứng dụng 2-1-WEB gọi Microsoft Graph) của hướng dẫn hướng dẫn MS-Ididity-AspNetCore-Webapp.

Thuộc tính

[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public async Task Profile()
{
 // Acquire the access token.
 string[] scopes = new string[]{"user.read"};
 string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);

 // Use the access token to call a protected web API.
 HttpClient client = new HttpClient();
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 string json = await client.GetStringAsync(url);
}
2 trên đỉnh của hành động bộ điều khiển (hoặc của trang dao cạo nếu bạn sử dụng mẫu dao cạo) được cung cấp bởi Microsoft.identity.web. Nó đảm bảo rằng người dùng được yêu cầu đồng ý nếu cần và tăng dần.

Có các biến thể phức tạp khác, chẳng hạn như:

  • Gọi một số API.
  • Xử lý sự đồng ý gia tăng và truy cập có điều kiện.

Các bước nâng cao này được đề cập trong Chương 3 của hướng dẫn 3-Webapp-Multi-Apis.

Mã cho ASP.NET tương tự như mã được hiển thị cho ASP.NET Core:

  • Một hành động của bộ điều khiển, được bảo vệ bởi một thuộc tính [ủy quyền], trích xuất ID người thuê và ID người dùng của thành viên
    [AuthorizeForScopes(Scopes = new[] { "user.read" })]
    public async Task Profile()
    {
     // Acquire the access token.
     string[] scopes = new string[]{"user.read"};
     string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
    
     // Use the access token to call a protected web API.
     HttpClient client = new HttpClient();
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
     string json = await client.GetStringAsync(url);
    }
    
    3 của bộ điều khiển. (ASP.NET sử dụng
    [AuthorizeForScopes(Scopes = new[] { "user.read" })]
    public async Task Profile()
    {
     // Acquire the access token.
     string[] scopes = new string[]{"user.read"};
     string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
    
     // Use the access token to call a protected web API.
     HttpClient client = new HttpClient();
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
     string json = await client.GetStringAsync(url);
    }
    
    4.)
  • Từ đó, nó xây dựng một đối tượng msal.net
    [AuthorizeForScopes(Scopes = new[] { "user.read" })]
    public async Task Profile()
    {
     // Acquire the access token.
     string[] scopes = new string[]{"user.read"};
     string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
    
     // Use the access token to call a protected web API.
     HttpClient client = new HttpClient();
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
     string json = await client.GetStringAsync(url);
    }
    
    5.
  • Cuối cùng, nó gọi phương thức AcquireTokenSilent của ứng dụng máy khách bí mật.
  • Nếu cần phải tương tác, ứng dụng web cần thách thức người dùng (ký lại) và yêu cầu thêm các khiếu nại.

Ghi chú

Phạm vi nên là tên phạm vi đủ điều kiện. Ví dụ, ________ 17.

Đoạn mã sau được trích xuất từ ​​homecontroll.cs#L157-L192 trong MS-Identity-Aspnet-Webapp-OpenidConnect ASP.NET MVC Mẫu mã:

public async Task ReadMail()
{
    IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();
    AuthenticationResult result = null;
    var account = await app.GetAccountAsync(ClaimsPrincipal.Current.GetMsalAccountId());
    string[] scopes = { "Mail.Read" };

    try
    {
        // try to get token silently
        result = await app.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false);
    }
    catch (MsalUiRequiredException)
    {
        ViewBag.Relogin = "true";
        return View();
    }

    // More code here
    return View();
}

Để biết chi tiết, hãy xem mã cho BuildConfidialClientApplication () và GetMsalAccountId trong mẫu mã

Trong mẫu Java, mã gọi API nằm trong phương thức GetUsersFromGraph trong AuthPageControll.java#L62.

Phương pháp cố gắng gọi

[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public async Task Profile()
{
 // Acquire the access token.
 string[] scopes = new string[]{"user.read"};
 string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);

 // Use the access token to call a protected web API.
 HttpClient client = new HttpClient();
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 string json = await client.GetStringAsync(url);
}
8. Nếu người dùng cần đồng ý với nhiều phạm vi hơn, mã sẽ xử lý đối tượng
[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public async Task Profile()
{
 // Acquire the access token.
 string[] scopes = new string[]{"user.read"};
 string accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);

 // Use the access token to call a protected web API.
 HttpClient client = new HttpClient();
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 string json = await client.GetStringAsync(url);
}
9 để thách thức người dùng.

@RequestMapping("/msal4jsample/graph/me")
public ModelAndView getUserFromGraph(HttpServletRequest httpRequest, HttpServletResponse response)
        throws Throwable {

    IAuthenticationResult result;
    ModelAndView mav;
    try {
        result = authHelper.getAuthResultBySilentFlow(httpRequest, response);
    } catch (ExecutionException e) {
        if (e.getCause() instanceof MsalInteractionRequiredException) {

            // If the silent call returns MsalInteractionRequired, redirect to authorization endpoint
            // so user can consent to new scopes.
            String state = UUID.randomUUID().toString();
            String nonce = UUID.randomUUID().toString();

            SessionManagementHelper.storeStateAndNonceInSession(httpRequest.getSession(), state, nonce);

            String authorizationCodeUrl = authHelper.getAuthorizationCodeUrl(
                    httpRequest.getParameter("claims"),
                    "User.Read",
                    authHelper.getRedirectUriGraph(),
                    state,
                    nonce);

            return new ModelAndView("redirect:" + authorizationCodeUrl);
        } else {

            mav = new ModelAndView("error");
            mav.addObject("error", e);
            return mav;
        }
    }

    if (result == null) {
        mav = new ModelAndView("error");
        mav.addObject("error", new Exception("AuthenticationResult not found in session."));
    } else {
        mav = new ModelAndView("auth_page");
        setAccountInfo(mav, httpRequest);

        try {
            mav.addObject("userInfo", getUserInfoFromGraph(result.accessToken()));

            return mav;
        } catch (Exception e) {
            mav = new ModelAndView("error");
            mav.addObject("error", e);
        }
    }
    return mav;
}
// Code omitted here

Trong mẫu Python, mã gọi Microsoft Graph nằm trong App.Py#L53-L62.

Mã cố gắng để nhận mã thông báo từ bộ đệm mã thông báo. Sau đó, sau khi thiết lập tiêu đề ủy quyền, nó gọi API Web. Nếu nó không thể nhận được mã thông báo, nó sẽ ký lại người dùng.

@app.route("/graphcall")
def graphcall():
    token = _get_token_from_cache(app_config.SCOPE)
    if not token:
        return redirect(url_for("login"))
    graph_data = requests.get(  # Use token to call downstream service.
        app_config.ENDPOINT,
        headers={'Authorization': 'Bearer ' + token['access_token']},
        ).json()
    return render_template('display.html', result=graph_data)

Bước tiếp theo

Chuyển sang bài viết tiếp theo trong kịch bản này, hãy gọi API Web.

Phản HồI

Gửi và xem ý kiến ​​ph