· 7 years ago · Dec 29, 2017, 10:34 AM
1using System;
2using System.Text;
3using Android.App;
4using Android.Content;
5using Android.OS;
6using Android.Widget;
7using OpenId.AppAuth;
8using Xamarin.Auth;
9
10namespace FreeHand.Message.Mail
11{
12 [Activity(Label = "MailActivity")]
13 [IntentFilter(
14 new[] { Intent.ActionView },
15 Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
16 DataSchemes = new[] { "myapplogin" })]
17 public class MailActivity :Activity
18 {
19 private static string DiscoveryEndpoint = "https://accounts.google.com/.well-known/openid-configuration";
20 private static string ClientId = "myid.apps.googleusercontent.com";
21 private static string RedirectUri = "com.googleusercontent.apps.myid:/oauth2redirect";
22
23 //private static string RedirectUri = "http://localhost";
24
25 private static string AuthEndpoint = null; // auth endpoint is discovered
26 private static string TokenEndpoint = null; // token endpoint is discovered
27 private static string RegistrationEndpoint = null; // dynamic registration not supported
28
29 readonly string TAG = typeof(MailActivity).FullName;
30 const int RC_SIGN_IN = 9001;
31 Button login,a;
32 GmailAction gmail = new GmailAction("","");
33 MailSerivce mailService;
34 private AuthorizationService authService;
35 Android.Support.CustomTabs.Chromium.SharedUtilities.CustomTabActivityHelper custom_tab_activity_helper = null;
36 protected override void OnCreate(Bundle savedInstanceState)
37 {
38 base.OnCreate(savedInstanceState);
39 SetContentView(Resource.Layout.Mail_Setting_Layout);
40
41 login = FindViewById<Button>(Resource.Id.btn_login);
42 a = FindViewById<Button>(Resource.Id.btn_sync_mail);
43
44 a.Click += delegate {
45 //gmail.Login_v2();
46 v3();
47
48 };
49 authService = new AuthorizationService(this);
50 login.Click += Login_Click;
51 custom_tab_activity_helper = new global::Android.Support.CustomTabs.Chromium.SharedUtilities.CustomTabActivityHelper();
52 }
53
54 protected override void OnStart()
55 {
56 base.OnStart();
57 custom_tab_activity_helper.BindCustomTabsService(this);
58 }
59
60 protected override void OnStop()
61 {
62 base.OnStop();
63
64 // Step 2.2 Customizing the UI - Native UI [OPTIONAL]
65 // [Chrome] Custom Tabs WarmUp and prefetch
66 custom_tab_activity_helper.UnbindCustomTabsService(this);
67
68 return;
69 }
70 private void v3()
71 {
72
73 Console.WriteLine("V3");
74 OAuth2Authenticator Auth2 = null;
75 Auth2 = new OAuth2Authenticator
76 (
77 clientId: ClientId,
78 clientSecret: null,
79
80 scope: "https://mail.google.com/",
81 authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"),
82 redirectUrl: new Uri("com.companyname.freehand:/oauth2redirect"),
83 accessTokenUrl : new Uri("https://accounts.google.com/o/oauth2/token"),
84 getUsernameAsync: null,
85 // Native UI API switch
86 // true - NEW native UI support
87 // false - OLD embedded browser API [DEFAULT]
88 // DEFAULT will be switched to true in the near future 2017-04
89 isUsingNativeUI: true
90
91 )
92 {
93 ShowErrors = true,
94 AllowCancel = false,
95 };
96 Auth2.Completed += Auth_Completed;
97 Auth2.Error += Auth_Error;
98 Auth2.BrowsingCompleted += Auth_BrowsingCompleted;
99 Intent ui_object = Auth2.GetUI(this);
100 if (Auth2.IsUsingNativeUI == true)
101 {
102 // Step 2.2 Customizing the UI - Native UI [OPTIONAL]
103 // In order to access CustomTabs API
104
105 Xamarin.Auth.CustomTabsConfiguration.AreAnimationsUsed = true;
106 Xamarin.Auth.CustomTabsConfiguration.IsShowTitleUsed = false;
107 Xamarin.Auth.CustomTabsConfiguration.IsUrlBarHidingUsed = false;
108 Xamarin.Auth.CustomTabsConfiguration.IsCloseButtonIconUsed = false;
109 Xamarin.Auth.CustomTabsConfiguration.IsActionButtonUsed = false;
110 Xamarin.Auth.CustomTabsConfiguration.IsActionBarToolbarIconUsed = false;
111 Xamarin.Auth.CustomTabsConfiguration.IsDefaultShareMenuItemUsed = false;
112 Xamarin.Auth.CustomTabsConfiguration.MenuItemTitle = null;
113 Xamarin.Auth.CustomTabsConfiguration.ToolbarColor = new Android.Graphics.Color(Resource.Color.zaloColor);
114 }
115
116 // Step 3 Present/Launch the Login UI
117 StartActivity(ui_object);
118 return;
119 }
120 void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
121 {
122
123 }
124
125 private void Auth_BrowsingCompleted(object sender, EventArgs e)
126 {
127 string title = "OAuth Browsing Completed";
128 string msg = "";
129
130 StringBuilder sb = new StringBuilder();
131 msg = sb.ToString();
132 Console.WriteLine("Auth_BrowsingCompleted "+msg);
133 }
134
135 private void Auth_Error(object sender, AuthenticatorErrorEventArgs e)
136 {
137 StringBuilder sb = new StringBuilder();
138 sb.Append("Message = ").Append(e.Message)
139 .Append(System.Environment.NewLine);
140 string msg = sb.ToString();
141 Console.WriteLine("Auth_Error: "+msg);
142 }
143
144 private void Auth_Completed(object sender, AuthenticatorCompletedEventArgs e)
145 {
146 if (!e.IsAuthenticated)
147 {
148 Console.WriteLine("Auth_Completed: not Authenticated ");
149 }
150 else
151 {
152 Account account = e.Account;
153 string token = default(string);
154 if (null != account)
155 {
156 string token_name = default(string);
157 Type t = sender.GetType();
158 if (t == typeof(Xamarin.Auth.OAuth2Authenticator))
159 {
160 token_name = "access_token";
161 token = account.Properties[token_name].ToString();
162 }
163 else if (t == typeof(Xamarin.Auth.OAuth1Authenticator))
164 {
165 token_name = "oauth_token";
166 token = account.Properties[token_name].ToString();
167 }
168 Console.WriteLine(token_name + ": " + token);
169 }
170 }
171 }
172
173 async void Login_Click(object sender, EventArgs e)
174 {
175 Console.WriteLine("initiating auth...");
176
177 try
178 {
179 AuthorizationServiceConfiguration serviceConfiguration;
180 if (DiscoveryEndpoint != null)
181 {
182 serviceConfiguration = await AuthorizationServiceConfiguration.FetchFromUrlAsync(
183 Android.Net.Uri.Parse(DiscoveryEndpoint));
184 }
185 else
186 {
187 serviceConfiguration = new AuthorizationServiceConfiguration(
188 Android.Net.Uri.Parse(AuthEndpoint),
189 Android.Net.Uri.Parse(TokenEndpoint),
190 Android.Net.Uri.Parse(RegistrationEndpoint));
191 }
192
193 Console.WriteLine("configuration retrieved, proceeding");
194 if (ClientId == null)
195 {
196 // Do dynamic client registration if no client_id
197 MakeRegistrationRequest(serviceConfiguration);
198 }
199 else
200 {
201 MakeAuthRequest(serviceConfiguration, new AuthState());
202 }
203 }
204 catch (AuthorizationException ex)
205 {
206 Console.WriteLine("Failed to retrieve configuration:" + ex);
207 }
208
209 }
210
211 private async void MakeRegistrationRequest(AuthorizationServiceConfiguration serviceConfig)
212 {
213 var registrationRequest = new RegistrationRequest.Builder(serviceConfig, new[] { Android.Net.Uri.Parse(RedirectUri) })
214 .SetTokenEndpointAuthenticationMethod(ClientSecretBasic.Name)
215 .Build();
216
217 Console.WriteLine("Making registration request to " + serviceConfig.RegistrationEndpoint);
218
219 try
220 {
221 var registrationResponse = await authService.PerformRegistrationRequestAsync(registrationRequest);
222 Console.WriteLine("Registration request complete");
223
224 if (registrationResponse != null)
225 {
226 ClientId = registrationResponse.ClientId;
227 Console.WriteLine("Registration request complete successfully");
228 // Continue with the authentication
229 MakeAuthRequest(registrationResponse.Request.Configuration, new AuthState((registrationResponse)));
230 }
231 }
232 catch (AuthorizationException ex)
233 {
234 Console.WriteLine("Registration request had an error: " + ex);
235 }
236 }
237 private void MakeAuthRequest(AuthorizationServiceConfiguration serviceConfig, AuthState authState)
238 {
239 var authRequest = new AuthorizationRequest.Builder(serviceConfig, ClientId, ResponseTypeValues.Code, Android.Net.Uri.Parse(RedirectUri))
240 .SetScope("https://mail.google.com/")
241 .Build();
242 Console.WriteLine("Making auth request to " + serviceConfig.AuthorizationEndpoint);
243 authService.PerformAuthorizationRequest(
244 authRequest,
245 TokenActivity.CreatePostAuthorizationIntent(this, authRequest, serviceConfig.DiscoveryDoc, authState),
246 authService.CreateCustomTabsIntentBuilder().Build());
247 }
248
249
250
251 }
252}