/// <summary> /// Creates and returns a new instance of the <see cref="ServerDataServiceSqlAuth"/> class which /// connects to the specified server using the specified credentials. /// </summary> /// <param name="managementServiceUri">The server's management service <see cref="Uri"/>.</param> /// <param name="sessionActivityId">An activity ID provided by the user that should be associated with this session.</param> /// <param name="accessTokenResult">The accessToken to be used to authenticate the user.</param> /// <param name="serverName">The name of the server to connect to. (Optional)</param> /// <returns>An instance of <see cref="ServerDataServiceSqlAuth"/> class.</returns> public static ServerDataServiceSqlAuth Create( Uri managementServiceUri, Guid sessionActivityId, AccessTokenResult accessTokenResult, string serverName) { if (managementServiceUri == null) { throw new ArgumentNullException("managementServiceUri"); } if (accessTokenResult == null) { throw new ArgumentNullException("accessTokenResult"); } // Create a ServerDataServiceSqlAuth object if (serverName == null) { return(new ServerDataServiceSqlAuth( managementServiceUri, new DataServiceConnectionType(ServerModelConnectionType), sessionActivityId, accessTokenResult)); } else { return(new ServerDataServiceSqlAuth( managementServiceUri, new DataServiceConnectionType(ServerModelConnectionType, serverName), sessionActivityId, accessTokenResult)); } }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); // Just for the sake of the sample, we use a short-lived token. This can be useful to mitigate the security risks // of access tokens that are used over standard HTTP. // But this is just the lifetime of the access token. The client can still renew it using their refresh token until // the authorization itself expires. accessToken.Lifetime = TimeSpan.FromMinutes(2); // Also take into account the remaining life of the authorization and artificially shorten the access token's lifetime // to account for that if necessary. //// TODO: code here // For this sample, we assume just one resource server. // If this authorization server needs to mint access tokens for more than one resource server, // we'd look at the request message passed to us and decide which public key to return. accessToken.ResourceServerEncryptionKey = new RSACryptoServiceProvider(); accessToken.ResourceServerEncryptionKey.ImportParameters(ResourceServerEncryptionPublicKey); accessToken.AccessTokenSigningKey = CreateRSA(); var result = new AccessTokenResult(accessToken); return(result); }
public void TestGoodRequest() { var principal = AccessTokenResult.Success(new System.Security.Claims.ClaimsPrincipal()); tokenProvider.Setup(t => t.ValidateToken(It.IsAny <HttpRequest>())).Returns(principal); var userRoleEntity = new UserRoleEntity() { UserId = "TEST", RoleName = "TestRole", PartitionKey = "TestRole", RowKey = "TEST" }; var ctor = typeof(TableQuerySegment <UserRoleEntity>) .GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic) .FirstOrDefault(c => c.GetParameters().Count() == 1); var mockQuerySegment = ctor.Invoke(new object[] { new List <UserRoleEntity>() { userRoleEntity } }) as TableQuerySegment <UserRoleEntity>; userRoleRepository.Setup(t => t.Get(It.IsAny <String>())).Returns(Task.FromResult(mockQuerySegment)); var request = TestFactory.CreateHttpRequest("{\"userId\": \"TEST\",\"roleName\": \"TestRole\",}"); var response = (OkObjectResult)_fixture.Run(request, userId, testLogger); Assert.AreEqual(StatusCodes.Status200OK, response.StatusCode); var returnEntityList = (TableQuerySegment <UserRoleEntity>)response.Value; var returnEntity = returnEntityList.FirstOrDefault(); Assert.AreEqual(userRoleEntity.UserId, returnEntity.UserId); Assert.AreEqual(userRoleEntity.RoleName, returnEntity.RoleName); }
private async Task <AccessTokenResult> RefreshAccessToken(string code, bool isRefresh) { // Try to get the new token AccessTokenResult data = await GetAccessToken(code, isRefresh); if (data == null) { return(null); } // Set the expires time data.ExpiresAt = DateTime.Now.AddSeconds(int.Parse(data.ExpiresIn)); // If this was a refresh the refresh token won't be given again. // So set it to the current token. if (String.IsNullOrWhiteSpace(data.RefreshToken) && AccessTokenData != null) { data.RefreshToken = AccessTokenData.RefreshToken; } // Set it as the new data. Is is super important to remember that setting a string // on the access token won't set it into the roaming settings again because it doesn't // trigger the setter for the object! AccessTokenData = data; return(data); }
/// <summary> /// Authenticates a new user. /// </summary> /// <returns></returns> public async Task <UserManager.SignInResult> AuthNewUser() { // Try to get the request token UserManager.SignInResult result = await GetRedditRequestToken(); if (!result.WasSuccess) { return(result); } // Try to get the access token AccessTokenResult accessToken = await RefreshAccessToken(result.Message, false); if (accessToken == null) { return(new UserManager.SignInResult() { Message = "Failed to get access token" }); } return(new UserManager.SignInResult() { WasSuccess = true }); }
private VerifyCredentialsResult VerifyCredentials(AccessTokenResult accessTokenResult) { if (accessTokenResult == null) { throw new ArgumentNullException("accessTokenResult"); } if (string.IsNullOrEmpty(accessTokenResult.AccessToken)) { throw new ArgumentException("accessTokenResult.AccessToken"); } if (string.IsNullOrEmpty(accessTokenResult.AccessTokenSecret)) { throw new ArgumentException("accessTokenResult.AccessTokenSecret"); } IRestResponse <VerifyCredentialsResult> response; try { var restClient = RestClientFactory.CreateRestClient(BaseUrl); restClient.Authenticator = OAuth1Authenticator.ForProtectedResource(PublicApiKey, SecretApiKey, accessTokenResult.AccessToken, accessTokenResult.AccessTokenSecret); var restRequest = new RestRequest("1.1/account/verify_credentials.json"); TraceSource.TraceVerbose("Retrieving user information. Twitter Endpoint: {0}", restClient.BuildUri(restRequest).AbsoluteUri); response = restClient.Execute <VerifyCredentialsResult>(restRequest); } catch (Exception exception) { var errorMessage = "Failed to retrieve VerifyCredentials json data from the Twitter Api. Error Messages: " + exception.RecursiveErrorMessages(); TraceSource.TraceError(errorMessage); throw new AuthenticationException(errorMessage, exception); } if (response == null || response.StatusCode != HttpStatusCode.OK || response.Data == null) { var errorMessage = string.Format( "Failed to obtain some VerifyCredentials json data from the Facebook api OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}. Error Message: {2}.", response == null ? "-- null response --" : response.StatusCode.ToString(), response == null ? string.Empty : response.StatusDescription, response == null ? string.Empty : response.ErrorException == null ? "--no error exception--" : response.ErrorException.RecursiveErrorMessages()); TraceSource.TraceError(errorMessage); throw new AuthenticationException(errorMessage); } return(response.Data); }
private bool LoadAccessToken() { if (this.IsEffectived) { return(true); } var loadAccessTokenUrl = string.Format(LoadAccessTokenApi, this.OrgName, this.AppName); var data = new LoadAccessTokenParams() { GrantType = "client_credentials", ClientId = this.ClientId, ClientSecret = this.ClientSecret }; var tokenResponse = HttpJson(HttpDecorator.HttpMethod.POST, loadAccessTokenUrl, data); AccessTokenResult tokenResult = null; if (IsErrorResult(tokenResponse.Content)) { LogManager.GetLogger().Error("Easemob-Error(LoadAccessToken): {0}", tokenResponse.Content); return(false); } else { tokenResult = JsonConvert.DeserializeObject <AccessTokenResult>(tokenResponse.Content); this.AccessToken = tokenResult.AccessToken; this.Expires = DateTime.Now.AddSeconds(tokenResult.ExpiresIn - 60); return(true); } }
private void OnAccessTokenResult(FacebookOAuthResult oauthresult) { if (AccessTokenResult != null) { AccessTokenResult.Invoke(this, oauthresult); } }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); // Just for the sake of the sample, we use a short-lived token. This can be useful to mitigate the security risks // of access tokens that are used over standard HTTP. // But this is just the lifetime of the access token. The client can still renew it using their refresh token until // the authorization itself expires. accessToken.Lifetime = TimeSpan.FromDays(14); // Also take into account the remaining life of the authorization and artificially shorten the access token's lifetime // to account for that if necessary. //// TODO: code here // For this sample, we assume just one resource server. // If this authorization server needs to mint access tokens for more than one resource server, // we'd look at the request message passed to us and decide which public key to return. // accessToken.ResourceServerEncryptionKey = new RSACryptoServiceProvider(); accessToken.ResourceServerEncryptionKey = CreateRSA(); // string szPubKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC32W+vIY9eZYY13Z0TqONE5LG3BHH6x4EWgb/LSEV674eFRw/AOvxphM7FjvoS4auZ1Yom4G6oFjDCR917gttma2b+7IuEhV5XdHM3lbH0dSrglASKtM6uHR0qjW0FPQR6rCKMHC1xSytAudI46nr/OkpcPM8KeXgJYvp+BYE0E6gjbwydcrgULCtcC0A3mZABixshjSaxzxUWCxA9RC7hSKPp9JptEcHcrJddaWzVORZHW+lUiNcFqXsm1K4CxoXE/KHenaz7d9GtA2vAvk1miueA6tsH1UOmZUY9rNVTKLoig5kKtYePSaa9/CZTEFYnhPkQtHZNZDoiN/e327ld [email protected]"; // accessToken.ResourceServerEncryptionKey.ImportCspBlob(System.Text.Encoding.ASCII.GetBytes(szPubKey)); // accessToken.ResourceServerEncryptionKey.ImportParameters(ResourceServerEncryptionPublicKey); accessToken.AccessTokenSigningKey = CreateRSA(); var result = new AccessTokenResult(accessToken); return(result); }
public async Task <IActionResult> RunUploadTraceAttachment( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "trace/{traceId}/attachments/{fileName}")] HttpRequest req, [Blob("trace-attachments", FileAccess.Write, Connection = "TraceStorage")] CloudBlobContainer blobContainer, [AccessToken] AccessTokenResult accessTokenResult, string traceId, string fileName, ILogger log ) { log.LogInformation("Trace Attachment file"); if (accessTokenResult.Status != AccessTokenStatus.Valid) { return(new UnauthorizedResult()); } string name = $"{accessTokenResult.User.Id}/{traceId}/{fileName}"; var traceAttachmentBlob = blobContainer.GetBlockBlobReference(name); traceAttachmentBlob.Properties.ContentType = req.ContentType; traceAttachmentBlob.Metadata.Add("uid", accessTokenResult.User.Id); await traceAttachmentBlob.UploadFromStreamAsync(req.Body); return(new StatusCodeResult(200)); }
/// <summary> /// Creates and returns a new instance of the <see cref="ServerDataServiceSqlAuth"/> class which /// connects to the specified server using the specified credentials. If the server name /// is null, the default server name from the serviceRoot Uri will be used. /// </summary> /// <param name="managementServiceUri">The server's management service <see cref="Uri"/>.</param> /// <param name="sessionActivityId">An activity ID provided by the user that should be associated with this session.</param> /// <param name="credentials">The credentials to be used to authenticate the user.</param> /// <param name="serverName">The name of the server to connect to. (Optional)</param> /// <returns>An instance of <see cref="ServerDataServiceSqlAuth"/> class.</returns> public static ServerDataServiceSqlAuth Create( Uri managementServiceUri, Guid sessionActivityId, SqlAuthenticationCredentials credentials, string serverName) { if (managementServiceUri == null) { throw new ArgumentNullException("managementServiceUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } // Retrieve GetAccessToken operation Uri Uri accessUri = DataConnectionUtility.GetAccessTokenUri(managementServiceUri); // Synchronously call GetAccessToken AccessTokenResult result = DataServiceAccess.GetAccessToken(accessUri, credentials); // Validate the retrieved access token AccessTokenResult.ValidateAccessToken(managementServiceUri, result); // Create and return a ServerDataService object return(Create(managementServiceUri, sessionActivityId, result, serverName)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "example")] HttpRequest req, ILogger log, [AccessToken] AccessTokenResult accessTokenResult) { log.LogInformation($"Request received for {accessTokenResult.Principal?.Identity.Name ?? "anonymous"}."); return(new OkResult()); }
/// <summary> /// 获取凭证接口 /// </summary> /// <param name="grant_type">获取access_token填写client_credential</param> /// <param name="appid">第三方用户唯一凭证</param> /// <param name="secret">第三方用户唯一凭证密钥,既appsecret</param> /// <returns></returns> public static AccessTokenResult GetToken(string appid, string secret, string grant_type = "client_credential") { var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type, appid, secret); AccessTokenResult result = HTTPGet.GetJson <AccessTokenResult>(url); return(result); }
protected AccessTokenResult LoadToken() { if (tokenResult == null) { //正确数据,请填写微信公众账号后台的AppId及AppSecret tokenResult = CommonApi.GetToken(AppId, AppSecret); } return(tokenResult); }
public ValueTask <AccessTokenResult> RequestAccessToken() { var token = new AccessToken { Value = TestAuthHandler.AuthorizedToken.Parameter }; var result = new AccessTokenResult(AccessTokenResultStatus.Success, token, null); return(ValueTask.FromResult(result)); }
protected AccessTokenResult LoadToken() { if (tokenResult == null || string.IsNullOrEmpty(tokenResult.access_token)) { //正确数据,请填写微信公众账号后台的AppId及AppSecret tokenResult = CommonApi.GetToken(AppId, AppSecret); } return(tokenResult); }
private void AddToCache(string key, AccessTokenResult accessTokenItem) { var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromDays(cacheExpirationInDays)); lock (_lock) { _cache.SetString(key, JsonConvert.SerializeObject(accessTokenItem), options); } }
/// <summary> /// 获取凭证接口 /// </summary> /// <param name="grant_type">获取access_token填写client_credential</param> /// <param name="appid">第三方用户唯一凭证</param> /// <param name="secret">第三方用户唯一凭证密钥,既appsecret</param> /// <returns></returns> public static AccessTokenResult GetToken(string appid, string secret, string grant_type = "client_credential") { //注意:此方法不能再使用ApiHandlerWapper.TryCommonApi(),否则会循环 var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type.AsUrlData(), appid.AsUrlData(), secret.AsUrlData()); AccessTokenResult result = Get.GetJson <AccessTokenResult>(url); return(result); }
/// <summary> /// 获取微信审批数据 /// </summary> /// <param name="strSDate"></param> /// <param name="strEDate"></param> /// <returns></returns> public GetApprovalDataJsonResult GetWXSHData(string strSDate, string strEDate, string strLastNum = "") { AccessTokenResult Token = CommonApi.GetToken(Qyinfo.corpId.Trim(), CommonHelp.GetConfig("WXLCDATA")); string strReturn = ""; string access_token = Token.access_token; GetApprovalDataJsonResult obj = OaDataOpenApi.GetApprovalData(access_token, DateTime.Parse(strSDate), DateTime.Parse(strEDate), 0); return(obj); }
public static AccessTokenResult GetToken(string appid, string secret, string grant_type = "client_credential") { //注意:此方法不能再使用ApiHandlerWapper.TryCommonApi(),否则会循环 var url = string.Format(Config.ApiMpHost + "/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type.AsUrlData(), appid.AsUrlData(), secret.AsUrlData()); AccessTokenResult result = Get.GetJson <AccessTokenResult>(url);//此处为最原始接口,不再使用重试获取的封装 return(result); }
/// <summary> /// Initialize a new instance of <see cref="AccessTokenNotAvailableException"/>. /// </summary> /// <param name="navigation">The <see cref="NavigationManager"/>.</param> /// <param name="tokenResult">The <see cref="AccessTokenResult"/>.</param> /// <param name="scopes">The scopes.</param> public AccessTokenNotAvailableException( NavigationManager navigation, AccessTokenResult tokenResult, IEnumerable <string> scopes) : base(message: "Unable to provision an access token for the requested scopes: " + scopes != null ? $"'{string.Join(", ", scopes ?? Array.Empty<string>())}'" : "(default scopes)") { _tokenResult = tokenResult; _navigation = navigation; }
public EmployeeContract GetUser(AccessTokenResult tokenResult) { if (tokenResult.Status == AccessTokenStatus.Valid) { var userId = long.Parse(tokenResult.Principal.Claims.First(x => x.Type == "id").Value); return(EmployeeService.GetEmployee(userId)); } return(null); }
/// <summary> /// 【异步方法】获取凭证接口 /// </summary> /// <param name="grant_type">获取access_token填写client_credential</param> /// <param name="appid">第三方用户唯一凭证</param> /// <param name="secret">第三方用户唯一凭证密钥,既appsecret</param> /// <returns></returns> public static async Task <AccessTokenResult> GetTokenAsync(string appid, string secret, string grant_type = "client_credential") { //注意:此方法不能再使用ApiHandlerWapper.TryCommonApi(),否则会循环 var url = string.Format(WxConfig.ApiMpHost + "/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type.AsUrlData(), appid.AsUrlData(), secret.AsUrlData()); AccessTokenResult result = await Get.GetJsonAsync <AccessTokenResult>(url); return(result); }
public void TestBadRequestWithAuthToken() { var principal = AccessTokenResult.Success(new System.Security.Claims.ClaimsPrincipal()); tokenProvider.Setup(t => t.ValidateToken(It.IsAny <HttpRequest>())).Returns(principal); var request = TestFactory.CreateHttpRequest(""); var response = (BadRequestObjectResult)_fixture.Run(request, testLogger); Assert.AreEqual(response.StatusCode, StatusCodes.Status400BadRequest); }
public void TestBadRequestNoAuthToken() { var principal = AccessTokenResult.NoToken(); tokenProvider.Setup(t => t.ValidateToken(It.IsAny <HttpRequest>())).Returns(principal); var request = TestFactory.CreateHttpRequest(""); var response = (UnauthorizedResult)_fixture.Run(request, testLogger); Assert.AreEqual(response.StatusCode, StatusCodes.Status401Unauthorized); }
public ActionResult GetToken(string appId, string appSecret) { try { AccessTokenResult data = CommonApi.GetToken(appId, appSecret, "client_credential"); return(base.Json(data, JsonRequestBehavior.AllowGet)); } catch (Exception) { return(base.Json(new { error = "执行过程发生错误!" }, JsonRequestBehavior.AllowGet)); } }
public async Task <IActionResult> RunGetImageTrashTypes( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "images/trashtypes")] HttpRequest req, [AccessToken] AccessTokenResult accessTokenResult, ILogger log ) { log.LogInformation($"Get Trash Types"); IEnumerable <TrashType> result = await _imageService.GetTrashTypes(); return((ActionResult) new OkObjectResult(result)); }
public string RunGetOneImage( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "images/imgName/{fileName}")] HttpRequest req, [Blob("images2label", FileAccess.Read, Connection = "TraceStorage")] CloudBlobContainer blobContainer, [AccessToken] AccessTokenResult accessTokenResult, string fileName, ILogger log ) { log.LogInformation($"Get Image {fileName}"); return(GetImage(blobContainer, fileName)); }
/// <summary> /// 使用授权码获取登录令牌 /// </summary> /// <param name="code">授权码</param> /// <returns>登录令牌</returns> /// <remarks>2013-9-9 陶辉 创建</remarks> public Result <AccessTokenResult> GetAuthorizationCode(string code) { IDictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("client_id", config.AppKey); dic.Add("client_secret", config.AppSecret); dic.Add("grant_type", "authorization_code"); dic.Add("code", code); dic.Add("redirect_uri", config.TaobaoCallBack); dic.Add("view", "tmall"); var objectJson = JObject.Parse(new Top.Api.Util.WebUtils().DoPost(config.AccessTokenUrl, dic)); //var refreshtoken = string.Empty; AccessTokenResult data = null; if (objectJson.Property("refresh_token") != null) { data = new AccessTokenResult() { AccessToken = objectJson["access_token"].ToString(), UserNick = objectJson["taobao_user_nick"].ToString() }; } //if (!string.IsNullOrEmpty(refreshtoken)) //{ // dic.Clear(); // dic.Add("client_id", config.AppKey); // dic.Add("client_secret", config.AppSecret); // dic.Add("grant_type", "refresh_token"); // dic.Add("refresh_token", refreshtoken); // dic.Add("redirect_uri", config.TaobaoCallBack); // dic.Add("view", "tmall"); // var objJson = JObject.Parse(new Top.Api.Util.WebUtils().DoPost(config.AccessTokenUrl, dic)); // if (objJson.Property("access_token") != null) // { // data = new AccessTokenResult() { // AccessToken = objJson["access_token"].ToString(), // UserNick=objJson["taobao_user_nick"].ToString() // }; // } // //data = Hyt.Util.Serialization.JsonUtil.ToObject<AccessTokenResult>(new Top.Api.Util.WebUtils().DoPost(config.AccessTokenUrl, dic)); //} return(new Result <AccessTokenResult>() { Status = true, StatusCode = 1, Data = data }); }
public async Task <IActionResult> RunGetRandomImage( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "images/random")] HttpRequest req, [Blob("images2label", FileAccess.Read, Connection = "TraceStorage")] CloudBlobContainer blobContainer, [AccessToken] AccessTokenResult accessTokenResult, ILogger log ) { log.LogInformation($"Get Random Image"); ImageLabel result = await _imageService.GetOneImageRandom(blobContainer); return((ActionResult) new OkObjectResult(new ImageLabelViewModel(result))); }