本文整理汇总了C#中OAuth2Authenticator类的典型用法代码示例。如果您正苦于以下问题:C# OAuth2Authenticator类的具体用法?C# OAuth2Authenticator怎么用?C# OAuth2Authenticator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
OAuth2Authenticator类属于命名空间,在下文中一共展示了OAuth2Authenticator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
public static void Main(string[] args)
{
// Display the header and initialize the sample.
CommandLine.EnableExceptionHandling();
CommandLine.DisplayGoogleSampleHeader("Tasks API");
// Register the authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials();
provider.ClientIdentifier = credentials.ClientId;
provider.ClientSecret = credentials.ClientSecret;
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new TasksService(auth);
// Execute request: Create sample list.
if (!ListExists(service, SampleListName) &&
CommandLine.RequestUserChoice("Do you want to create a sample list?"))
{
CreateSampleTasklist(service);
}
CommandLine.WriteLine();
// Execute request: List task-lists.
ListTaskLists(service);
CommandLine.PressAnyKeyToExit();
}
示例2: DirectoryService
public DirectoryService DirectoryService()
{
var provider = InitializeProvider();
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
return new DirectoryService(new BaseClientService.Initializer { Authenticator = auth });
}
示例3: LoginToFacebook
void LoginToFacebook (object sender, EventArgs e)
{
var auth = new OAuth2Authenticator (
clientId: "346691492084618",
scope: "",
authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += (s, ee) => {
if (!ee.IsAuthenticated) {
this.facebookStatus.Text = "Not Authenticated";
return;
}
// Now that we're logged in, make a OAuth2 request to get the user's info.
var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, ee.Account);
request.GetResponseAsync().ContinueWith (t => {
if (t.IsFaulted)
this.facebookStatus.Text = "Error: " + t.Exception.InnerException.Message;
else if (t.IsCanceled)
this.facebookStatus.Text = "Canceled";
else
{
var obj = JsonValue.Parse (t.Result.GetResponseText());
this.facebookStatus.Text = "Logged in as " + obj["name"];
}
}, uiScheduler);
};
var intent = auth.GetUI (this);
StartActivityForResult (intent, 42);
}
示例4: OnModelChanged
protected override void OnModelChanged(VisualElement oldModel, VisualElement newModel)
{
base.OnModelChanged(oldModel, newModel);
// this is a ViewGroup - so should be able to load an AXML file and FindView<>
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator(
clientId: "574134802616730", // your OAuth2 client id
scope: "email,user_about_me", // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"), // the auth URL for the service
redirectUrl: new Uri("https://www.cautom.com/SocialAuth/FBLogin/")); // the redirect URL for the service
auth.Completed += (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{
//App.SuccessfulLoginAction.Invoke();
// Use eventArgs.Account to do wonderful things
//App.SaveToken(eventArgs.Account.Properties["access_token"]);
string accessToken = eventArgs.Account.Properties["access_token"];
new FacebookLoginWebView().fetchUserInfoFromAccessToken(accessToken);
}
else
{
// The user cancelled
}
};
activity.StartActivity(auth.GetUI(activity));
}
示例5: OnElementChanged
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
System.Diagnostics.Debug.WriteLine ("======>Login Page OAuth");
base.OnElementChanged (e);
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator (
clientId: "621549137987350", // your OAuth2 client id
scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"), // the auth URL for the service
redirectUrl: new Uri ("http://ihbiproject.azurewebsites.net/api/Users")); // the redirect URL for the service
auth.Completed += async (sender, eventArgs) => {
if (eventArgs.IsAuthenticated) {
try {
var accessToken = eventArgs.Account.Properties ["access_token"].ToString ();
App.Instance.SaveToken(accessToken);
AccountStore.Create (activity).Save (eventArgs.Account, "WellnessFB");
var expiresIn = Convert.ToDouble (eventArgs.Account.Properties ["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds (expiresIn);
var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, eventArgs.Account);
var response = await request.GetResponseAsync ();
var obj = JObject.Parse (response.GetResponseText ());
var id = obj ["id"].ToString ().Replace ("\"", "");
var name = obj ["name"].ToString ().Replace ("\"","");
App.Instance.SuccessfulLoginAction.Invoke();
} catch (Exception ex) {
System.Diagnostics.Debug.WriteLine("========> Error getting from GraphAPI" +ex);
}
} else {
}
};
System.Diagnostics.Debug.WriteLine ("======>after OAuth");
activity.StartActivity(auth.GetUI(activity));
}
示例6: CheckAuth
public JsonResult CheckAuth()
{
const string ServiceAccountId = "ServiceAccountId.apps.googleusercontent.com";
const string ServiceAccountUser = "[email protected]";
X509Certificate2 cert = new X509Certificate2();
try
{
cert =
new X509Certificate2(
System.Web.HttpContext.Current.Server.MapPath(
"~/Content/key/0eee0d919aaef70bbb5da23b192aede576577058-privatekey.p12"), "notasecret",
X509KeyStorageFlags.Exportable);
}
catch (Exception ex)
{
}
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description, cert)
{
Scope = Oauth2Service.Scopes.UserinfoProfile.GetStringValue(),
// AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),
ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
//,ServiceAccountUser = ServiceAccountUser
};
OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
JsonResult results = Json(authenticator);
results.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return results;
}
示例7: LoginToVk
void LoginToVk()
{
var auth = new OAuth2Authenticator (
SecKey: VkSettings.SecureKey,
clientId: VkSettings.AppID,
scope: "friends,video,audio",
authorizeUrl: new Uri ("https://oauth.vk.com/authorize"),
redirectUrl: new Uri ("https://oauth.vk.com/blank.html"));
auth.AllowCancel = true;
auth.Completed += (s, ee) => {
if (!ee.IsAuthenticated) {
//TODO: THINGS IF NOT AUTHORISED
return;
}
else
{
var token = ee.Account.Properties ["access_token"].ToString ();
var uid = ee.Account.Properties ["user_id"].ToString ();
_user.VkUserInfo = new VkUserInfo(token, uid);
}
};
//TODO SOMETHING ELSE
var intent = auth.GetUI (this);
}
示例8: DownloadFile
public System.IO.Stream DownloadFile(string FileID, string CLIENT_ID, string CLIENT_SECRET, string ConnectionString)
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
var authenticator = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var service = new DriveService(authenticator);
_ConnectionString = ConnectionString;
File file = service.Files.Get(FileID).Fetch();
if (!String.IsNullOrEmpty(file.DownloadUrl))
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(file.DownloadUrl));
request.Headers.Set("Authorization", "Bearer " + authenticator.State.AccessToken.ToString());
authenticator.ApplyAuthenticationToRequest(request);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
return response.GetResponseStream();
}
else
{
throw new Exception("An error occurred: " + response.StatusDescription);
}
}
catch (Exception e)
{
throw new Exception("Downloading File Failed: " + e.Message);
}
}
else
{
// The file doesn't have any content stored on Drive.
return null;
}
}
示例9: GetAnalyticsService
/// <summary>
/// Return Analytics Service object
/// </summary>
/// <returns>Analytics Service object</returns>
public static AnalyticsService GetAnalyticsService()
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = Settings.ClientIdentifier;
provider.ClientSecret = Settings.ClientSecret;
if (string.IsNullOrWhiteSpace(provider.ClientIdentifier))
{
throw new Exception("Client identifier not found");
}
if (string.IsNullOrWhiteSpace(provider.ClientSecret))
{
throw new Exception("Client secret not found");
}
string refreshToken = Settings.RefreshToken;
if (string.IsNullOrWhiteSpace(refreshToken))
{
throw new Exception("Refresh token not found");
}
var request = HttpContext.Current.Request;
var authenticator = new OAuth2Authenticator<NativeApplicationClient>(provider, (arg) =>
{
IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/analytics.readonly" });
state.Callback = new Uri(string.Format("{0}://{1}{2}/GoogleAnalytics/Callback", request.Url.Scheme, request.Url.Host, request.Url.Port == 80 ? string.Empty : ":" + request.Url.Port));
state.RefreshToken = refreshToken;
var result = arg.RefreshToken(state);
return state;
});
return new AnalyticsService(authenticator);
}
示例10: LoginAsync
public void LoginAsync(Action<bool, Dictionary<string, string>> loginCallback)
{
var controller = UIApplication.SharedApplication.KeyWindow.RootViewController;
var auth = new OAuth2Authenticator(MeetupService.ClientId, MeetupService.ClientSecret, string.Empty, new Uri(MeetupService.AuthorizeUrl), new Uri(MeetupService.RedirectUrl), new Uri(MeetupService.AccessTokenUrl));
auth.AllowCancel = true;
auth.ShowUIErrors = false;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += (s, ee) => {
vc.DismissViewController (true, null);
if (loginCallback != null)
loginCallback (ee.IsAuthenticated, ee.Account == null ? null : ee.Account.Properties);
};
auth.Error += (sender, e) =>
{
//vc.DismissViewController(true, null);
//if (loginCallback != null)
// loginCallback (false, null);
};
vc = auth.GetUI ();
controller.PresentViewControllerAsync (vc, true);
}
示例11: LoginByGoogle
void LoginByGoogle (bool allowCancel)
{
var auth = new OAuth2Authenticator ( clientId: "847549521106-35dvaoe5jafmc5tuk2ll5054********.apps.googleusercontent.com" ,
scope: "https://www.googleapis.com/auth/userinfo.email" ,
authorizeUrl: new Uri ( "https://accounts.google.com/o/oauth2/auth" ) ,
redirectUrl: new Uri ( "https://www.googleapis.com/plus/v1/people/me" ) ,
getUsernameAsync: null );
auth.AllowCancel = allowCancel;
auth.Completed += async (sender , e ) =>
{
if ( !e.IsAuthenticated )
{
Toast.MakeText(this,"Fail to authenticate!",ToastLength.Short).Show();
return;
}
e.Account.Properties.TryGetValue ( "access_token" , out access_token );
if(await fnGetProfileInfoFromGoogle ())
{
Toast.MakeText ( this , "Authentcated successfully" , ToastLength.Short ).Show ();
}
};
var intent = auth.GetUI ( this );
StartActivity ( intent );
}
示例12: ViewDidAppear
public override void ViewDidAppear(bool animated)
{
if (!IsShown)
{
IsShown = true;
base.ViewDidAppear(animated);
var auth = new OAuth2Authenticator(
clientId: "YOUR_OAUTH2_CLIENT_ID",
scope: "WHAT_ARE_YOU_ACCESSING_DELIMITED_+_SYMBOLS",
authorizeUrl: new Uri("AUTH_URL_FOR_SERVICE"),
redirectUrl: new Uri("REDIRECT_URL_FOR_THE_SERVICE")
);
auth.Completed += (sender, eventArgs) =>
{
App.SuccessfulLoginAction.Invoke();
if (eventArgs.IsAuthenticated)
App.SaveFacebookToken(eventArgs.Account.Properties["access_token"]);
else
{
// cancelled
}
};
PresentViewController(auth.GetUI(), true, null);
}
}
示例13: OnElementChanged
protected override void OnElementChanged (ElementChangedEventArgs<Page> ee)
{
base.OnElementChanged (ee);
var activity = Context as Activity;
if (!string.IsNullOrEmpty (Settings.AccessToken)) {
return;
}
authenticator = new OAuth2Authenticator (
clientId: AuthHelpers.ClientId, // your OAuth2 client id
scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: new Uri (AuthHelpers.AuthoriseUrl), // the auth URL for the service
redirectUrl: new Uri (AuthHelpers.RedirectUrl)); // the redirect URL for the service
authenticator.Completed += (sender, e) => {
//DismissViewController (true, null);
if (e.IsAuthenticated) {
const string accessTokenKey = "access_token";
if (e.IsAuthenticated && e.Account.Properties.ContainsKey (accessTokenKey)) {
Settings.AccessToken = e.Account.Properties [accessTokenKey];
AccountStore.Create (Forms.Context).Save (e.Account, "facebook");
}
}
};
activity.StartActivity (authenticator.GetUI (activity));
}
示例14: OnElementChanged
// protected override void OnModelChanged (VisualElement oldModel, VisualElement newModel)
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged (e);
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator (
clientId: App.Current.Properties ["clientId"].ToString(),
scope: App.Current.Properties ["scope"].ToString(),
authorizeUrl: new Uri( App.Current.Properties ["authorizeUrl"].ToString()),
redirectUrl: new Uri(App.Current.Properties ["redirectUrl"].ToString())
);
auth.Completed += (sender,eventArgs) => {
if (eventArgs.IsAuthenticated){
App.Current.Properties ["access_token"] = eventArgs.Account.Properties ["access_token"].ToString();
if(App.Current.Properties ["access_token"].ToString().Length>0)
{
//use the eventargs to do good stuff
AccountStore.Create (activity).Save (eventArgs.Account, "Google");
App.Current.MainPage = new ProfilePage();
}
}
else
{
//User Cancelled
}
};
activity.StartActivity(auth.GetUI(activity));
}
示例15: CheckForValidAccessTokenTest
public void CheckForValidAccessTokenTest()
{
int accessTokenCounter = 1;
var state = new AuthorizationState();
var client = new NativeApplicationClient(new Uri("http://example.com"));
var auth = new OAuth2Authenticator<NativeApplicationClient>(
client, (clt) =>
{
// Load a "cached" access token.
state.AccessToken = "token" + (accessTokenCounter++);
return state;
});
// Check that the initial state is null.
Assert.IsNull(auth.State);
// Check that the state was set when .LoadAccessToken() is called.
auth.LoadAccessToken();
Assert.AreEqual(state, auth.State);
Assert.AreEqual("token1", auth.State.AccessToken);
// Check that it wont be set again.
auth.LoadAccessToken();
Assert.AreEqual("token1", auth.State.AccessToken);
// Check that it is set if our state gets invalid.
state.AccessToken = null;
auth.LoadAccessToken();
Assert.AreEqual("token2", auth.State.AccessToken);
}