pdp_auth/
pdp_auth.rs

1use ibmcloud_iam::jwt::validate_token;
2use ibmcloud_iam::pdp as pdpapi;
3use ibmcloud_iam::pdp::Resource;
4use ibmcloud_iam::token::TokenManager;
5
6pub fn main() -> Result<(), Box<dyn std::error::Error>> {
7    // production IAM endpoint
8    let endpoint = "https://iam.cloud.ibm.com";
9
10    // get a user token from IAM
11    // normally this would be something your web service or server would receive from a user
12    // but we grab one here for the sake of completeness
13    let api_key =
14        std::env::var("IBMCLOUD_API_KEY").expect("Could not read IBMCLOUD_API_KEY from env");
15    let tm = TokenManager::new(&api_key, &endpoint);
16    let user_token = tm.token()?;
17
18    // validate user token, this checks the signature and returns claims
19    let _claims = validate_token(&user_token, &endpoint);
20
21    // Service ID API key, this is unique to your web service/server
22    let service_id_key =
23        std::env::var("SERVICE_ID_KEY").expect("Could not parse SERVICE_ID_KEY from env");
24
25    // build PDP client object for interacting with the IAM PDP endpoint
26    let pdp = pdpapi::PDPClient::new(&service_id_key, &endpoint);
27
28    // get Subject type from user token
29    let sub = pdpapi::subject_from_token(&user_token);
30
31    // action on the resource to be authorized
32    let action = "books.dashboard.view";
33
34    // create Resource object for PDP authorization request
35    // this is specific to your web service/server and should
36    // match up with the Attributes allowed in your IAM Service definition
37    let mut resource = Resource::new();
38    [
39        ("serviceName", "books"),
40        ("accountId", "1111222233334444"),
41        ("ctype", "public"),
42        ("serviceInstance", "9e386139-0000-000-8101-103771fa7793"),
43    ]
44    .iter()
45    .for_each(|tup| {
46        resource.insert(tup.0.to_string(), tup.1.to_string());
47    });
48
49    // build the final request, send to IAM, get and return the response
50    let resp = pdp.authorize(sub, &action, resource)?;
51
52    println!("Authorization Decision: {:?}", resp);
53
54    Ok(())
55}