· 7 years ago · Aug 01, 2018, 05:52 PM
1app.UseTwitterAuthentication(new TwitterAuthenticationOptions()
2 {
3 ConsumerKey = "key",
4 ConsumerSecret = "qCLLsuS79YDkmr2DGiyjruV76mWZ4hVZ4EiLU1RpZkxOfDqwmh",
5 Provider = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationProvider
6 {
7 OnAuthenticated = (context) =>
8 {
9 context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_token", context.AccessToken));
10 context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_secret", context.AccessTokenSecret));
11 return Task.FromResult(0);
12 }
13 },
14 BackchannelCertificateValidator = new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(new[]
15 {
16 "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
17 "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
18 "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
19 "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
20 "‎add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
21 "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
22 "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A
23 "B13EC36903F8BF4701D498261A0802EF63642BC3" // DigiCert High Assurance EV Root CA
24 }),
25 });
26
27[AllowAnonymous]
28 public ActionResult TwitterRegistration()
29 {
30 string UrlPath = HttpContext.Request.Url.Authority;
31 // pass in the consumerkey, consumersecret, and return url to get back the token
32 NameValueCollection dict = new TwitterClient().GenerateTokenUrl(ConsumerKey, ConsumerSecret, "https://" + UrlPath + "/Account/TwitterRegistrationCallback");
33 // set a session var so we can use it when twitter calls us back
34 Session["dict"] = dict;
35 // call "authenticate" not "authorize" as the twitter docs say so the user doesn't have to reauthorize the app everytime
36 return Redirect("https://api.twitter.com/oauth/authenticate?oauth_token=" + dict["oauth_token"]);
37 }
38
39[AllowAnonymous]
40 public ActionResult TwitterRegistrationCallback(string oauth_token, string oauth_verifier)
41 {
42 TwitterClient twitterClient = new TwitterClient();
43 NameValueCollection dict = (NameValueCollection)Session["dict"];
44 NameValueCollection UserDictionary = HttpUtility.ParseQueryString(twitterClient.GetAccessToken(ConsumerKey, ConsumerSecret, oauth_token, oauth_verifier, dict));
45 TwitterUserModel twitterUser = JsonConvert.DeserializeObject<TwitterUserModel>(twitterClient.GetTwitterUser(ConsumerKey, ConsumerSecret, UserDictionary));
46 Session["twitterUser"] = twitterUser;
47
48 // Returning challenge not working just redirecting to the action inn case of twitter as we are already authenitcated
49
50 return new ChallengeResult("Twitter", Url.Action("ExternalRegistrationCallback", "Account", null));
51
52 }
53
54context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
55
56// GET: /Account/ExternalRegistrationCallback
57 [AllowAnonymous]
58 public async Task<ActionResult> ExternalRegistrationCallback()
59 {
60 //TODO: Check
61 if (User.Identity.IsAuthenticated)
62 {
63 return RedirectToAction("Index", "Manage");
64 }
65
66 var loginInfo = await _authenticationManager.GetExternalLoginInfoAsync();
67
68
69 if (Session["twitterUser"] != null)
70 {
71 //Workarround for twitter registration callback not using the challenge
72
73 loginInfo = new ExternalLoginInfo();
74 TwitterUserModel twitterUser = (TwitterUserModel)Session["twitterUser"];
75 loginInfo.Email = twitterUser.email;
76 }
77
78 if (loginInfo == null)
79 {
80 return RedirectToAction("Login");
81 }
82
83
84 // Get the information about the user from the external login provider
85 var info = await _authenticationManager.GetExternalLoginInfoAsync();
86 if (info == null)
87 {
88 return View("ExternalLoginFailure");
89 }
90
91 // Sign in the user with this external login provider if the user already has a login
92 var result = await _signInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
93 switch (result)
94 {
95 case SignInStatus.Success:
96 //User is already registered We show error and tell the user to go back to login page?
97 return RedirectToLocal((string)Session["ReturnUrl"]);
98 case SignInStatus.LockedOut:
99 return View("Lockout");
100 case SignInStatus.RequiresVerification:
101 //
102 return RedirectToAction("SendCode", new { ReturnUrl = (string)Session["ReturnUrl"], RememberMe = false });
103 case SignInStatus.Failure:
104 default:
105 // User is authenticated through the previous challange, So here needs to be saved
106
107 RegistrationBasicViewModel model = (RegistrationBasicViewModel)Session["RegistrationModel"];
108
109 //Check the user is in our db?
110 ApplicationUser user = _userManager.FindByEmail(loginInfo.Email);
111 IdentityResult identityResult;
112 if (user == null)
113 {
114
115 user = new ApplicationUser
116 {
117 UserName = loginInfo.Email,
118 Email = loginInfo.Email,
119 FirstName = model.FirstName,
120 LastName = model.LastName,
121 Nickname = model.Nickname
122 };
123 identityResult = await _userManager.CreateAsync(user);
124 }
125 else
126 {
127 //TODO : Here we might want to tell the user it already exists
128 identityResult = IdentityResult.Success;
129
130 //IdentityResult.Failed(new string[] { "User already registered" });
131 }
132
133 if (identityResult.Succeeded)
134 {
135
136 identityResult = await _userManager.AddLoginAsync(user.Id, info.Login);
137 if (identityResult.Succeeded)
138 {
139 //Adding the branch after te user is sucessfully added
140 await _signInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
141
142 _userBranchService.AddUserBranch(user.Id, model.BranchId);
143
144 //Redirect to home page
145 return RedirectToLocal((string)Session["ReturnUrl"]);
146 }
147 }
148
149 setPartnerBranchViewBag(model.PartnerId, (string) Session["partner"]);
150
151 AddErrors(identityResult);
152 return View("Register", model );
153
154
155
156 }
157 }
158
159[HttpRequestException: Response status code does not indicate success: 403 (Forbidden).]
160 System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode() +223
161 Microsoft.Owin.Security.Twitter.<ObtainRequestTokenAsync>d__23.MoveNext(
162
163[HttpRequestException: Response status code does not indicate success: 403 (Forbidden).]
164System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode() +121662
165Microsoft.Owin.Security.Twitter.<ObtainRequestTokenAsync>d__23.MoveNext() +2389
166System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
167System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
168Microsoft.Owin.Security.Twitter.<ApplyResponseChallengeAsync>d__12.MoveNext() +1091