Oracle® Fusion Middleware Oracle Access Management開発者ガイド 11g リリース2 (11.1.2.2.0) for All Platforms B69537-08 |
|
![]() 前 |
![]() 次 |
この章では、JavaクライアントSDKを使用してデスクトップ・アプリケーションを構築する方法について説明します。JavaクライアントSDKでは、モバイル・デバイス上でのアプリケーションの構築はサポートしていません。この章の内容は次のとおりです。
モバイル・サービス用Mobile and Social JavaクライアントSDKは、Oracle Access Management配布パッケージに含まれており、Oracle Technical Network (OTN) Webサイトからダウンロードすることもできます。
この開発者ガイドの他に、Javadocツールによって生成されるAPIドキュメントが使用可能です。APIクラス、インタフェース、コンストラクタ、メソッドおよびフィールドの説明は、使用可能なAPIドキュメントを参照してください。このドキュメントは、SDKでHTMLとして提供され、Oracle Fusion Middleware Mobile and Social Java APIリファレンス.としてPDFおよびHTML形式でOracle Access Management製品ライブラリからダウンロードすることもできます。
この項では、クライアント・トークン、ユーザー・トークンおよびアクセス・トークンをリクエストする方法について説明するサンプル・コードを提供します。
トークンには、アイテムに関連する属性、およびトークン・ベアラの権限、有効性またはアイデンティティを確立する暗号化された情報が含まれています。クライアント・トークンには資格証明情報が含まれ、ユーザー・トークンはクライアント・トークンをカプセル化し、アクセス・トークンには保護されたリソースのアクセスに必要なセキュリティ情報が含まれています。
この項のサンプル・コードは、JWTAuthentication (JSON Web Token Authentication)サービス・タイプをサポートしています。サービス・プロバイダの構成方法の詳細は、『Oracle Fusion Middleware Oracle Access Management管理者ガイド』のモバイル・サービスの構成に関する項を参照してください。
この項のコード・サンプルは、次のカテゴリに分類されます。
oic_clientsdk.jar
ファイルからの次のJavaクライアントSDKクラスをインポートします。
import oracle.security.idaas.rest.jaxrs.client.sdk.ClientSDKConfig; import oracle.security.idaas.rest.jaxrs.client.sdk.Headers; import oracle.security.idaas.rest.jaxrs.client.sdk.HeadersDefaultImpl; import oracle.security.idaas.rest.jaxrs.client.sdk.OICClientException; import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.AuthenticationClient; import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.AuthenticationResult; import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenCreateRequest; import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenCreateRequestImpl; import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenDeleteRequest; import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenDeleteRequestImpl; import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenExchangeRequest; import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenExchangeRequestImpl; import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenReadRequest; import oracle.security.idaas.rest.jaxrs.client.sdk.authentication.TokenReadRequestImpl;
ClientSDKConfig
オブジェクトを初期化し、サービス・プロバイダjwtauthentication
.を使用して様々なアクションのエンドポイントを定義します。次に、AuthenticationClient
オブジェクトを初期化します。
AuthenticationClientSDKConfig cc = new AuthenticationClientSDKConfig(); cc.setRegisterationServiceURI("http://hostcomputer.example.com:18001/ oic_rest/rest/jwtauthentication/register"); cc.setAuthenticationServiceURI("http://hostcomputer.example.com:18001/ oic_rest/rest/jwtauthentication/authenticate"); cc.setAccessTokenServiceURI("http://hostcomputer.example.com:18001/ oic_rest/rest/jwtauthentication/access"); cc.setTokenInfoServiceURI("http://hostcomputer.example.com:18001/ oic_rest/rest/jwtauthentication/tokens/info"); AuthenticationClient tc = new AuthenticationClient(cc);
クライアント・トークン・リクエストの必須パラメータを定義し、トークンを作成するようリクエストします。savedClientToken
という変数にトークン・リクエストの結果を保存します。
String subjectType = "USERCREDENTIAL"; String uname = "profileid1"; String password = "secret12"; String tokenTypeToCreate = "CLIENTTOKEN"; TokenCreateRequest tcrd = new TokenCreateRequestImpl(subjectType, uname, password, tokenTypeToCreate); Headers headers = new HeadersDefaultImpl(); AuthenticationResult savedClientToken = tc.createToken(tcrd, headers);
ユーザー・トークン・リクエストの必須パラメータを定義し、トークンを作成するようリクエストします。前の手順からのクライアント・トークンをREST認可ヘッダーに追加し、savedUserToken
という変数にユーザー・トークン・リクエストの結果を保存します。
String subjectType = "USERCREDENTIAL"; String uname = "sean"; String password = "secret12"; String tokenTypeToCreate = "USERTOKEN"; TokenCreateRequest tcrd = new TokenCreateRequestImpl(subjectType, uname, password, tokenTypeToCreate); Headers headers = new HeadersDefaultImpl(); //Value expects certain format including type... String tokenHeaderValue = "TOKEN" + " " + savedClientToken.getValue(); headers.setIdaasRestAuthZHeader(tokenHeaderValue); AuthenticationResult savedUserToken = tc.createToken(tcrd, headers);
アクセス・トークン・リクエストの必須パラメータを定義し、トークンを作成するようリクエストします。savedAccessToken
という変数にトークン・リクエストの結果を保存します。
String resource = "http:myserver.com:8080/index.html"; String context = "QaZdhh77randomstuff"; String tokenSubjectValue = savedClientToken.getValue(); String credentialSubjectType = "TOKEN"; String newTokenTypeToCreate = "ACCESSTOKEN"; TokenExchangeRequest tcberd = new TokenExchangeRequestImpl(credentialSubjectType, tokenSubjectValue, resource, context, newTokenTypeToCreate); AuthenticationResult savedAccessToken = tc.createToken(tcberd, headers);
String tokenValueToVerify = savedClientToken.getValue(); String tokenSubjectTypeToVerify = "TOKEN"; headers = new HeadersDefaultImpl(); headers.setIdaasRestAuthZHeader("TOKEN " + tokenValueToVerify); TokenReadRequest tokenToRead = new TokenReadRequestImpl(); tokenToRead.setSubjectValue(tokenValueToVerify); tokenToRead.setSubjectType(tokenSubjectTypeToVerify); AuthenticationResult retrievedToken = tc.readToken(tokenToRead, headers); System.out.println("Token returned from readToken() =" + retrievedToken.getValue()); if (null != savedClientToken && null != retrievedToken) { System.out.println("Does value in savedClientToken == retrievedToken?" + savedClientToken.getValue().equals(retrievedToken.getValue())); }
Headers headers = new HeadersDefaultImpl(); headers.setIdaasRestAuthZHeader("TOKEN " + savedClientToken.getValue()); TokenReadRequest tokenToRead = new TokenReadRequestImpl(); tokenToRead.setSubjectValue(savedUserToken.getValue()); tokenToRead.setSubjectType("TOKEN"); AuthenticationResult retrievedToken = tc.readToken(tokenToRead, headers); System.out.println("Token returned from readToken() =" + retrievedToken.getValue()); if (null != savedUserToken && null != retrievedToken) { System.out.println("Does value in savedUserToken == retrievedToken?" + savedUserToken.getValue().equals(retrievedToken.getValue())); }
この手順で、ユーザーは、認証プロバイダによって保護されている、保護されたリソースです。
UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); final String SEARCH_PAGE_POSITION_QUERY_PARAM_NAME = "pagePos"; final String SEARCH_PAGE_SIZE_QUERY_PARAM_NAME = "pageSize"; String pageSizeValue = "1"; //Just get one user for this test. String pageSizePosition = "0"; //Now do a search and fetch first page o results. Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put(SEARCH_PAGE_SIZE_QUERY_PARAM_NAME, pageSizeValue); queryParameters.put(SEARCH_PAGE_POSITION_QUERY_PARAM_NAME, pageSizePosition); // Set Header to include the User Token for authetication. Headers headers = new HeadersDefaultImpl(); headers.setAuthZHeader(savedUserToken); //Perform search operation. JSONCollection searchResults = pc.searchUsers(queryParameters, headers);
String deleteSubjectValue = savedClientToken.getValue(); //use first token value String deleteTokenType = "TOKEN"; TokenDeleteRequest tokenToDelete = new TokenDeleteRequestImpl(); tokenToDelete.setSubjectValue(deleteSubjectValue); tokenToDelete.setTokenType(deleteTokenType); boolean result = false; result = tc.deleteToken(tokenToDelete, headers);
この項のコード・サンプルを使用する前に、このSDKに固有ではない情報について、「ユーザー・プロファイル・サービスを使用したアプリケーションの構築」を参照してください。
この項のコード・サンプルは、次のカテゴリに分類されます。
次のコード・サンプルでは、ユーザー・プロファイル・サービスがアクセスおよび更新可能なディレクトリ・ストアにあるユーザー・レコードと連携させる方法について説明します。この項では基本的な次のシナリオについて説明します。
まず、oic_clientsdk.jar
ファイルから次のJavaクラスをインポートし、次にpeopleサービスURIグローバル変数を宣言します。
import oracle.security.idaas.rest.jaxrs.client.sdk.ClientSDKConfig; import oracle.security.idaas.rest.jaxrs.client.sdk.Headers; import oracle.security.idaas.rest.jaxrs.client.sdk.HeadersDefaultImpl; import oracle.security.idaas.rest.jaxrs.client.sdk.OICClientException; import oracle.security.idaas.rest.jaxrs.client.sdk.userprofile.JSONCollection; import oracle.security.idaas.rest.jaxrs.client.sdk.userprofile.PeopleClient; private static String serviceURI = "http://hostcomputer.example.com:18001/oic_rest/rest/userprofile/people";
次のサンプルはuid peopletestuser123
を使用してユーザー・レコードを作成します。
UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); //Just generate some fake user info. String uid = "peopletestuser123"; String userpassword = "secret123"; String sn = uid; String cn = uid; String mail = uid + "@example.com"; //Now put these values into the resourceAttrs map, and pass to helper. Map<String, Object> resourceAttrs = new HashMap<String, Object>(); resourceAttrs.put("uid", uid); resourceAttrs.put("password", userpassword); resourceAttrs.put("lastname", sn); resourceAttrs.put("commonname", cn); resourceAttrs.put("mail", mail); List<String> phoneNums = new ArrayList<String>(); phoneNums.add("408-123-5555"); phoneNums.add("408-123-9999"); resourceAttrs.put("telephone", phoneNums); String personJson = pc.createUser(resourceAttrs, new HeadersDefaultImpl());
次のサンプルはuid peopletestuser123
を使用してユーザー・レコードを取得します。
UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); String uidForExistingUser = "peopletestuser123"; //now GET that user just to check Map<String, String> queryParameters = new HashMap<String, String>();//none yet String existingUser = pc.readUser(uidForExistingUser, queryParameters, new HeadersDefaultImpl()); boolean found = false; JSONObject jo = new JSONObject(existingUser); String s = jo.getString("uid"); found = s.equalsIgnoreCase(uid);
次のサンプルはuid peopletestuser123
を使用してユーザー・レコードを更新します。
UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); //Just generate some fake user info. final String CN_VALUE = "UPDATED CN"; String uidForExistingUser = "peopletestuser123"; //From class-defined uid. //now make some attributes with new values to update Map<String, Object> attrsToUpdate = new HashMap<String, Object>(); attrsToUpdate.put("commonname", CN_VALUE); String result = pc.updateUser(uidForExistingUser, attrsToUpdate,new HeadersDefaultImpl());
次のサンプルはuid peopletestuser123
を使用してユーザー・レコードを削除します。
UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); boolean deleteResult = pc.deleteUser("peopletestuser123", new HeadersDefaultImpl());
次のサンプルはuid peopletestuser123
を使用してユーザー・レコードを検索します。
UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); //now do a search on uid attribute Map<String, String> queryParameters = new HashMap<String, String>(); String queryValue = "peopletestuser"+ "*"; queryParameters.put("searchparam.uid", queryValue); //Set query parameters and empty headers. JSONCollection searchResult = pc.searchUsers(queryParameters, new HeadersDefaultImpl()); //Get raw JSON array value in "elements" attribute. String elementJSONString = searchResult.getJsonArrayElements(); JSONArray ja = null; ja = new JSONArray(elementJSONString); //Now try to match the result to the expected User with uid. JSONObject elem = null; boolean found = false; for(int i=0; i<ja.length() && found==false; i++) { elem = ja.getJSONObject(i); //Get item from array String u = elem.getString("uid"); //Check if attr is present AND matches some value. if(u.equalsIgnoreCase("peopletestuser123")) { found = true; } }
次のサンプルはユーザー属性commonname
を取得し、属性description
が存在しないことを確認します。
final String ATTRIBUTES_TO_FETCH_QUERY_PARAM_NAME = "attrsToFetch"; String attributeToFetchName = "commonname"; //fetch this attribute String attributeShouldNotBePresent = "description"; ClientSDKConfig cc = new ClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); //Now GET that User just to check. Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put(ATTRIBUTES_TO_FETCH_QUERY_PARAM_NAME, attributeToFetchName); String existingUser = pc.readUser("peopletestuser123", queryParameters, new HeadersDefaultImpl()); boolean found = false; try { JSONObject jo = new JSONObject(existingUser); //Throws exception if attribute not present String s = jo.getString(attributeToFetchName); found = true; } catch (JSONException je) { found = false; } //Now verify that a certain attribute is NOT present. found = false; try { JSONObject jo = new JSONObject(existingUser); //throws exception if attribute not present for(Iterator it = jo.keys(); it.hasNext() && found==false; ) { String key = (String) it.next(); if(key.equalsIgnoreCase(attributeShouldNotBePresent)) { found = true; //Bad if present because it should not be. } } } catch (JSONException je) {}
グループはユーザーのセットです。
この項では、次の基本的なシナリオについてのコード・サンプルを示します。
まず、次のJavaクラスをインポートし、次にgroupsサービスURIグローバル変数を宣言します。
import oracle.security.idaas.rest.jaxrs.client.sdk.ClientSDKConfig; import oracle.security.idaas.rest.jaxrs.client.sdk.HeadersDefaultImpl; import oracle.security.idaas.rest.jaxrs.client.sdk.OICClientException; import oracle.security.idaas.rest.jaxrs.client.sdk.userprofile.GroupsClient; import oracle.security.idaas.rest.jaxrs.client.sdk.userprofile.JSONCollection; private static GroupsClient gc = null; private static PeopleClient pc = null; private static String roleServiceURI = 'http://hostcomputer.example.com:18001/oic_rest/ rest/userprofile/groups"; private static String peopleServiceURI = "http://hostcomputer.example.com:18001/oic_rest/ rest/userprofile/people"; Map<String, String> accessURIMap = Util.createAccessURIMap("manager", "reports", "memberOf", "members", "groupMemberOf", "groupMembers", "ownerOf", "personOwner", "groupOwner", "groupOwnerOf"); Map<String, String> entityURIMap = Util.createEntityURIMap("report-uri", "manager-uri", "person-uri", "group-uri", "member-uri", "group-uri", "owner-uri", "group-uri", "group-uri", "owner-uri"); UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(roleServiceURI); cc.setAccessURIMap(accessURIMap); cc.setEntityURIMap(entityURIMap); gc = new GroupsClient(cc); UserProfileClientSDKConfig cc2 = new UserProfileClientSDKConfig(peopleServiceURI); cc2.setAccessURIMap(accessURIMap); cc2.setEntityURIMap(entityURIMap); pc = new PeopleClient(cc2);
Map<String, Object> resourceAttrs = new HashMap<String, Object>(); resourceAttrs.put("commonname", "testGroup"); resourceAttrs.put("description", "testGroupDescription"); String creategroup = gc.createGroup(resourceAttrs, new HeadersDefaultImpl());
String readgroup = gc.readGroup("testGroup", new HashMap<String, String>(), new HeadersDefaultImpl());
Map<String, Object> resourceAttrs2 = new HashMap<String, Object>(); resourceAttrs2.put("description", "new description"); String udpatedgroup = gc.updateGroup("testGroup", resourceAttrs2, new HeadersDefaultImpl());
boolean deletedgroup = gc.deleteGroup("testGroup", new HeadersDefaultImpl());
//search with searchOperator = OR, commonname and description Map<String, String> queryParams = new HashMap<String,String>(); String commonname = "testGroup" + 1; String description = "testGroup" + "Description"; queryParams.put("searchparam.commonname", commonname); queryParams.put("searchparam.description", description); queryParams.put("searchFilter","SimpleOR"); JSONCollection searchResult = gc.searchGroups(queryParams, new HeadersDefaultImpl()); //get raw JSON array value in "elements" attribute String elementJSONString = searchResult.getJsonArrayElements(); JSONArray ja = new JSONArray(elementJSONString);
次のサンプルではグループを検索し、一度に1ページ、結果を返します。
final String SEARCH_PAGE_POSITION_QUERY_PARAM_NAME = "pagePos"; final String SEARCH_PAGE_SIZE_QUERY_PARAM_NAME = "pageSize"; String pageSizeValue = "1"; //just get one group for this test String pageSizePosition = "0"; //now do a search and fetch first page o results Map<String, String> queryParams = new HashMap<String, String>(); queryParams.put(SEARCH_PAGE_SIZE_QUERY_PARAM_NAME, pageSizeValue); queryParams.put(SEARCH_PAGE_POSITION_QUERY_PARAM_NAME, pageSizePosition); JSONCollection searchResults = gc.searchGroups(queryParams, new HeadersDefaultImpl()); //get raw JSON array value in "elements" attribute String elementJSONString = searchResults.getJsonArrayElements(); JSONArray ja = null; ja = new JSONArray(elementJSONString); boolean justOneFound = false; //the search returns a set with just one user if (ja.length() == Integer.parseInt(pageSizeValue)) { justOneFound = true; }
次の例では、addPersonMember
メソッドを使用しています。「addMemberOfを使用したグループへのグループ(またはユーザー)の追加」も参照してください。
String resultRoleMembership = gc.addPersonMember("testGroup", "testuser123", new HeadersDefaultImpl());
次の例では、getPersonMember
メソッドを使用しています。「getMemberOfを使用したグループ・メンバーシップの取得」も参照してください。
Map<String, String> queryParameters = new HashMap<String, String>(); //none yet String membershipId ="testuser123"; String result = gc.getPersonMember("testGroup",membershipId,queryParameters, new HeadersDefaultImpl());
次の例では、searchGroupMembers
メソッドを使用しています。「searchMemberOfを使用したグループの検索」も参照してください。
String queryFilter = "(uid=" +"*)"; Map<String, String> queryParams = new HashMap<String, String>(); queryParams.put("nativequery", queryFilter); //need to use membership uri such as ...doctors/members JSONCollection searchResults = gc.searchPersonMembers("testGroup", queryParams, new HeadersDefaultImpl()); //get raw JSON array value in "elements" attribute String elementJSONString = searchResults.getJsonArrayElements(); JSONArray ja = null; ja = new JSONArray(elementJSONString); //Sample of how to get the members' URIs. A client could call GET on each of these // persons' URIs using the person client API to get details about each member.Set<String> userUriSet = new HashSet<String>(); final String PERSON_URI_FIELD_NAME = "person-uri"; for (int i=0; i<ja.length(); i++) { JSONObject jo = ja.getJSONObject(i); //Get the URI field of this user. String uri = jo.getString(PERSON_URI_FIELD_NAME); if (uri != null && !uri.isEmpty()) { userUriSet.add(uri); } } // Get Group members in the group. searchResults = gc.searchGroupMembers("testGroup", queryParams, new HeadersDefaultImpl());
次の例では、deletePersonMember
メソッドを使用しています。「deleteMemberOfを使用したグループからのグループ(またはユーザー)の削除」も参照してください。
boolean result = gc.deletePersonMember("testGroup", "testuser123", new HeadersDefaultImpl());
次の例は、ユーザーまたはグループへのグループ所有権の割当て方法を示しています。
// Add user testuser123 to group testGroup as group owner. String resultRoleOwnership = gc.addPersonOwner("testGroup", "testuser123", new HeadersDefaultImpl()); // Add group testSubGroup to group testGroup as group owner. String resultRoleOwnership2 = gc.addGroupOwner("testGroup", "testSubGroup", new HeadersDefaultImpl());
Map<String, String> queryParameters = new HashMap<String, String>();//none yet String ownershipId="testuser123"; String result = gc.getPersonOwner("testGroup", ownershipId, queryParameters, new HeadersDefaultImpl()); ownershipId ="testSubGroup"; result = gc.getGroupOwner("testGroup", ownershipId, queryParameters, new HeadersDefaultImpl());
String queryFilter = "(uid=" +"*)";
Map<String, String> queryParams = new HashMap<String, String>(); queryParams.put("nativequery", queryFilter); // Get Person owners in the group. JSONCollection searchResults = gc.searchPersonOwners("testGroup", queryParams, new HeadersDefaultImpl()); // Get raw JSON array value in the "elements" attribute. String elementJSONString = searchResults.getJsonArrayElements(); JSONArray ja = null; ja = new JSONArray(elementJSONString); // Sample of how to get the members' URIs. A client could call GET on each of these // person URIs using the person client API and get details on each member. Set<String> userUriSet = new HashSet<String>(); final String OWNER_URI_FIELD_NAME = "owner-uri"; for(int i=0; i<ja.length(); i++) { JSONObject jo = ja.getJSONObject(i); //Get URI field of this user. String uri = jo.getString(OWNER_URI_FIELD_NAME); if (uri != null && !uri.isEmpty()) { userUriSet.add(uri); } } // Get Group owners in the group. searchResults = gc.searchGroupOwners("testGroup", queryParams, new HeadersDefaultImpl());
boolean result = gc.deletePersonOwner("testGroup", "testuser123", new HeadersDefaultImpl());boolean result2= gc.deleteGroupOwner("testGroup", "testSubGroup", new HeadersDefaultImpl());
次の例は、addMemberOf
メソッドを使用して、グループを別のグループのメンバーにしたり、ユーザーをグループのメンバーにする方法を示しています。
// Add group "testSubGroup" to be a member of group "testGroup" String resultRoleMembership2= gc.addMemberOf("testGroup", "testSubGroup", new HeadersDefaultImpl()); // Add user "testuser123" to be a member of group "testGroup" String resultRoleMembership = pc.addMemberOf("testuser123", "testGroup", new HeadersDefaultImpl());
次の例は、getMemberOf
メソッドを使用して、指定したグループの関係のデータを取得する方法を示しています。
// Get relationship data where user "testuser123" is a member of group "testGroup" String resultRoleMembership = pc.getMemberOf("testuser123", "testGroup", new HeadersDefaultImpl()); // Get relationship data where group "testsubGroup" is a member of group "testGroup" String resultRoleMembership2= gc.getMemberOf("testGroup", "testSubGroup", new HeadersDefaultImpl());
String queryFilter = "(uid=" +"*)"; Map<String, String> queryParams = new HashMap<String, String>(); queryParams.put("nativequery", queryFilter); // Search groups of which Person "testuser123" is a member JSONCollection searchResults = pc.searchMemberOf("testuser123", queryParams, new HeadersDefaultImpl()); //Get raw JSON array value in "elements" attribute String elementJSONString = searchResults.getJsonArrayElements(); JSONArray ja = null; ja = new JSONArray(elementJSONString); // Sample of how to get the members' URIs. A client could call GET on each of these // person URIs using the person client API to get details about each member.Set<String> groupUriSet = new HashSet<String>(); final String GROUP_URI_FIELD_NAME = "group-uri"; for(int i=0; i<ja.length(); i++) { JSONObject jo = ja.getJSONObject(i); //Get URI field of this user. String uri = jo.getString(GROUP_URI_FIELD_NAME); if (uri != null && !uri.isEmpty()) { groupUriSet.add(uri); } } // Search Groups of which group "testSbuGroup" is a member. searchResults = gc.searchMemberOf("testSubGroup", queryParams, new HeadersDefaultImpl());
// Delete member "testuser123" from group "testGroup" boolean result = pc.deleteMemberOf("testuser123","testGroup", new HeadersDefaultImpl()); // Delete member "testSubGroup" from group "testGroup" boolean result2= gc.deleteMemberOf("testGroup","testSubGroup", new HeadersDefaultImpl());
// Add user "testuser123" to be an owner of group "testGroup" String resultRoleOwnership = pc.addOwnerOf("testuser123", "testGroup", new HeadersDefaultImpl()); // Add group "testSubGroup" to be an owner of group "testGroup" String resultRoleOwnership2 = gc.addOwnerOf("testGroup", "testSubGroup", new HeadersDefaultImpl());
// Get relationship data where user "testuser123" is an owner of group "testGroup" String resultRoleOwnership = pc.getOwnerOf("testuser123", "testGroup", new HeadersDefaultImpl()); // Get relationship data where group "testsubGroup" is an owner of group "testGroup" String resultRoleOwnership2= gc.getOwnerOf("testGroup", "testSubGroup", new HeadersDefaultImpl());
String queryFilter = "(uid=" +"*)"; Map<String, String> queryParams = new HashMap<String, String>(); queryParams.put("nativequery", queryFilter); // Search Groups of which Person "testuser123" is an owner. JSONCollection searchResults = pc.searchOwnerOf("testuser123", queryParams, new HeadersDefaultImpl()); // Get raw JSON array value in "elements" attribute. String elementJSONString = searchResults.getJsonArrayElements(); JSONArray ja = null; ja = new JSONArray(elementJSONString); // Sample of how to get the members' URIs. A client could call GET on each of these person URIs using the person client API to get details about each member. Set<String> groupUriSet = new HashSet<String>(); final String GROUP_URI_FIELD_NAME = "group-uri"; for(int i=0; i<ja.length(); i++) { JSONObject jo = ja.getJSONObject(i); // Get URI field of this user. String uri = jo.getString(GROUP_URI_FIELD_NAME); if (uri != null && !uri.isEmpty()) { groupUriSet.add(uri); } } // Search Groups of which group "testSbuGroup" is an owner. searchResults = gc.searchOwnerOf("testSubGroup", queryParams, new HeadersDefaultImpl());
// Delete owner "testuser123" from group "testGroup" boolean result = pc.deleteOwnerOf("testuser123","testGroup", new HeadersDefaultImpl()); // Delete owner "testSubGroup" from group "testGroup" boolean result2= gc.deleteOwnerOf("testGroup","testSubGroup", new HeadersDefaultImpl());
組織は通常、マネージャや部下を含む、人の階層グループです。
この項では、次の基本的なシナリオについてのコード・サンプルを示します。
まず、次のJavaクラスをインポートし、次にgroupsサービスURIグローバル変数を宣言します。
import oracle.security.idaas.rest.jaxrs.client.sdk.ClientSDKConfig; import oracle.security.idaas.rest.jaxrs.client.sdk.Headers; import oracle.security.idaas.rest.jaxrs.client.sdk.HeadersDefaultImpl; import oracle.security.idaas.rest.jaxrs.client.sdk.userprofile.PeopleClient; private static String personServiceURI= "http://hostcomputer.example.com:18001/oic_rest/rest/userprofile/people"; private static String peopleBaseURI = "/oic_rest/rest/userprofile/people";
この項の3つのヘルパー・ユーティリティは、組織データを使用する場合に役立ちます。
ユーザー・データを作成するためのヘルパー・ユーティリティ
public static String createPersonHelper(String personServiceURI, String username,String password,Map<String, String> optionalAttributes) { ClientSDKConfig cc = new ClientSDKConfig(personServiceURI); PeopleClient pc = new PeopleClient(cc); //Generate some fake user info. String uid = username; String userpassword = password; String sn = uid; String cn = uid; String mail = uid + "@example.com"; try { //now put these values into the resourceAttrs map, and pass to helper //these java string names need to match the json field names Map<String, Object> resourceAttrs = new HashMap<String, Object>(); resourceAttrs.put("uid", uid); resourceAttrs.put("password", userpassword); resourceAttrs.put("lastname", sn); resourceAttrs.put("commonname", cn); resourceAttrs.put("mail", mail); if (optionalAttributes != null && !optionalAttributes.isEmpty()) { for(Map.Entry<String, String> me : optionalAttributes.entrySet()) { resourceAttrs.put(me.getKey(), me.getValue()); } } String newUser = pc.createUser(resourceAttrs, new HeadersDefaultImpl()); }
マネージャと部下の関係を確立するためのヘルパー・ユーティリティ
private static boolean assignManagerToUser(String personServiceURI, String serviceBaseURI, String userUID, String theManagerId) { ClientSDKConfig cc = new ClientSDKConfig(personServiceURI); PeopleClient pc = new PeopleClient(cc); final String MANAGER_URI_SEGMENT_NAME = "manager"; //now make payload final String MANAGER_URI_JSON_ATTRIBUTE_NAME = "manager-uri"; final String REPORTS_URI_JSON_ATTRIBUTE_NAME = "report-uri"; Map<String, Object> resourceAttrs = new HashMap<String, Object>(); resourceAttrs = new HashMap<String, Object>(); //use base URI od people service within json values String theManagerURIValue = serviceBaseURI + "/" + theManagerId; resourceAttrs.put(MANAGER_URI_JSON_ATTRIBUTE_NAME, theManagerURIValue); String theReporteeURIValue = serviceBaseURI + "/" + userUID; //user being added to list of reports resourceAttrs.put(REPORTS_URI_JSON_ATTRIBUTE_NAME, theReporteeURIValue); return pc.addUserToOrgChart(userUID, MANAGER_URI_SEGMENT_NAME, resourceAttrs, new HeadersDefaultImpl()); }
データ準備ユーティリティ
このユーティリティは、組織内の異なる階層レベルでユーザーを作成します。
String theUIDofManager = null; Map<String, String> optionalAttributes = new HashMap<String, String>(); optionalAttributes.put("manager", theUIDofManager); //keep a map of created people in orgchart Map<String, String> createdPeople= new HashMap<String, String>(); String userPassword = "secret123"; String userId = "ceo"+ "orgcharttestuser"+ "123"; // user is CEO String person = Util.createPersonHelper(peopleServiceURI, userId, userPassword, optionalAttributes ); theUIDofManager = userId; //set to previously created user userId = "director" + "orgcharttestuer" + "123"; // user id DIRECTOR optionalAttributes = new HashMap<String, String>();//reset for each new user person = Util.createPersonHelper(peopleServiceURI, userId, userPassword, optionalAttributes); //now assign this newly created user DIRECTOR's manager to be CEO assignManagerToUser(peopleServiceURI, peopleBaseURI, userId, theUIDofManager); theUIDofManager = userId; //set to previously created user userId = "developer111" + "orgcharttestuser" + "123"; // user is DEVELOPER111 optionalAttributes = new HashMap<String, String>();//reset for each new user person = Util.createPersonHelper(peopleServiceURI, userId, userPassword, optionalAttributes); //now assign this newly created user DEVELOPER111's manager to be DIRECTOR assignManagerToUser(peopleServiceURI, peopleBaseURI, userId, theUIDofManager); userId = "developer222"+ "orgcharttestuser"+"123"; // user is DEVELOPER222 optionalAttributes = new HashMap<String, String>();//reset for each new user person = Util.createPersonHelper(peopleServiceURI, userId, userPassword, optionalAttributes); //now assign this newly created user DEVELOPER222's manager to be DIRECOTR assignManagerToUser(peopleServiceURI, peopleBaseURI, userId, theUIDofManager);
//Set empty query parameters and empty headers. Map<String, String> searchQueryParameters = new HashMap<String, String>(); Headers searchHeaders = new HeadersDefaultImpl(); JSONCollection resultSet = pc.searchManagers("developer222orgcharttestuser123", searchQueryParameters, searchHeaders); //get raw JSON array value in "elements" attribute String elementJSONString = resultSet.getJsonArrayElements(); boolean found = false; final String MANAGER_URI_ATTRIBUTE_NAME = "manager-uri"; JSONArray ja = new JSONArray(elementJSONString); for(int i=0; i< ja.length() && found==false; i++) { JSONObject elem = ja.getJSONObject(i);//get item from array try { //The "manager-uri" attribute of this item in element array is //expanded automatically so its value is a JSONObject. JSONObject managerURIObject = elem.getJSONObject(MANAGER_URI_ATTRIBUTE_NAME); //Check if attr is present AND matches some value. if(managerURIObject.getString("uri").equalsIgnoreCase("directororgcharttestuser123")) { found = true; } } catch (JSONException je) { //An exception is thrown if attribute is not found or is not a JSON object //found = false; } //print out each user, until found }
Map<String, String> searchQueryParameters = new HashMap<String, String>(); Headers searchHeaders = new HeadersDefaultImpl(); JSONCollection resultSet = pc.searchReportees("ceoorgcharttestuser123", searchQueryParameters, searchHeaders); //Get raw JSON array value in "elements" attribute. String elementJSONString = resultSet.getJsonArrayElements(); boolean found = false; final String REPORTS_URI_ATTRIBUTE_NAME = "report-uri"; JSONArray ja = new JSONArray(elementJSONString); for(int i=0; i< ja.length() && found==false; i++) { JSONObject elem = ja.getJSONObject(i); //Get item from array try { JSONObject reportURIObject = elem.getJSONObject(REPORTS_URI_ATTRIBUTE_NAME); //Check if attr is present AND matches some value. if(reportURIObject.getString("uri").equalsIgnoreCase("directororgcharttestuser123")) { found = true; } } catch (JSONException je) { //exception is thrown if attribute is not found or is not JSON object //found = false; } //Print out each user, until found. }
次のコード・サンプルでは、直属ではない部下を含む、組織内の部下のすべてを検証します。
ClientSDKConfig cc = new ClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); //Now test CEO orgchart by getting reports with scope=all, which should include developer. String orgChartIdURI = "reports"; //Now do a search and fetch first page o results. Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put(ClientConstants.ATTRIBUTES_TO_ORG_CHART_SCOPE_QUERY_PARAM_NAME, "all"); JSONCollection resultSet = pc.searchReportees("ceoorgcharttestuser123", queryParameters, new HeadersDefaultImpl()); //Get raw JSON array value in "elements" attribute. String elementJSONString = resultSet.getJsonArrayElements(); boolean found = false; JSONArray ja = new JSONArray(elementJSONString); for (int i=0; i<ja.length(); i++) { JSONObject jo = ja.getJSONObject(i); Object reportURIObj = jo.get("report-uri"); if (reportURIObj.toString().indexOf( "developer111orgcharttestuser123") != -1) { found = true; } }
次のコード・サンプルでは、toTop
属性を使用して、管理連鎖にマネージャを含む配列を取得します。
UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); // Now do a search and fetch the first page of results. Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put(ClientConstants.ATTRIBUTES_TO_ORG_CHART_SCOPE_QUERY_PARAM_NAME, "toTop"); JSONCollection resultSet = pc.searchManagers("developer111orgcharttestuser123", queryParameters, new HeadersDefaultImpl()); // Get raw JSON array value in "elements" attribute. String elementJSONString = resultSet.getJsonArrayElements();
次のコード・サンプルでは、部下IDおよびマネージャIDがわかっている場合にマネージャの詳細を取得します。
ClientSDKConfig cc = new ClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); final String ATTRIBUTES_TO_PREFETCH_QUERY_PARAM_NAME = ClientConstants.ATTRIBUTES_TO_PRFFETCH_QUERY_PARAM_NAME; String attributeToPrefetch = "report-uri"; final String MANAGER_URI_SEGMENT_NAME = "manager"; //Now read/get new user's details. String reporteeId = "developer111orgcharttestuser123"; String managerId = "directororgcharttestuser123"; //Now GET that user just to check. Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put(ATTRIBUTES_TO_PREFETCH_QUERY_PARAM_NAME, attributeToPrefetch); //Get raw JSON representation. String existingManagerRel = pc.getManager(reporteeId, managerId, queryParameters, new HeadersDefaultImpl()); //Now obtain manager details and retrieve the reports data. JSONObject jo = new JSONObject(existingManagerRel); Object managerAttributeValue = jo.get(attributeToPrefetch);
UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); final String ATTRIBUTES_TO_PREFETCH_QUERY_PARAM_NAME = ClientConstants.ATTRIBUTES_TO_PRFFETCH_QUERY_PARAM_NAME; String attributeToPrefetchName = "manager(commonname)"; Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put(ATTRIBUTES_TO_PREFETCH_QUERY_PARAM_NAME, attributeToPrefetchName); // Get the raw JSON representation of the person. String existingUser = pc.readUser("developer111orgcharttestuser123", queryParameters, new HeadersDefaultImpl()); // Get the manager attribute, which is expanded by prefetch to include one or more // sub-attributes, so that manager is a JSON object within the person JSON. // Now it is a JSONObject. JSONObject jo = new JSONObject(existingUser); Object managerAttributeValue = (Object) jo.get("manager"); System.out.println(CLASS_NAME + "." + METHOD + ": prefetch detail=" + managerAttributeValue);
ClientSDKConfig cc = new ClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); String uidForExistingUser = "developer111orgcharttestuser123"; String theManagerId = "directororgcharttestuser123"; final String REPORTS_URI_SEGMENT_NAME = "reports"; Map<String, String> queryParameters = new HashMap<String, String>(); //None yet. String existingOrgChartInstanceDetails = pc.getReportee(theManagerId, uidForExistingUser, queryParameters, new HeadersDefaultImpl()); //Now that we verified it exists, delete this membership in the reports list. boolean deleteResult = pc.deleteOrgChartInstance(theManagerId, REPORTS_URI_SEGMENT_NAME, uidForExistingUser, new HeadersDefaultImpl()); //Now try to get/read that user again. This time we should not find the user. queryParameters = new HashMap<String, String>(); //None yet. existingOrgChartInstanceDetails = null; try { existingOrgChartInstanceDetails = pc.readOrgChartInstance(theManagerId, REPORTS_URI_SEGMENT_NAME, uidForExistingUser, queryParameters, new HeadersDefaultImpl()); } catch (OICClientException ce) { System.out.println("existingOrgChartInstanceDetails was successfully deleted so not found" + " on subsequent read."); }
UserProfileClientSDKConfig cc = new UserProfileClientSDKConfig(serviceURI); PeopleClient pc = new PeopleClient(cc); final String SEARCH_PAGE_POSITION_QUERY_PARAM_NAME = "pagePos"; final String SEARCH_PAGE_SIZE_QUERY_PARAM_NAME = "pageSize"; String pageSizeValue = "1"; //Just get one user for this test. String pageSizePosition = "0"; //Now do a search and fetch first page o results. Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put(SEARCH_PAGE_SIZE_QUERY_PARAM_NAME, pageSizeValue); queryParameters.put(SEARCH_PAGE_POSITION_QUERY_PARAM_NAME, pageSizePosition); //Set query params and empty headers. JSONCollection searchResults = pc.searchUsers(queryParameters, new HeadersDefaultImpl()); //Get raw JSON array value in "elements" attribute String elementJSONString = searchResults.getJsonArrayElements(); JSONArray ja = null; ja = new JSONArray(elementJSONString); boolean justOneFound = false; //The search returns a set with just one user. if (ja.length() == Integer.parseInt(pageSizeValue)) { justOneFound = true; }
この例では、Access Manager認証サービスによって保護されている認可サービスにアクセスする方法を示します。
String clientToken = null; String userToken = null; ClientSDKConfig cc = null; AuthenticationClient authNClient = null; AuthorizationClient authZClient = null; Headers headers = new HeadersDefaultImpl(); headers.setContractName("Default"); TokenCreateRequest req = null; AuthenticationResult resultToken = null; // Create a Client Token. cc = new ClientSDKConfig("http://hostcomputer.example.com:18001/oic_rest/rest/oamauthentication/authenticate"); authNClient = new AuthenticationClient(cc); req = new TokenCreateRequestImpl("USERCREDENTIAL", "profileid1", "secret12", "CLIENTTOKEN"); headers = new HeadersDefaultImpl(); headers.setContractName("Default"); resultToken = authNClient.createToken(req, headers); clientToken = resultToken.getValue(); System.out.println("ClientToken from REST Service : " + clientToken); // Create a User Token. req = new TokenCreateRequestImpl("USERCREDENTIAL", "jane", "secret12", "USERTOKEN"); headers = new HeadersDefaultImpl(); headers.setIdaasRestAuthZHeader("TOKEN " + clientToken); headers.setContractName("Default"); resultToken = authNClient.createToken(req, headers); userToken = resultToken.getValue(); System.out.println("UserToken from REST Service : " + userToken); // Access the Authorization Service using the User Token. cc = new ClientSDKConfig("http://hostcomputer.example.com:18001/idaas_rest/rest/oamauthorization/authorization"); authZClient = new AuthorizationClient(cc); headers = new HeadersDefaultImpl(); headers.setAuthZHeader(userToken); headers.setContractName("Default"); Map<String, String> qp = new HashMap<String,String>(); qp.put("resource", "http://hostcomputer.example.com:18001/index.html"); qp.put("action", "get"); qp.put(ClientConstants.IDAAS_REST_SUBJECT_TYPE_QUERY_PARAM_NAME, "TOKEN"); qp.put(ClientConstants.IDAAS_REST_SUBJECT_VALUE_QUERY_PARAM_NAME, userToken); AuthorizationDecision ad = authZClient.getAuthzDecision (qp, headers); System.out.println("AuthZ Decision from REST Service : " + ad.getAllowed());