本文整理汇总了C#中OAuth2Authenticator类的典型用法代码示例。如果您正苦于以下问题:C# OAuth2Authenticator类的具体用法?C# OAuth2Authenticator怎么用?C# OAuth2Authenticator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
OAuth2Authenticator类属于命名空间,在下文中一共展示了OAuth2Authenticator类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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();
}
开发者ID:jithuin,项目名称:infogeezer,代码行数:29,代码来源:Program.cs
示例2: DirectoryService
public DirectoryService DirectoryService()
{
var provider = InitializeProvider();
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
return new DirectoryService(new BaseClientService.Initializer { Authenticator = auth });
}
开发者ID:kaciDin,项目名称:google-apps-powershell-client,代码行数:7,代码来源:SimpleOAuth.cs
示例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);
}
开发者ID:pjcollins,项目名称:Xamarin.Auth,代码行数:33,代码来源:MainActivity.cs
示例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));
}
开发者ID:getsaurabh02,项目名称:M2EMobile,代码行数:31,代码来源:LoginPageRenderer.cs
示例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));
}
开发者ID:vash47,项目名称:ihbi-project,代码行数:34,代码来源:LoginPageRenderer.cs
示例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;
}
开发者ID:planet95,项目名称:proSEOMVC,代码行数:33,代码来源:ProfileController.cs
示例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);
}
开发者ID:Grawl,项目名称:hubbl,代码行数:26,代码来源:Authorization.cs
示例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;
}
}
开发者ID:raghulvarmams,项目名称:EImplementation,代码行数:35,代码来源:Dms.cs
示例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);
}
开发者ID:calebjenkins,项目名称:linq2ga,代码行数:36,代码来源:GoogleAnalyticsServiceManager.cs
示例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);
}
开发者ID:Tolulope,项目名称:MeetupManager,代码行数:25,代码来源:MeetupLogin.cs
示例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 );
}
开发者ID:suchithm,项目名称:LoginByGoogle_Xamarin,代码行数:27,代码来源:MainActivity.cs
示例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);
}
}
开发者ID:nodoid,项目名称:xamauth,代码行数:27,代码来源:LoginPageRenderer.cs
示例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));
}
开发者ID:nishanil,项目名称:MyMenu,代码行数:31,代码来源:LoginPageRenderer_Android.cs
示例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));
}
开发者ID:Jake-a-Lake,项目名称:GaragePrincess,代码行数:33,代码来源:LoginPageRenderer.cs
示例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);
}
开发者ID:jithuin,项目名称:infogeezer,代码行数:30,代码来源:OAuth2AuthenticatorTest.cs
示例16: OnCreate
protected override void OnCreate(Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
var auth = new OAuth2Authenticator (
clientId: "1647251678863645",
scope: "",
authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));
auth.Completed += (sender, eventArgs) => {
if (eventArgs.IsAuthenticated) {
// Use eventArgs.Account to do wonderful things
StartActivity (typeof(DashActivity));
} else {
// The user cancelled
StartActivity (typeof(MainActivity));
}
};
StartActivity (auth.GetUI (this));
}
开发者ID:sudo-wrestlers,项目名称:hackathon,代码行数:27,代码来源:LoginActivity.cs
示例17: OnElementChanged
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged (e);
// 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: "pXQhRdqeGPraG8z85f139g", // your OAuth2 client id
scope: "", // The scopes for the particular API you're accessing. The format for this will vary by API.
authorizeUrl: new Uri ("https://www.yammer.com/dialog/oauth"), // the auth URL for the service
redirectUrl: new Uri ("http://deamon.info/university/330/yammer.php")); // the redirect URL for the service
auth.Completed += (sender, eventArgs) => {
//Console.WriteLine("hi");
//Console.WriteLine(eventArgs);
if (eventArgs.IsAuthenticated) {
App.SuccessfulLoginAction.Invoke();
Console.WriteLine("yammer connected");
Console.WriteLine(eventArgs.Account);
// Use eventArgs.Account to do wonderful things
App.SaveToken(eventArgs.Account.Properties["access_token"]);
} else {
// The user cancelled
Console.WriteLine("yammer not connected");
}
//Console.WriteLine("bye");
//Console.WriteLine(App.Token);
};
activity.StartActivity (auth.GetUI(activity));
}
开发者ID:dittopower,项目名称:330-App---Tconnect,代码行数:32,代码来源:LoginPageRenderer.cs
示例18: GetAuthenticatorFromState
/// <summary>
/// Retrieve an IAuthenticator instance using the provided state.
/// </summary>
/// <param name="credentials">OAuth 2.0 credentials to use.</param>
/// <returns>Authenticator using the provided OAuth 2.0 credentials</returns>
public static IAuthenticator GetAuthenticatorFromState(IAuthorizationState credentials)
{
var provider = new StoredStateClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET, credentials);
var auth = new OAuth2Authenticator<StoredStateClient>(provider, StoredStateClient.GetState);
auth.LoadAccessToken();
return auth;
}
开发者ID:festigf,项目名称:g3,代码行数:12,代码来源:OAuth2Credential.cs
示例19: LoginToVk
void LoginToVk()
{
var auth = new OAuth2Authenticator (
clientId: "", // put your id here
scope: "friends,video,groups",
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) {
var builder = new AlertDialog.Builder (this);
builder.SetMessage ("Not Authenticated");
builder.SetPositiveButton ("Ok", (o, e) => { });
builder.Create().Show();
return;
}
else
{
token = ee.Account.Properties ["access_token"].ToString ();
userId = ee.Account.Properties ["user_id"].ToString ();
GetInfo();
}
};
var intent = auth.GetUI (this);
StartActivity (intent);
}
开发者ID:Danil410,项目名称:VkApiXamarin,代码行数:27,代码来源:MainActivity.cs
示例20: ViewDidAppear
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear (animated);
var auth = new OAuth2Authenticator(
clientId: "",
scope: "",
authorizeUrl: new Uri(""),
redirectUrl: new Uri("")
);
auth.Completed += ( sender, eventArgs) => {
//We popped the UI, so it's on us to dismiss in iOS....
App.SuccessfulLoginAction.Invoke();
if (eventArgs.IsAuthenticated){
//Use eventArgs.Account to do good stuff
App.SaveToken(eventArgs.Account.Properties["access_token"]);
}
else{
//User cancelled
}
};
PresentViewController(auth.GetUI(),true,null);
}
开发者ID:Jake-a-Lake,项目名称:GaragePrincess,代码行数:25,代码来源:LoginPageRenderer.cs
注:本文中的OAuth2Authenticator类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论