4b29518f42d1fc5fb1f4ec60924ce687e1c7c655
[aaf/authz.git] / cadi / oauth-enduser / src / test / java / org / onap / aaf / cadi / enduser / test / OnapClientExample.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * ===========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END====================================================
19  *
20  */
21
22 package org.onap.aaf.cadi.enduser.test;
23
24 import java.io.IOException;
25 import java.net.ConnectException;
26 import java.security.GeneralSecurityException;
27 import java.util.Date;
28 import java.util.GregorianCalendar;
29
30 import org.onap.aaf.cadi.Access.Level;
31 import org.onap.aaf.cadi.CadiException;
32 import org.onap.aaf.cadi.LocatorException;
33 import org.onap.aaf.cadi.PropAccess;
34 import org.onap.aaf.cadi.client.Future;
35 import org.onap.aaf.cadi.client.Rcli;
36 import org.onap.aaf.cadi.client.Result;
37 import org.onap.aaf.cadi.client.Retryable;
38 import org.onap.aaf.cadi.config.Config;
39 import org.onap.aaf.cadi.oauth.TimedToken;
40 import org.onap.aaf.cadi.oauth.TokenClient;
41 import org.onap.aaf.cadi.oauth.TokenClientFactory;
42 import org.onap.aaf.cadi.oauth.TzClient;
43 import org.onap.aaf.cadi.util.FQI;
44 import org.onap.aaf.misc.env.APIException;
45 import org.onap.aaf.misc.env.util.Chrono;
46
47 import aafoauth.v2_0.Introspect;
48 import aafoauth.v2_0.Token;
49
50
51 public class OnapClientExample {
52         private static TokenClientFactory tcf;
53         private static PropAccess access;
54
55         public final static void main(final String args[]) {
56                 // These Objects are expected to be Long-Lived... Construct once
57                 
58                 // Property Access
59                 // This method will allow you to set "cadi_prop_files" (or any other property) on Command line 
60                 access = new PropAccess(args);
61                 
62                 // access = PropAccess();
63                 // Note: This style will load "cadi_prop_files" from VM Args
64                 
65                 // Token aware Client Factory
66                 try {
67                         tcf = TokenClientFactory.instance(access);
68                 } catch (APIException | GeneralSecurityException | IOException | CadiException e1) {
69                         access.log(e1, "Unable to setup OAuth Client Factory, Fail Fast");
70                         System.exit(1);
71                 }
72                 
73                 final int CALL_TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF));
74                 
75                 try {
76                         //////////////////////////////////////////////////////////////////////
77                         // Scenario 1:
78                         // Get and use an OAuth Client, which understands Token Management
79                         //////////////////////////////////////////////////////////////////////
80                         // Create a Token Client, that gets its tokens from expected OAuth Server
81                         //   In this example, it is AAF, but it can be the Alternate OAuth
82
83                         TokenClient tc = tcf.newClient(Config.AAF_OAUTH2_TOKEN_URL); // can set your own timeout here (url, timeoutMilliseconds)
84                         
85                         // Here's a trick to get the namespace out of a Fully Qualified AAF Identity (your MechID)
86                         String ns = FQI.reverseDomain(tc.client_id());
87                         System.out.printf("\nNote: The AAF Namespace of FQI (Fully Qualified Identity) %s is %s\n\n",tc.client_id(), ns);
88
89                         // Now, we can get a Token.  Note: for "scope", use AAF Namespaces to get AAF Permissions embedded in
90                         // Note: getToken checks if Token is expired, if so, then refreshes before handing back.
91                         Result<TimedToken> rtt = tc.getToken(ns,"org.onap.test"); // get multiple scopes
92                         
93                         // Note: you can clear a Token's Disk/Memory presence by
94                         //  1) removing the Token from the "token/outgoing" directory on the O/S
95                         //  2) programmatically by calling "clearToken" with exact params as "getToken", when it has the same credentials set
96                         //       tc.clearToken("org.onap.aaf","org.onap.test");
97                         
98                         // Result Object can be queried for success
99                         if(rtt.isOK()) {
100                                 TimedToken token = rtt.value;
101                                 print(token); // Take a look at what's in a Token
102                                 
103                                 // Use this Token in your client calls with "Tokenized Client" (TzClient)
104                                 // These should NOT be used cross thread.
105                                 // Get Hello Service URL... roll your own in your own world.
106                                 final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL, 
107                                                 "https://AAF_LOCATE_URL/AAF_NS.hello:2.0");
108
109
110                                 TzClient helloClient = tcf.newTzClient(endServicesURL);
111                                 helloClient.setToken(tc.client_id(), token);
112                                 
113                                 // This client call style, "best" call with "Retryable" inner class covers finding an available Service 
114                                 // (when Multi-services exist) for the best service, based (currently) on distance.
115                                 //
116                                 // the "Generic" in Type gives a Return Value for the Code, which you can set on the "best" method
117                                 // Note that variables used in the inner class from this part of the code must be "final", see "CALL_TIMEOUT"
118                                 String rv = helloClient.best(new Retryable<String>() {
119                                         @Override
120                                         public String code(Rcli<?> client) throws CadiException, ConnectException, APIException {
121                                                 Future<String> future = client.read("hello","text/plain");
122                                                 // The "future" calling method allows you to do other processing, such as call more than one backend
123                                                 // client before picking up the result
124                                                 // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then 
125                                                 if(future.get(CALL_TIMEOUT)) {
126                                                         // Client Returned expected value
127                                                         return future.value;
128                                                 } else {
129                                                         throw new APIException(future.code()  + future.body());
130                                                 }                                       
131                                         }
132                                 });
133                                 
134                                 // You want to do something with returned value.  Here, we say "hello"
135                                 System.out.printf("\nPositive Response from Hello: %s\n",rv);
136                                 
137                                 
138                                 //////////////////////////////////////////////////////////////////////
139                                 // Scenario 2:
140                                 // As a Service, read Introspection information as proof of Authenticated Authorization
141                                 //////////////////////////////////////////////////////////////////////
142                                 // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces (
143                                 // i.e. if(isUserInRole("ns.perm|instance|action")) {...
144                                 //
145                                 // Here, however, is a way to introspect via Java
146                                 //
147                                 // now, call Introspect (making sure right URLs are set in properties)
148                                 // We need a Different Introspect TokenClient, because different Endpoint (and usually different Services)
149                                 TokenClient tci = tcf.newClient(Config.AAF_OAUTH2_INTROSPECT_URL);
150                                 Result<Introspect> is = tci.introspect(token.getAccessToken());
151                                 if(is.isOK()) {
152                                         // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure
153                                         print(is.value); // do something with Introspect Object
154                                 } else {
155                                         access.printf(Level.ERROR, "Unable to introspect OAuth Token %s: %d %s\n",
156                                                         token.getAccessToken(),rtt.code,rtt.error);
157                                 }
158                         } else {
159                                 access.printf(Level.ERROR, "Unable to obtain OAuth Token: %d %s\n",rtt.code,rtt.error);
160                         }
161                         
162                 } catch (CadiException | LocatorException | APIException | IOException e) {
163                         e.printStackTrace();
164                 }
165         }
166         
167         /////////////////////////////////////////////////////////////
168         // Examples of Object Access
169         /////////////////////////////////////////////////////////////
170         private static void print(Token t) {
171                 GregorianCalendar exp_date = new GregorianCalendar();
172                 exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn());
173                 System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n",
174                 t.getAccessToken(),
175                 t.getTokenType(),
176                 t.getExpiresIn(),
177                 Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))),
178                 t.getScope(),
179                 t.getRefreshToken());
180         }
181         
182         private static void print(Introspect ti) {
183                 if(ti==null || ti.getClientId()==null) {
184                         System.out.println("Empty Introspect");
185                         return;
186                 }
187                 Date exp = new Date(ti.getExp()*1000); // seconds
188                 System.out.printf("Introspect\n"
189                                 + "\tAccessToken:\t%s\n"
190                                 + "\tClient-id:\t%s\n"
191                                 + "\tClient Type:\t%s\n"
192                                 + "\tActive:  \t%s\n"
193                                 + "\tUserName:\t%s\n"
194                                 + "\tExpires: \t%d (%s)\n"
195                                 + "\tScope:\t\t%s\n"
196                                 + "\tContent:\t%s\n",
197                 ti.getAccessToken(),
198                 ti.getClientId(),
199                 ti.getClientType(),
200                 ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(),
201                 ti.getUsername(),
202                 ti.getExp(),
203                 Chrono.timeStamp(exp),
204                 ti.getScope(),
205                 ti.getContent()==null?"":ti.getContent());
206                 
207                 System.out.println();
208         }
209
210 }