public OAuth() { InitializeComponent(); switch (Type) { case AuthType.Twitter: viewModel = new TwitterOAuthModel(); break; case AuthType.Buffer: viewModel = new BufferOAuthModel(); break; default: throw new NotImplementedException(string.Format("Type {0} unknown", Type)); } wb.Navigated += (sender, e) => viewModel.BrowserNavigated(e); wb.Navigating += (sender, e) => viewModel.BrowserNavigating(e); this.Loaded += (sender, e) => viewModel.PageLoaded(); viewModel.BrowserNavigate += (sender, e) => Dispatcher.InvokeIfRequired(() => wb.Navigate(e)); DataContext = viewModel; }
public ActionResult Callback(string oauth_token, string oauth_verifier) { var tokenSecret = (string)TempData["OAuthTokenSecret"]; Session["OAuthToken"] = oauth_token; var accessToken = _oAuthService.GetAccessToken(oauth_token, tokenSecret, oauth_verifier); var parameters = new OAuthCheckTokenParameters(oauth_token); var checkTokenResult = _flickrApi.OAuthCheckToken(parameters); ViewBag.CheckTokenResponse = checkTokenResult; var getPhotoParameters = new GetPhotosParameters(userId: "27725019@N00") .PerPage(10); var flickrPhotosResult = _flickrApi.PeopleGetPhotos(getPhotoParameters); var oAuthModel = new OAuthModel { AccessToken = accessToken, CheckTokenResult = checkTokenResult, Photos = flickrPhotosResult, }; return(View(oAuthModel)); }
public OAuthModel GetOAuthModel(OAuthAppsettingsModel oAuthAppsettingsModel, System.DateTime dateTimeNow, IElapsedTimeService elapsedTimeService, IEncodingService encodingService) { var consumerKey = !string.IsNullOrEmpty(oAuthAppsettingsModel.ConsumerKey) ? oAuthAppsettingsModel.ConsumerKey : Environment.GetEnvironmentVariable("CONSUMER_KEY"); var consumerSecret = !string.IsNullOrEmpty(oAuthAppsettingsModel.ConsumerSecret) ? oAuthAppsettingsModel.ConsumerSecret : Environment.GetEnvironmentVariable("CONSUMER_SECRET"); var accessToken = !string.IsNullOrEmpty(oAuthAppsettingsModel.AccessToken) ? oAuthAppsettingsModel.AccessToken : Environment.GetEnvironmentVariable("ACCESS_TOKEN"); var tokenSecret = !string.IsNullOrEmpty(oAuthAppsettingsModel.TokenSecret) ? oAuthAppsettingsModel.TokenSecret : Environment.GetEnvironmentVariable("TOKEN_SECRET"); var timeStamp = elapsedTimeService .UnixEpoch(dateTimeNow) .ToString(); var nonce = encodingService .ToBase64String(timeStamp); var oAuthModel = new OAuthModel() { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, AccessToken = accessToken, TokenSecret = tokenSecret, TimeStamp = timeStamp, Nonce = nonce }; if (oAuthModel.IsNullOrEmpty()) { throw new Exception("OAuthModel IsNullOrEmpty, check keys in appsettings.json or provide keys in environment variables."); } return(oAuthModel); }
public async Task <ActionResult> Login(AccountModel model) { var errmsg = string.Empty; OAuthModel token = null; var errcode = 0; try { if (string.IsNullOrEmpty(model.WorkUserId)) { throw new ArgumentNullException(nameof(model.WorkUserId)); } var user = _accountService.Login(model.Account, model.Password); if (user != null) { //业务系统绑定微信号 _accountService.BindWorkID(user.UserId, model.WorkUserId); await _unitOfWork.SaveChangesAsync(); //根据OAuth2.0 颁发令牌 token = await GetTokenAsync(user); if (token == null) { throw new Exception("令牌获取失败"); } } } catch (Exception ex) { errcode = 500; errmsg = ex.Message; } return(Content(JsonHandler.ToJson(new { errmsg, errcode, token }))); }
public IActionResult Authenticate([FromBody] OAuthModel login) { SmartHttpResult result = new SmartHttpResult(); try { var entity = DAL.SmartUser.GetEntityByName(login.UserName); if (entity != null) { var encrypted = EncryptProvider.AESEncrypt(login.PassWord, entity.Salt); if (entity.PassWord == encrypted) { //重新加密 var Saltkey = Guid.NewGuid().ToString("N"); var decrypted = EncryptProvider.AESEncrypt(login.PassWord, Saltkey); //替换密码与密钥 DAL.SmartUser.utlSmartUserByName(login.UserName, decrypted, Saltkey); var claims = new Claim[] { new Claim(ClaimTypes.Name, login.UserName), new Claim(ClaimTypes.Role, entity.Role) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.SecretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var tokenModel = new JwtSecurityToken( setting.Issuer, setting.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(setting.TokenExpires), creds); var jwtToken = new JwtTokenModel(); jwtToken.Token = new JwtSecurityTokenHandler().WriteToken(tokenModel); var tokenUser = new TokenUserModel(); tokenUser.UserName = entity.UserName; tokenUser.Email = entity.Email; tokenUser.Phone = entity.Phone; tokenUser.Avatar = entity.Avatar; jwtToken.User = tokenUser; result.Set(true, jwtToken); return(new JsonResult(result)); } else { result.Set(false, "用户密码不正确!"); } } else { result.Set(false, "用户不存在!"); } } catch (Exception err) { result.Set(false, err.Message); } return(new JsonResult(result)); }
public async Task <ActionResult> WorkLogin(string nonce) { var errmsg = string.Empty; OAuthModel token = null; var errcode = 0; try { var user = LocalCacheManager.Get <User>(nonce); if (user == null) { throw new Exception("nonce 无效或已过期"); } LocalCacheManager.Remove(nonce); if (string.IsNullOrEmpty(user.WorkUserId)) { //记录日志 throw new Exception("用户未绑定业务系统账号,请联系管理员"); } //根据OAuth2.0 颁发令牌 token = await GetTokenAsync(user); if (token == null) { throw new Exception("令牌获取失败"); } } catch (Exception ex) { errcode = 500; errmsg = ex.Message; } return(Content(JsonHandler.ToJson(new { errmsg, errcode, token }))); }
//https://api.weibo.com/2/users/counts.json public async Task <UserStatuses> GetUserStatuses(OAuthModel OAuth) { HttpClient httpClient = new HttpClient(); string userUrl = "https://api.weibo.com/2/statuses/user_timeline.json" + "?access_token=" + OAuth.access_token; Uri userUri = new Uri(userUrl); HttpResponseMessage responseMessage = await httpClient.GetAsync(userUri); StorageFile userStatus; string userInfo; if (responseMessage.IsSuccessStatusCode) { userInfo = await responseMessage.Content.ReadAsStringAsync(); userStatus = await ApplicationData.Current.LocalFolder.CreateFileAsync("UserStatus", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(userStatus, userInfo); } else { userStatus = await ApplicationData.Current.LocalFolder.GetFileAsync("UserStatus"); userInfo = await FileIO.ReadTextAsync(userStatus); } UserStatuses root = JsonConvert.DeserializeObject <UserStatuses>(userInfo); return(root); }
public async Task <UserInfoObject> GetUserInfoAsync(OAuthModel OAuth) { HttpClient httpClient = new HttpClient(); string userUrl = "https://api.weibo.com/2/users/show.json" + "?access_token=" + OAuth.access_token + "&uid=" + OAuth.uid; Uri userUri = new Uri(userUrl); HttpResponseMessage responseMessage = await httpClient.GetAsync(userUri); StorageFile userInfoFile; string userInfo = string.Empty; if (responseMessage.IsSuccessStatusCode) { userInfo = await responseMessage.Content.ReadAsStringAsync(); userInfoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("UserInfo", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(userInfoFile, userInfo); } else { userInfoFile = await ApplicationData.Current.LocalFolder.GetFileAsync("UserInfo"); if (userInfoFile != null) { userInfo = await FileIO.ReadTextAsync(userInfoFile); } } UserInfoObject root = JsonConvert.DeserializeObject <UserInfoObject>(userInfo); return(root); }
public void OAuth_given_valid_data_should_return_valid_HttpHeaderModel() { // Arrange var consumerKey = "ConsumerKey"; var consumerSecret = "ConsumerSecret"; var accessToken = "AccessToken"; var tokenSecret = "TokenSecret"; var timeStamp = "1579220112"; var nonce = "ShPKxisPFC0"; var expected = new HttpHeaderModel() { Name = "Authorization", Value = $"OAuth oauth_consumer_key=\"{consumerKey}\",oauth_token=\"{accessToken}\",oauth_signature_method=\"PLAINTEXT\",oauth_timestamp=\"{timeStamp}\",oauth_nonce=\"{nonce}\",oauth_version=\"1.0\",oauth_signature=\"{consumerSecret}%26{tokenSecret}\"" }; var oAuthModel = new OAuthModel() { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, AccessToken = accessToken, TokenSecret = tokenSecret, TimeStamp = timeStamp, Nonce = nonce }; IHttpHeaderService classUnderTest = new HttpHeaderService(); // Act var actual = classUnderTest.OAuth(oAuthModel); // Assert actual.Should().BeEquivalentTo(expected); }
public HomePage() { this.InitializeComponent(); OAuth = OAuthModel.GetOAuthModel(); weiBoAPIAccessHelper = new WeiBoAPIAccessHelper(); this.Loaded += HomePage_Loaded; }
public static async Task <bool> GetAccessTokenAsync(OAuthModel OAuth) { string URL = OAuth.OAuthBaseUri + "client_id=" + OAuth.clientId + "&response_type=code&redirect_uri=" + OAuth.redirectUri; Uri requireUri = new Uri(URL); Uri callbackUri = new Uri(OAuth.redirectUri); WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requireUri, callbackUri); switch (result.ResponseStatus) { case WebAuthenticationStatus.Success: Debug.WriteLine("success"); string responseData = result.ResponseData; string[] Data = responseData.Split('='); OAuth.code = Data[1]; string tokenUrl = "https://api.weibo.com/oauth2/access_token?client_id=" + OAuth.clientId + "&client_secret=" + OAuth.client_secret + "&grant_type=authorization_code&redirect_uri=" + OAuth.redirectUri + "&code=" + OAuth.code; Uri tokenUri = new Uri(tokenUrl); Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); var response = await httpClient.PostAsync(tokenUri, new HttpStringContent("")); Debug.WriteLine(response.Content); if (response.IsSuccessStatusCode) { var responseResult = await response.Content.ReadAsStringAsync(); Debug.WriteLine(responseResult); var splitString = responseResult.Split(new string[] { "{\"", "\",\"", "\":\"", "\":", ",\"", "\"}" }, StringSplitOptions.RemoveEmptyEntries); Debug.WriteLine(splitString.ToString()); OAuth.access_token = splitString[1]; OAuth.remind_in = splitString[3]; OAuth.expires_in = int.Parse(splitString[5]); OAuth.uid = Int64.Parse(splitString[7]); OAuth.isRealName = bool.Parse(splitString[9]); ApplicationData.Current.LocalSettings.Values["AccessToken"] = OAuth.access_token; ApplicationData.Current.LocalSettings.Values["uid"] = OAuth.uid; //{"access_token":"2.004hKTODJy_fJCc62c96775c1D7OkD","remind_in":"157679999","expires_in":157679999,"uid":"2962219841","isRealName":"true"} return(true); } else { await new MessageDialog("There is an error to get the Authorization").ShowAsync(); } break; case WebAuthenticationStatus.ErrorHttp: Debug.WriteLine("Error http"); await new MessageDialog("Error http").ShowAsync(); break; case WebAuthenticationStatus.UserCancel: Debug.WriteLine("User cancel"); await new MessageDialog("User cancel").ShowAsync(); break; } return(false); }
public static OAuthModel UserOAuthInfo(string AppId, string AppSecret, string code) { string host = "https://api.weixin.qq.com/sns/oauth2/access_token"; string url = host + $"?appid={AppId}&secret={AppSecret}&code={code}&grant_type=authorization_code"; string urlContent = HttpUtil.GetUrlContent(url); OAuthModel oAuthEntity = JsonConvert.DeserializeObject <OAuthModel>(urlContent); return(oAuthEntity); }
public void GetOAuthModel_given_valid_data_should_return_valid_OAuthModel() { // Arrange var consumerKey = "consumerKey"; var consumerSecret = "consumerSecret"; var accessToken = "accessToken"; var tokenSecret = "tokenSecret"; var timeStamp = 1579220112d; var nonce = "ShPKxisPFC0"; var dateTimeNow = System.DateTime.Now; var oAuthAppsettingsModel = new OAuthAppsettingsModel() { AccessToken = accessToken, ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, TokenSecret = tokenSecret }; var expected = new OAuthModel() { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, AccessToken = accessToken, TokenSecret = tokenSecret, TimeStamp = timeStamp.ToString(), Nonce = nonce }; IAuthorizationModelService classUnderTest = new AuthorizationModelService(); var mockElapsedTimeService = new Mock <IElapsedTimeService>(); var mockEncodingService = new Mock <IEncodingService>(); mockElapsedTimeService .Setup(x => x.UnixEpoch(dateTimeNow)) .Returns(timeStamp); mockEncodingService .Setup(x => x.ToBase64String(timeStamp.ToString())) .Returns(nonce); // Act var actual = classUnderTest.GetOAuthModel( oAuthAppsettingsModel, dateTimeNow, mockElapsedTimeService.Object, mockEncodingService.Object); // Assert actual.Should().BeEquivalentTo(expected); }
public HttpHeaderModel OAuth(OAuthModel oAuthModel) { // TODO ~ unit test this path, consider custom exception? if (oAuthModel.IsNullOrEmpty()) { throw new Exception("oAuthModel IsNullOrEmpty, check keys in appsettings.json or provide keys in environment variables."); } return(new HttpHeaderModel() { Name = "Authorization", Value = $"OAuth oauth_consumer_key=\"{oAuthModel.ConsumerKey}\",oauth_token=\"{oAuthModel.AccessToken}\",oauth_signature_method=\"{oAuthModel.SignatureMethod}\",oauth_timestamp=\"{oAuthModel.TimeStamp}\",oauth_nonce=\"{oAuthModel.Nonce}\",oauth_version=\"1.0\",oauth_signature=\"{oAuthModel.ConsumerSecret}%26{oAuthModel.TokenSecret}\"" }); }
public async Task <IActionResult> LoginPost([FromBody] OAuthModel model) { var s = HttpContext.Authentication; //ViewData["ReturnUrl"] = "/"; if (ModelState.IsValid) { var entity = DAL.SmartUser.GetEntityByName(model.UserName); if (entity != null) { var encrypted = EncryptProvider.AESEncrypt(model.PassWord, entity.Salt); if (entity.PassWord == encrypted) { //重新加密 var Saltkey = Guid.NewGuid().ToString("N"); var decrypted = EncryptProvider.AESEncrypt(model.PassWord, Saltkey); //替换密码与密钥 DAL.SmartUser.utlSmartUserByName(model.UserName, decrypted, Saltkey); //创建用户身份标识 var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); claimsIdentity.AddClaims(new List <Claim>() { new Claim(ClaimTypes.Sid, model.UserName), new Claim(ClaimTypes.Name, model.UserName), new Claim(ClaimTypes.Role, "admin"), }); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); return(Redirect("/Home/Index")); } else { ModelState.AddModelError(string.Empty, "帐号或者密码错误。"); } } else { ModelState.AddModelError(string.Empty, "用户不存在。"); } } return(View(model)); }
private bool ScopesAreValid(string[] scopes, string clientId, out string msg, out OAuthModel model) { if (scopes.Length == 0) //todo skip this if grant_type is SSO { msg = "no scopes found!"; model = null; return false; } var app = _dbContext.Apps.FirstOrDefault(a => a.ClientId == clientId); if (app == null) { msg = "invalid client id"; model = null; return false; } bool scopeOk = true; var developerInfo = _dbContext.Users.FirstOrDefault(u => u.UserName == app.Username); var oauthModel = new OAuthModel { Developer = developerInfo.Fullname, AppName = app.Name, AppDescription = app.Description, DeveloperEmail = developerInfo.Email, Scopes = app.AppScopes.Select(s => new AppScopeList { Name=s.OAuthScope.Name, Alias=s.OAuthScope.Alias, Description=s.OAuthScope.Description, }).ToList() }; string errMsg = string.Empty; foreach (var scope in scopes) { if (app.AppScopes.FirstOrDefault(s => s.OAuthScope.Name == scope) == null) { errMsg = string.Format("Scope, {0}, has not been registered with your account", scope); scopeOk = false; break; } } msg = errMsg; model = oauthModel; return scopeOk; }
public HttpService(OAuthModel authModel, IHttpHeaderService httpHeaderService, IJsonConvertService jsonConvertService) { _httpHeaderModel = httpHeaderService.OAuth(authModel); _jsonConvertService = jsonConvertService; }