Best NBi code snippet using NBi.Core.Api.Authentication.OAuth2
FileShareProviderBox.cs
Source:FileShareProviderBox.cs
1// ------------------------------------------------------------------------------------------------------------------------2// Copyright (c) Zoom Audits, LLC.3// 4// Created By: Tim Vidrine5// Created On: 01/25/20196// ------------------------------------------------------------------------------------------------------------------------78using System;9using System.Collections.Generic;10//using System.IdentityModel.Tokens.Jwt;11using System.IO;12using System.Net.Http;13using System.Net.Http.Headers;14using System.Security.Claims;15using System.Security.Cryptography;16using System.Threading.Tasks;17using Apollo.Core.Contracts;18using Apollo.Core.Contracts.Configuration;19using Apollo.Core.Contracts.Providers;20using Apollo.Core.Messages.Responses;21//using Box.V2.Config;22//using Box.V2.JWTAuth;23//using Microsoft.IdentityModel.Tokens;24using Newtonsoft.Json;25using Org.BouncyCastle.Crypto.Parameters;26using Org.BouncyCastle.Math;27using Org.BouncyCastle.OpenSsl;2829namespace Apollo.Infrastructure.Providers30{31 public class FileShareProviderBox 32 {33 private ILogManager _logManager;34 private IAuditConfiguration _auditConfiguration;35 private readonly HttpClient _client = new HttpClient();3637 public FileShareProviderBox(ILogManager logManager, IAuditConfiguration auditConfiguration)38 {39 _logManager = logManager;40 _auditConfiguration = auditConfiguration;41 }42 public GetResponse<string> CreateShareFolderLink(string folderName, string description)43 {44 return CreateShareFolderLinkAsync(folderName, description).Result;45 }4647 public async Task<GetResponse<string>> CreateShareFolderLinkAsync(string folderName, string description)48 { 49 var response = new GetResponse<string>();50 try51 {52 // Authorize53 var token = await GetAccessTokenAsync();545556 // Create Folder57 var baseUrl = "https://api.box.com/2.0";58 59 _client.DefaultRequestHeaders.Authorization =60 new AuthenticationHeaderValue("Bearer", token);61 62 _client.DefaultRequestHeaders.Accept.Clear();63 _client.DefaultRequestHeaders.Accept.Add(64 new MediaTypeWithQualityHeaderValue("application/json"));6566 var foo = await _client.GetAsync($@"{baseUrl}/folder/0/items");67 var fooData = await foo.Content.ReadAsStringAsync();68 var folderResponse = await _client.PostAsJsonAsync(69 $@"{baseUrl}/folders/0/",70 new71 {72 name = folderName,73 parent = new74 {75 id = 076 }77 78 });7980 var data = await folderResponse.Content.ReadAsStringAsync();8182 // Create link83 }84 catch (Exception e)85 {86 _logManager.LogError(e, "FileShareProviderBox.CreateShareLinkAsync");87 response.AddError(e);88 }8990 return response;91 }9293 private async Task<string> GetAccessTokenAsync()94 {95 // JWT Assertion96 //var config = new BoxConfig();97 //var key = GetKey(config);98 //var claims = GetClaims(config);99 //var authenticationUrl = "https://api.box.com/oauth2/token";100 //var expirationTime = DateTime.UtcNow.AddSeconds(59);101 //var payload = new JwtPayload(102 // config.BoxSettings.ClientId,103 // authenticationUrl,104 // claims,105 // null,106 // expirationTime);107 //var credentials = new SigningCredentials(new RsaSecurityKey(key), SecurityAlgorithms.RsaSha512);108109 //var header = new JwtHeader(signingCredentials: credentials);110 //var jst = new JwtSecurityToken(header, payload);111 //var tokenHandler = new JwtSecurityTokenHandler();112 //var assertion = tokenHandler.WriteToken(jst);113114 //// Authentication115 //var content = new FormUrlEncodedContent(new[]116 //{117 // // This specifies that we are using a JWT assertion118 // // to authenticate119 // new KeyValuePair<string, string>(120 // "grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"),121 // // Our JWT assertion122 // new KeyValuePair<string, string>(123 // "assertion", assertion),124 // // The OAuth 2 client ID and secret125 // new KeyValuePair<string, string>(126 // "client_id", config.BoxSettings.ClientId),127 // new KeyValuePair<string, string>(128 // "client_secret", config.BoxSettings.ClientSecret)129 // });130131 //var authResponse = await _client.PostAsync(authenticationUrl, content);132 //var data = await authResponse.Content.ReadAsStringAsync();133 //var token = JsonConvert.DeserializeObject<Token>(data);134 //return token.access_token;135 return string.Empty;136 }137 private RSA CreateRsaProvider(RSAParameters rp)138 {139 var rsaCsp = RSA.Create();140 rsaCsp.ImportParameters(rp);141142 return rsaCsp;143 }144145 private RSAParameters ToRsaParameters(RsaPrivateCrtKeyParameters privateKey)146 {147 var rp = new RSAParameters148 {149 Modulus = privateKey.Modulus.ToByteArrayUnsigned(),150 Exponent = privateKey.PublicExponent.ToByteArrayUnsigned(),151 P = privateKey.P.ToByteArrayUnsigned(),152 Q = privateKey.Q.ToByteArrayUnsigned(),153 154 };155156 rp.D = ConvertRsaParametersField(privateKey.Exponent, rp.Modulus.Length);157 rp.DP = ConvertRsaParametersField(privateKey.DP, rp.P.Length);158 rp.DQ = ConvertRsaParametersField(privateKey.DQ, rp.Q.Length);159 rp.InverseQ = ConvertRsaParametersField(privateKey.QInv, rp.Q.Length);160 return rp;161 }162163 private byte[] ConvertRsaParametersField(BigInteger n, int size)164 {165 var bs = n.ToByteArrayUnsigned();166167 if (bs.Length == size)168 return bs;169170 if(bs.Length > size)171 throw new ArgumentException("Specified size too small", "size");172173 var padded = new byte[size];174 Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);175176 return padded;177 }178179 private RSA GetKey(BoxConfig config)180 {181 182 var appAuth = config.BoxSettings.AppAuth;183 var stringReader = new StringReader(appAuth.PrivateKey);184 var passwordFinder = new PasswordFinder(appAuth.PassPhrase);185 var pemReader = new PemReader(stringReader, passwordFinder);186 var keyParams = (RsaPrivateCrtKeyParameters)pemReader.ReadObject();187 return CreateRsaProvider(ToRsaParameters(keyParams));188 }189190 private IList<Claim> GetClaims(BoxConfig config)191 {192 var randomNumber = new byte[64];193 RandomNumberGenerator.Create().GetBytes(randomNumber);194 var jti = Convert.ToBase64String(randomNumber);195196 return new List<Claim>197 {198 new Claim("sub", config.EnterpriseId),199 new Claim("box_sub_type", "enterprise"),200 new Claim("jti", jti)201 };202 }203 }204205 public class BoxConfig206 {207 public BoxConfig()208 {209 BoxSettings = new BoxSettings1();210 }211 public string EnterpriseId => "160706641";212 public BoxSettings1 BoxSettings { get; set; }213214 public class BoxSettings1215 {216 public BoxSettings1()217 {218 AppAuth = new AppAuth1();219 }220 public string ClientId => "uwlxl89u9gkrj5hqcgwsm2ft5pfqnhv2";221 public string ClientSecret => "gYRTvX8c7BxZYRO2MB0nRmY7XwK33AzK";222 public AppAuth1 AppAuth { get; set; }223 public class AppAuth1224 {225 public string PrivateKey => "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIALaAJlWtyQcCAggA\nMBQGCCqGSIb3DQMHBAhu4FeaIFh7KwSCBMjZdMGgnp/uM442vR1/oHbTwhterkf2\nY9hzPul8Yh0TNVY1JmFhor+v/zjC0nUZURHbV8G9+MyigsfOa73c2Pq3ohU3XU1s\nbiKKxnhFNXj9VuZVyC142H6TOmqImE0jLu5bjEv+Wfz/UgFvJaIXk4rsedjsDCqT\n6o+E0Lr6dFw6IIvRj0ZhF+Cd9BrEVoQ/Ai0A0KSuZMJ0r7A5DkAEUAsYFWHGBdSU\nwDMRPajRQ0K/6eyjTuIbLlzGMxJ5AJVbQzZA9OFEI6Jc4d9PDq8VK5LnyUZpAOpj\n3xzdw0U0fOf5crUWd9F3EzHoT3yc0J1ToeALEMQYfRZGr2P3Wxuka/W46y1VazPS\ntuuSvxCD47EXYCK/az92M0soGi9EfDc/DeixzMWPL5+6kLF6+sb40Cdd9bcZzE+V\n91KMzCjASioVSHZPgYn81ZFeYjlsfOB7Gi3cZXPxwOvk6B+ZFibiKMriF6TKcV5t\nKkf1ISECncaNp9ej94DY9BvynY2cGG2IXH1WWrOMF+2hz/1HdXbJ2pIZVERx/FWo\nz7VqyFRXkC8NizsPHV/AE6rysb0r1TZ6CVXYZ771Tid9ub170wJHPHOW/ZnYyUfH\ncxKfzhXeJ70V+c2kpz5WoNv0IVi38x65RdJc9B0U2/Xm0IP9jyQPWSuXIeuudAET\ntHynK2NreFP3y3aYOT52gX3t1hO199UyrQcleeoejlfV+iNkecj3w7nRKLR0JT8h\nQK0JDLwzojEojUFOPSyalrCr7qs53SjtlHUMCyZxetvn+MUoU56it34+4YN9tag0\nykTuQuzgHExrqHgTk21UeZFcHaW3bpUYfru7QolQwIzsHmWQeOV5VxrbVLF1ZxNZ\nf56N1NPlAROMukxzHMBwyVFMrtRZQ6L1ypBc+M+E51eB3AI7TCjGdEAyBrqz5w0l\nP/J12e09jxpDZpXSOO5ShWnzzwFdGzzw/gQyRX8my9NxdRWkYBwysXf2ds8b8q78\nei0BCJRMTbZP4esxWyuewnz9+fkBoEz/kA7Pqqoe21tW4DB3rXMTb6TCAIYo+Rg4\nFZBjzyZqOUoyNhvI11CRCtewnUf2NzX8fr80miwJ5wzrAHKm954laZYbxTTTqpaa\n7JiSZq5ADpJi9etc+4nGxCyUn7Odrn4OkI8yRPTs3bkeRaAKWwu2Wne3xZDL0fg5\nBFEO5lHAaozLtSHAvToeh7tJze2JWeMFfl6h95sWUESjo4o7fzI6G5ULGn/KbnTc\ntJrE0KM18kD9fDrIaVEbMo6zwnpTeDtQgAVKhYPkoPQtzf94tjsLe8NdeyI6H6RA\nSdz/+BH32rVZjUdXeu6SVdPHYXEIl9ow8wLryhbT3MNHwsJauWncJLteCzCFvACp\nv23pfhcZdHF4L+EMUMvdjiDzfrGxZdyJi0WE/j20N9BczuS8b+LsjxSfm+c45k9Y\nyAE+o6X3DzFMH1PgZ+ACx1CDNk37UnjnYtkjw8P+NuLNAQbzYflP8W07cdv4ix6K\nTOhtbYQSp2PABinEI1iQ5Z7N7p4RyTK74lpZ7q547ytBlPPwpnzneu+2RQBtgewy\nRZ8F49HDsvQTmHwdgFp2Y60BafTnI8uaFXUqCSkUtnv/iq+sLVQw9/rdJS/e0+lz\nYgQ=\n-----END ENCRYPTED PRIVATE KEY-----\n";226 public string PassPhrase => "0a779b14a32dce78bff8bbb4fd6219c7";227 public string PublicKeyId => "urzri07p";228 }229 }230 231 }232 233 public class Token234 {235 public string access_token { get; set; }236 }
...
RestHelper.cs
Source:RestHelper.cs
...57 case ApiKeyXml x: return new ApiKey(helper.InstantiateResolver<string>(x.Name), helper.InstantiateResolver<string>(x.Value));58 case HttpBasicXml x: return new HttpBasic(helper.InstantiateResolver<string>(x.Username), helper.InstantiateResolver<string>(x.Password));59 case NtmlCurrentUserXml _: return new NtlmCurrentUser();60 case NtmlUserPasswordXml x: return new NtlmUserPassword(helper.InstantiateResolver<string>(x.Username), helper.InstantiateResolver<string>(x.Password));61 case OAuth2Xml x: return new OAuth2(helper.InstantiateResolver<string>(x.AccessToken), helper.InstantiateResolver<string>(x.TokenType));62 default: throw new ArgumentOutOfRangeException();63 }64 }65 }66}...
OAuth2.cs
Source:OAuth2.cs
...7using System.Text;8using System.Threading.Tasks;9namespace NBi.Core.Api.Authentication10{11 public class OAuth2 : IAuthentication12 {13 public IScalarResolver<string> AccessToken { get; }14 public IScalarResolver<string> TokenType { get; }15 public OAuth2(IScalarResolver<string> accessToken, IScalarResolver<string> tokenType)16 => (AccessToken, TokenType) = (accessToken, tokenType);17 public OAuth2(IScalarResolver<string> accessToken)18 : this(accessToken, new LiteralScalarResolver<string>("OAuth")) { }19 public IAuthenticator GetAuthenticator() => new OAuth2AuthorizationRequestHeaderAuthenticator(AccessToken.Execute(), TokenType.Execute());20 }21}...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!