.net core identity server Custom token provider generating long token string - asp.net-core

This is how I configured my custom token provider,
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Tokens.ProviderMap.Add("CustomEmailConfirmationTokenProvider",
new TokenProviderDescriptor(typeof(CustomEmailConfirmationTokenProvider<ApplicationUser>)));
options.Tokens.EmailConfirmationTokenProvider = "CustomEmailConfirmationTokenProvider";
})
.AddEntityFrameworkStores<IdentityDbContext>()
.AddTokenProvider<CustomEmailConfirmationTokenProvider<ApplicationUser>>("CustomEmailConfirmationTokenProvider");
And this is code for custom token provider class,
public class CustomEmailConfirmationTokenProvider<TUser> : DataProtectorTokenProvider<TUser> where TUser : class
{
public CustomEmailConfirmationTokenProvider(IDataProtectionProvider dataProtectionProvider,IOptions<CustomEmailConfirmationTokenProviderOptions> options
, ILogger<DataProtectorTokenProvider<TUser>> logger)
: base(dataProtectionProvider, options,logger)
{ }
}
public class CustomEmailConfirmationTokenProviderOptions : DataProtectionTokenProviderOptions
{
public CustomEmailConfirmationTokenProviderOptions()
{
Name = "CustomEmailConfirmationTokenProvider";
TokenLifespan = TimeSpan.FromMinutes(1);
}
}
this is how I generate user token,
var myToken = await usrManager.GenerateUserTokenAsync(user, "CustomEmailConfirmationTokenProvider", UserManager<object>.ResetPasswordTokenPurpose);
and this is how I verify the token validity using custom provider,
var isValid = await usrManager.VerifyUserTokenAsync(userinfo, "CustomEmailConfirmationTokenProvider",
UserManager<object>.ResetPasswordTokenPurpose, model.Token);
The above codes,including setting of TokenLifeSpan are working fine.
But the token is generating as a long string as example below,
CfDJ8IvIvIomoPJKkcJtJSNCN4wB6Fp82OPzYvkVaHtBzJBjY9EwOBt2nMg1WudWBTc1giurpRIXhSHeJTe3CLswJEOL7nng9Hd7H/ctDVNSEL5eBnzXVZpvSNmVCvgwIg3cwSNtcjjsYmGFA01EgyEkXXkBZg+jLDiEsKU8YgmaoQd5bOLE3WLopZo2lboG7dOnZv777SMHitbQNJ2SdRyZf2aMAybKAkHnKGIR3ZSyQXRM
I want to change this toke as just 6 digits characters.
Where should I modify to solve this issue?

If you look at the asp.net sources, you will see that the default token provider is inherited from the TotpSecurityStampBasedTokenProvider DefaultEmailTokenProvider which uses the "D6" format in the GenerateAsync method TotpSecurityStampBasedTokenProvider whereas your custom provider is inherited from the DataProtectorTokenProvider which uses the Base64String format in the GenerateAsync method DataProtectorTokenProvider. I think you can try to change the base class for your custom provider to get a 6 digits token, but the Rfc6238AuthenticationService that is used by the TotpSecurityStampBasedTokenProvider has a hardcoded lifespan of 3 minutes Rfc6238AuthenticationService. For creating a custom Rfc6238AuthenticationService see this answer.
CustomEmailConfirmationTokenProvider
public class CustomEmailConfirmationTokenProvider<TUser> : TotpSecurityStampBasedTokenProvider<TUser> where TUser : class
{
private readonly TimeSpan _timeStep;
public CustomEmailConfirmationTokenProvider()
{
// Here you can setup expiration time.
_timeStep = TimeSpan.FromMinutes(1);
}
public override async Task<string> GenerateAsync(
string purpose,
UserManager<TUser> manager,
TUser user)
{
if (manager == null)
throw new ArgumentNullException(nameof(manager));
byte[] token = await manager.CreateSecurityTokenAsync(user);
string async = CustomRfc6238AuthenticationService.GenerateCode
(
token,
await this.GetUserModifierAsync(purpose, manager, user),
_timeStep
)
.ToString("D6", (IFormatProvider)CultureInfo.InvariantCulture);
token = (byte[])null;
return async;
}
public override async Task<bool> ValidateAsync(
string purpose,
string token,
UserManager<TUser> manager,
TUser user)
{
if (manager == null)
throw new ArgumentNullException(nameof(manager));
int code;
if (!int.TryParse(token, out code))
return false;
byte[] securityToken = await manager.CreateSecurityTokenAsync(user);
string userModifierAsync = await this.GetUserModifierAsync(purpose, manager, user);
return securityToken != null && CustomRfc6238AuthenticationService.ValidateCode(
securityToken,
code,
userModifierAsync,
_timeStep);
}
// It's just a dummy for inheritance.
public override Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user)
{
return Task.FromResult(true);
}
}
CustomRfc6238AuthenticationService
public static class CustomRfc6238AuthenticationService
{
private static readonly TimeSpan _timestep = TimeSpan.FromMinutes(3);
private static readonly Encoding _encoding = new UTF8Encoding(false, true);
internal static int ComputeTotp(
HashAlgorithm hashAlgorithm,
ulong timestepNumber,
byte[]? modifierBytes)
{
// # of 0's = length of pin
const int Mod = 1000000;
// See https://tools.ietf.org/html/rfc4226
// We can add an optional modifier
var timestepAsBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((long)timestepNumber));
var hash = hashAlgorithm.ComputeHash(ApplyModifier(timestepAsBytes, modifierBytes));
// Generate DT string
var offset = hash[hash.Length - 1] & 0xf;
Debug.Assert(offset + 4 < hash.Length);
var binaryCode = (hash[offset] & 0x7f) << 24
| (hash[offset + 1] & 0xff) << 16
| (hash[offset + 2] & 0xff) << 8
| (hash[offset + 3] & 0xff);
return binaryCode % Mod;
}
private static byte[] ApplyModifier(Span<byte> input, byte[] modifierBytes)
{
var combined = new byte[checked(input.Length + modifierBytes.Length)];
input.CopyTo(combined);
Buffer.BlockCopy(modifierBytes, 0, combined, input.Length, modifierBytes.Length);
return combined;
}
// More info: https://tools.ietf.org/html/rfc6238#section-4
private static ulong GetCurrentTimeStepNumber(TimeSpan timeStep)
{
var delta = DateTimeOffset.UtcNow - DateTimeOffset.UnixEpoch;
return (ulong)(delta.Ticks / timeStep.Ticks);
}
public static int GenerateCode(byte[] securityToken, string? modifier = null, TimeSpan? timeStep = null)
{
if (securityToken == null)
{
throw new ArgumentNullException(nameof(securityToken));
}
// Allow a variance of no greater than time step in either direction
var currentTimeStep = GetCurrentTimeStepNumber(timeStep ?? _timestep);
var modifierBytes = modifier is not null ? _encoding.GetBytes(modifier) : null;
using (var hashAlgorithm = new HMACSHA1(securityToken))
{
return ComputeTotp(hashAlgorithm, currentTimeStep, modifierBytes);
}
}
public static bool ValidateCode(byte[] securityToken, int code, string? modifier = null, TimeSpan? timeStep = null)
{
if (securityToken == null)
{
throw new ArgumentNullException(nameof(securityToken));
}
// Allow a variance of no greater than time step in either direction
var currentTimeStep = GetCurrentTimeStepNumber(timeStep ?? _timestep);
using (var hashAlgorithm = new HMACSHA1(securityToken))
{
var modifierBytes = modifier is not null ? _encoding.GetBytes(modifier) : null;
for (var i = -2; i <= 2; i++)
{
var computedTotp = ComputeTotp(hashAlgorithm, (ulong)((long)currentTimeStep - i), modifierBytes);
if (computedTotp == code)
{
return true;
}
}
}
// No match
return false;
}
}
Usage
var user = await _userManager.GetUserAsync(User);
if (user != null)
{
var token = await _userManager.GenerateUserTokenAsync(user, "CustomEmailConfirmationTokenProvider", UserManager<object>.ResetPasswordTokenPurpose);
var isValid = await _userManager.VerifyUserTokenAsync(user, "CustomEmailConfirmationTokenProvider", UserManager<object>.ResetPasswordTokenPurpose, token);
}
Note: This algorithm has a variance of no greater than time step in either direction.

Related

Is there a way to improve the code? .Net Core 6.0 and Cosmos Database with SQL API

It's my first time using .Net Core 6.0 WebAPI and Cosmos Database with SQL API, so I'm concerned that I've done things correctly.
I have used /address/zipcode as a partition key in the below sample
public class FamilyService : IFamilyService
{
public FamilyService(CosmosClient dbClient, string databaseName, string containerName)
{
this._container = dbClient.GetContainer(databaseName, containerName);
}
public Task<Family> GetFamilyDataAsync(string id, string zipcode)
{
return Task.FromResult(_container.GetItemLinqQueryable<Family>(allowSynchronousQueryExecution: true)
.Where(p => p.Id == id && p.Address.ZipCode == zipcode)
.ToList().First());
}
public async Task AddFamilyDataAsync(Family family)
{
await this._container.CreateItemAsync<Family>(family, new PartitionKey(family.Address.ZipCode));
}
public async Task UpdateFamilyDataAsync(Family family)
{
await this._container.ReplaceItemAsync<Family>(family, family.Id, new PartitionKey(family.Address.ZipCode));
}
public async Task DeleteFamilyDataAsync(string id, string zipcode)
{
await this._container.DeleteItemAsync<Family>(id, new PartitionKey(zipcode));
}
private async Task<bool> GetFamilyDataFromId(string id, string zipcode)
{
string query = $"select * from c where c.id=#familyId";
QueryDefinition queryDefinition = new QueryDefinition(query).WithParameter("#familyId", id);
List<Family> familyResults = new List<Family>();
FeedIterator streamResultSet = _container.GetItemQueryStreamIterator(
queryDefinition,
requestOptions: new QueryRequestOptions()
{
PartitionKey = new PartitionKey(zipcode),
MaxItemCount = 10,
MaxConcurrency = 1
});
while (streamResultSet.HasMoreResults)
{
using (ResponseMessage responseMessage = await streamResultSet.ReadNextAsync())
{
if (responseMessage.IsSuccessStatusCode)
{
dynamic streamResponse = FromStream<dynamic>(responseMessage.Content);
List<Family> familyResult = streamResponse.Documents.ToObject<List<Family>>();
familyResults.AddRange(familyResult);
}
else
{
return false;
}
}
}
if (familyResults != null && familyResults.Count > 0)
{
return true;
}
return familyResults;
}
Especially I want to focus more on those methods that retrieves the data from the database.
Update#1 : I have updated the code as suggested by #Mark Brown.
public class FamilyService : IFamilyService
{
private Container _container;
private static readonly JsonSerializer Serializer = new JsonSerializer();
public FamilyService(CosmosClient dbClient, string databaseName, string containerName)
{
this._container = dbClient.GetContainer(databaseName, containerName);
}
public async Task<Family> GetFamilyDataAsync(string id, string zipCode)
{
return await _container.ReadItemAsync<Family>(id, new PartitionKey(zipCode));
}
public async Task<List<Family>> GetAllFamilyDataAsync(string zipCode)
{
string query = $"SELECT * FROM Family";
QueryDefinition queryDefinition = new QueryDefinition(query);
List<Family> familyResults = new List<Family>();
FeedIterator<Family> feed = _container.GetItemQueryIterator<Family>(
queryDefinition,
requestOptions: new QueryRequestOptions()
{
PartitionKey = new PartitionKey(zipCode),
MaxItemCount = 10,
MaxConcurrency = 1
});
while (feed.HasMoreResults)
{
FeedResponse<Family> response = await feed.ReadNextAsync();
foreach (Family item in response)
{
familyResults.Add(item);
}
}
return familyResults;
}
public async Task<List<Family>> GetAllFamilyDataByLastNameAsync(string lastName, string zipCode)
{
string query = $"SELECT * FROM Family where Family.lastName = #lastName";
QueryDefinition queryDefinition = new QueryDefinition(query).WithParameter("#lastName", lastName);
List<Family> familyResults = new List<Family>();
FeedIterator<Family> feed = _container.GetItemQueryIterator<Family>(
queryDefinition,
requestOptions: new QueryRequestOptions()
{
PartitionKey = new PartitionKey(zipCode),
MaxItemCount = 10,
MaxConcurrency = 1
});
while (feed.HasMoreResults)
{
FeedResponse<Family> response = await feed.ReadNextAsync();
foreach (Family item in response)
{
familyResults.Add(item);
}
}
return familyResults;
}
public async Task<List<Family>> GetAllFamilyDataPaginatedAsync(int pageNumber, string zipCode)
{
int pageSize = 2;
int itemsToSkip = (pageSize * pageNumber) - pageSize;
QueryRequestOptions options = new QueryRequestOptions { MaxItemCount = pageSize };
string continuationToken = null;
List<Family> familyResults = new List<Family>();
IQueryable<Family> query = this._container
.GetItemLinqQueryable<Family>(false, continuationToken, options)
.Where(i => i.Address.ZipCode == zipCode)
.Skip(itemsToSkip);
using (FeedIterator<Family> iterator = query.ToFeedIterator<Family>())
{
FeedResponse<Family> feedResponse = await iterator.ReadNextAsync();
foreach (Family item in feedResponse)
{
familyResults.Add(item);
}
}
return familyResults;
}
public async Task AddFamilyDataAsync(Family family)
{
await this._container.CreateItemAsync<Family>(family, new PartitionKey(family.Address.ZipCode));
}
public async Task UpdateFamilyDataAsync(Family family)
{
await this._container.ReplaceItemAsync<Family>(family, family.Id, new PartitionKey(family.Address.ZipCode));
}
public async Task DeleteFamilyDataAsync(string id, string zipCode)
{
await this._container.DeleteItemAsync<Family>(id, new PartitionKey(zipCode));
}
}
If you are searching for something with the partition key and id then that can only return a single item as id must be unique within a pk. So GetFamilyDataAsync() can be implemented using ReadItemAsync() rather than a query. PS: Not sure why you would ever do this, allowSynchronousQueryExecution: true
GetFamilyDataFromId() also can be implemented using ReadItemAsync(). Even if this did require a query, it doesn't make sense to implement to return a stream, then deserialize into an object. Just use the variant that can deserialize directly into a POCO.
Can't say if this is completely optimal for everything, but you can go here to find more things as a place to start, https://learn.microsoft.com/en-us/azure/cosmos-db/sql/best-practice-dotnet
The other thing to call out is zip code as a partition key. This might work at small scale, but it could run into issues at larger scale depending on how many families and how many records for each family are stored within a single partition. Max size for a single partition key value is 20 GB. Fine for small workloads but possibly an issue at larger scale.

Creating Web Token issue

I am trying to create and use a JWT for authorization in a .Net Core 2 web api app. This line produces the error in bold below:
public string Value => new JwtSecurityTokenHandler().WriteToken(this.token);
System.ArgumentOutOfRangeException: 'IDX10603: The algorithm: 'HS256'
requires the SecurityKey.KeySize to be greater than '128' bits.
KeySize reported: '96'.'
Here is the complete code below. Source is from:
https://github.com/TahirNaushad/Fiver.Security.Bearer/blob/master/Fiver.Security.Bearer.Helpers/JwtToken.cs
[AllowAnonymous]
[HttpPost, Route("CreateToken")]
public IActionResult CreateToken([FromBody]RegisterMemberModel inputModel)
{
var token = new JwtTokenBuilder()
.AddSecurityKey(JwtSecurityKey.Create("fiversecret "))
.AddSubject("james bond")
.AddIssuer("Fiver.Security.Bearer")
.AddAudience("Fiver.Security.Bearer")
.AddClaim("MembershipId", "111")
.AddExpiry(1)
.Build();
return Ok(token.Value);
}
public sealed class JwtToken
{
private JwtSecurityToken token;
internal JwtToken(JwtSecurityToken token)
{
this.token = token;
}
public DateTime ValidTo => token.ValidTo;
public string Value => new JwtSecurityTokenHandler().WriteToken(this.token);
}
public sealed class JwtTokenBuilder
{
private SecurityKey securityKey = null;
private string subject = "";
private string issuer = "";
private string audience = "";
private Dictionary<string, string> claims = new Dictionary<string, string>();
private int expiryInMinutes = 5;
public JwtTokenBuilder AddSecurityKey(SecurityKey securityKey)
{
this.securityKey = securityKey;
return this;
}
public JwtTokenBuilder AddSubject(string subject)
{
this.subject = subject;
return this;
}
public JwtTokenBuilder AddIssuer(string issuer)
{
this.issuer = issuer;
return this;
}
public JwtTokenBuilder AddAudience(string audience)
{
this.audience = audience;
return this;
}
public JwtTokenBuilder AddClaim(string type, string value)
{
this.claims.Add(type, value);
return this;
}
public JwtTokenBuilder AddClaims(Dictionary<string, string> claims)
{
this.claims.Union(claims);
return this;
}
public JwtTokenBuilder AddExpiry(int expiryInMinutes)
{
this.expiryInMinutes = expiryInMinutes;
return this;
}
public JwtToken Build()
{
EnsureArguments();
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, this.subject),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}
.Union(this.claims.Select(item => new Claim(item.Key, item.Value)));
var token = new JwtSecurityToken(
issuer: this.issuer,
audience: this.audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(expiryInMinutes),
signingCredentials: new SigningCredentials(
this.securityKey,
SecurityAlgorithms.HmacSha256));
return new JwtToken(token);
}
private void EnsureArguments()
{
if (this.securityKey == null)
throw new ArgumentNullException("Security Key");
if (string.IsNullOrEmpty(this.subject))
throw new ArgumentNullException("Subject");
if (string.IsNullOrEmpty(this.issuer))
throw new ArgumentNullException("Issuer");
if (string.IsNullOrEmpty(this.audience))
throw new ArgumentNullException("Audience");
}
}
Block size: the size of the data block the underlying hash algorithm
operates upon. For SHA-256, this is 512 bits, for SHA-384 and SHA-512,
this is 1024 bits.
Output length: the size of the hash value produced by the underlying
hash algorithm. For SHA-256, this is 256 bits, for SHA-384 this is 384
bits, and for SHA-512, this is 512 bits.
Therefore we require a 128 bit secret key. If you want to store this as text then a 128 bit key can be represented by generating a random 32 character length string.
I got caught up in the same spot (props to the author or this howto -> ASP.NET Core 2.0 Bearer Authentication. The key length is the issue, probably a typo on the authors part.
Instead of;
JwtSecurityKey.Create("fiversecret ")
use
JwtSecurityKey.Create("fiver-secret-key")

IMemoryCache issues, cannot convert to string?

I can't enter the statement if (ConvertedAccessTokenCache.Contains(accessToken)) when I send a request in Postman, I have to check if the AccessTokenCache contains (accessToken) <- Authorization:Bearer c2E6dGVsZWFkcmU1NSxudA==....
But when it checks if it contains I get "Microsoft.Extensions.Caching.Memory.MemoryCache" as result when holding mouse over that point..
Any ideas what I am missing?
namespace ....Security.Token
{
public class TokenManager
{
private readonly IMemoryCache AccessTokenCache;
private readonly IMemoryCache RefreshTokenCache;
private CancellationTokenSource ctsAccess;
private CancellationTokenSource ctsRefresh;
private readonly uint RefreshTokenValidTime = 60 * 60 * 10; //seconds
#if DEBUG
private readonly uint TokenExpirationTime = 60 * 60 * 2; //seconds
#else
private readonly uint TokenExpirationTime = 60 * 5; //seconds
#endif
public TokenManager()
{
AccessTokenCache = new MemoryCache(new MemoryCacheOptions());
RefreshTokenCache = new MemoryCache(new MemoryCacheOptions());
ctsAccess = new CancellationTokenSource(60 * 60 * 2);
ctsRefresh = new CancellationTokenSource(60 * 60 * 10);
}
public long ValidateToken(string accessToken)
{
var ConvertedAccessTokenCache = AccessTokenCache.ToString();
if (ConvertedAccessTokenCache.Contains(accessToken))
{
var token = (TokenResponse)AccessTokenCache.Get(accessToken);
var createdDate = GetCreatedDate(accessToken);
var validToDate = createdDate.AddSeconds(token.expires_in);
var clientId = GetClientId(accessToken);
if (validToDate > SystemTime.Now())
{
return clientId;
}
}
return -1L;
}
}
}
public UserEntity GetUser(string credentials)
{
var token = new TokenManager();
var clientId = token.ValidateToken(credentials);
if (clientId == -1)
{
return null;
}
var user = Execute(context =>
{
var command = new GetCommand<UserEntity>(c => c.UserDataAccess.GetUser(clientId));
return command.Execute(null, false, context);
});
return user;
}
AccessTokenCache is an instance of MemoryCache and when you call ToString() you call it's default implementation, which returns the full-qualified name.
You need to call TryGetValue or one of the extension methods like AccessTokenCache.Get<String>("key").
Extension methods may require to declare. You need to call TryGetValue or one of the extension methods like using Microsoft.Extensions.Caching.Memory before they become available.
public long ValidateToken(string accessToken)
{
// Get<TokenResponse> or TryGetValue will return default value if not found
// which is null in case of string and classes
var token = AccessTokenCache.Get<TokenResponse>(accessToken);
if (token != null)
{
var createdDate = GetCreatedDate(accessToken);
var validToDate = createdDate.AddSeconds(token.expires_in);
var clientId = GetClientId(accessToken);
if (validToDate > SystemTime.Now())
{
return clientId;
}
}
}

Adding a new Extension to my generated certificate

I need to add a new Extension of OID 1.3.6.1.5.5.7.1.26 in my certificate. I got this OID extension in my certificate but with the following error:
Certificate Extensions: 10
[1]: ObjectId: 1.3.6.1.5.5.7.1.26 Criticality=false
Extension unknown: DER encoded OCTET string =
0000: 04 0C 30 0A 13 08 33 39 20 64 63 20 32 62 ..0...
39 dc 2b
I want this OID to be recognized similar to other extensions like AuthorityInfoAccess, etc.
Do I need to edit the jar of Bouncy Castle X509 class?
Im using ACME4j as a client and Letsencrypt Boulder as my server.
Here is the CSR Builder code for signing up the certificate.
public void sign(KeyPair keypair) throws IOException {
//Security.addProvider(new BouncyCastleProvider());
Objects.requireNonNull(keypair, "keypair");
if (namelist.isEmpty()) {
throw new IllegalStateException("No domain was set");
}
try {
GeneralName[] gns = new GeneralName[namelist.size()];
for (int ix = 0; ix < namelist.size(); ix++) {
gns[ix] = new GeneralName(GeneralName.dNSName,namelist.get(ix));
}
SignatureAlgorithmIdentifierFinder algFinder = new
DefaultSignatureAlgorithmIdentifierFinder();
GeneralNames subjectAltName = new GeneralNames(gns);
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keypair.getPublic());
ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
//extensionsGenerator.addExtension(Extension.authorityInfoAccess, true, subjectAltName);
//extensionsGenerator.addExtension(new ASN1ObjectIdentifier("TBD"), false, subjectAltName);
//extensionsGenerator.addExtension(new ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.24"), false, subjectAltName);
extensionsGenerator.addExtension(new ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.26").intern(), false, subjectAltName);
//extentionsGenerator.addExtension();
p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
PrivateKey pk = keypair.getPrivate();
/*JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(
pk instanceof ECKey ? EC_SIGNATURE_ALG : EC_SIGNATURE_ALG);
ContentSigner signer = csBuilder.build(pk);*/
if(pk instanceof ECKey)
{
AlgorithmIdentifier sigAlg = algFinder.find("SHA1withECDSA");
AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().
find(sigAlg);
ContentSigner signer = new JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).setProvider(BOUNCY_CASTL E_PROVIDER).build(keypair.getPrivate());
csr=p10Builder.build(signer);
System.out.println("ZIPED CSR ECDSA: "+csr);
}
else
{
ContentSigner signer = new JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).build(keypair.getPrivate ());
csr = p10Builder.build(signer);
System.out.println("ZIPED CSR RSA: "+csr);
}
//csr = p10Builder.build(signer);
} catch (Exception ex) {
ex.printStackTrace();;
}
}
Note: for these codes I used bcprov-jdk15on 1.56
Some comments about your code. First of all, note the ASN1 structure:
TNAuthorizationList ::= SEQUENCE SIZE (1..MAX) OF TNEntry
TNEntry ::= CHOICE {
spc [0] ServiceProviderCodeList,
range [1] TelephoneNumberRange,
one E164Number
}
Note that TNEntry is a choice, and TNAuthorizationList is a sequence of TNEntry objects. So your class name should be changed to TNEntry. In the code below, please remember that I've changed the class name to TNEntry.
I've also changed some things in this class. In getInstance(Object obj) method, the types of spc and range fields are incorrect (according to ASN1 definition, they are both sequences):
switch (tag) {
case spc:
case range: // both are sequences
return new TNEntry(tag, ASN1Sequence.getInstance(tagObj, false));
// not sure about "one" field, as it's not tagged
}
I just don't know how to handle the one field, as it's not tagged. Maybe it should be a DERIA5String, or maybe there's another type for "untagged" choices.
In this same class (remember, I've changed its name to TNEntry), I also removed the constructor public TNEntry(int tag, String name) because I'm not sure if it applies (at least I didn't need to use it, but you can keep it if you want), and I've changed toString method to return a more readable string:
public String toString() {
String sep = System.getProperty("line.separator");
StringBuffer buf = new StringBuffer();
buf.append(this.getClass().getSimpleName());
buf.append(" [").append(tag);
buf.append("]: ");
switch (tag) {
case spc:
buf.append("ServiceProviderCodeList: ").append(sep);
ASN1Sequence seq = (ASN1Sequence) this.obj;
int size = seq.size();
for (int i = 0; i < size; i++) {
// all elements are DERIA5Strings
DERIA5String str = (DERIA5String) seq.getObjectAt(i);
buf.append(" ");
buf.append(str.getString());
buf.append(sep);
}
break;
case range:
buf.append("TelephoneNumberRange: ").append(sep);
// there are always 2 elements in TelephoneNumberRange
ASN1Sequence s = (ASN1Sequence) this.obj;
DERIA5String str = (DERIA5String) s.getObjectAt(0);
buf.append(" start: ");
buf.append(str.getString());
buf.append(sep);
ASN1Integer count = (ASN1Integer) s.getObjectAt(1);
buf.append(" count: ");
buf.append(count.toString());
buf.append(sep);
break;
default:
buf.append(obj.toString());
}
return buf.toString();
}
And I also created a TNAuthorizationList class, which holds the sequence of TNEntry objects (remember that I've changed your class name to TNEntry, so this TNAuthorizationList class is a different one). Note that I also created a constant to hold the OID (just to make things a little bit easier):
public class TNAuthorizationList extends ASN1Object {
// put OID in a constant, so I don't have to remember it all the time
public static final ASN1ObjectIdentifier TN_AUTH_LIST_OID = new ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.26");
private TNEntry[] entries;
public TNAuthorizationList(TNEntry[] entries) {
this.entries = entries;
}
public static TNAuthorizationList getInstance(Object obj) {
if (obj instanceof TNAuthorizationList) {
return (TNAuthorizationList) obj;
}
if (obj != null) {
return new TNAuthorizationList(ASN1Sequence.getInstance(obj));
}
return null;
}
public static TNAuthorizationList getInstance(ASN1TaggedObject obj, boolean explicit) {
return getInstance(ASN1Sequence.getInstance(obj, explicit));
}
private TNAuthorizationList(ASN1Sequence seq) {
this.entries = new TNEntry[seq.size()];
for (int i = 0; i != seq.size(); i++) {
entries[i] = TNEntry.getInstance(seq.getObjectAt(i));
}
}
public TNEntry[] getEntries() {
TNEntry[] tmp = new TNEntry[entries.length];
System.arraycopy(entries, 0, tmp, 0, entries.length);
return tmp;
}
#Override
public ASN1Primitive toASN1Primitive() {
return new DERSequence(entries);
}
public String toString() {
String sep = System.getProperty("line.separator");
StringBuffer buf = new StringBuffer();
buf.append(this.getClass().getSimpleName());
buf.append(":").append(sep);
for (TNEntry tnEntry : entries) {
buf.append(" ");
buf.append(tnEntry.toString());
buf.append(sep);
}
return buf.toString();
}
}
Now, to add this extension to a certificate, I've done this code (with some sample data as I don't know what should be in each field in a real world situation):
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(etc...);
// create TNEntries for TNAuthorizationList
TNEntry[] entries = new TNEntry[2];
// create a "spc" entry
DERIA5String[] cList = new DERIA5String[] { new DERIA5String("spc1"), new DERIA5String("spc2") };
DERSequence spc = new DERSequence(cList);
entries[0] = TNEntry.getInstance(new DERTaggedObject(false, TNEntry.spc, spc));
// create a "range" entry
DERSequence range = new DERSequence(new ASN1Encodable[] { new DERIA5String("123456"), new ASN1Integer(1) });
entries[1] = TNEntry.getInstance(new DERTaggedObject(false, TNEntry.range, range));
TNAuthorizationList tnAuthList = new TNAuthorizationList(entries);
builder.addExtension(TNAuthorizationList.TN_AUTH_LIST_OID, false, tnAuthList);
Once you have the certificate object (a X509Certificate in my example), you can do:
// cert is a X509Certificate instance
ASN1Primitive value = X509ExtensionUtil.fromExtensionValue(cert.getExtensionValue(TNAuthorizationList.TN_AUTH_LIST_OID.getId()));
TNAuthorizationList authList = TNAuthorizationList.getInstance(value);
System.out.println(authList.toString());
The output will be:
TNAuthorizationList:
TNEntry [0]: ServiceProviderCodeList:
spc1
spc2
TNEntry [1]: TelephoneNumberRange:
start: 123456
count: 1
Notes:
As I said, this code is incomplete because I'm not sure how to handle the one field of TNEntry, because it's not tagged (I don't know if it must be a DERIA5String or if there's another type of object for an "untagged" field).
You could also do some improvements:
ServiceProviderCodeList can have 1 to 3 elements, so you could validate its size
TelephoneNumberRange: the start field has a specific format (FROM ("0123456789#*") which I think it means only these characters are accepted), so you could also validate it
To create the values for ServiceProviderCodeList and TelephoneNumberRange, I've created the DERSequence objects by hand, but you can create custom classes for them if you want: ServiceProviderCodeList could hold a list of DERIA5String and perform proper validations in its constructor (size from 1 to 3), and TelephoneNumberRange could have start and count fields (with proper validation of start value) - and toASN1Primitive just need to return a DERSequence of its fields in the right order
For your parsing issues, I've checked acme4j code and it uses a java.security.cert.X509Certificate class. The toString() method of this class (when using Sun's default provider) is generating this "extension unknown" output (according to the corresponding code).
So, in order to parse it correctly (show the formatted output as described above), you'll probably have to change acme4j's code (or write your own), creating a new toString() method and include the new TNAuthorizationList classes in this method.
When you provide the code showing how you're using acme4j, I'll update this answer accordingly, if needed.
As the OID 1.3.6.1.5.5.7.1.26 is still a draft, I believe it's very unlikely that tools and systems like Let's Encrypt recognize this extension (they'll probably do it after this extension becomes official, and I really don't know the bureaucratic process behind such approvals).
Which means you'll probably have to code it. I've been using Bouncy Castle for a couple of years but never had to create a new ASN1 structure. But if I had to, I'd take a look at its source code as an initial guidance.
Considering the ASN1 structure of this extension:
TNAuthorizationList ::= SEQUENCE SIZE (1..MAX) OF TNEntry
TNEntry ::= CHOICE {
spc [0] ServiceProviderCodeList,
range [1] TelephoneNumberRange,
one E164Number
}
ServiceProviderCodeList ::= SEQUENCE SIZE (1..3) OF IA5String
-- Service Provider Codes may be OCNs, various SPIDs, or other
-- SP identifiers from the telephone network
TelephoneNumberRange ::= SEQUENCE {
start E164Number,
count INTEGER
}
E164Number ::= IA5String (SIZE (1..15)) (FROM ("0123456789#*"))
The extension value must be a SEQUENCE of TNEntry. So you could use ASN1Sequence (or its subclass DERSequence) and put instances of TNEntry inside it.
To create a TNEntry, you need to implement ASN1Choice (take a look at source of GeneralName class and do something similar).
And so on, until you have the whole structure mapped to their respective classes, using Bouncy Castle built-in classes to support you (there are DERIA5String for IA5String and DERInteger for INTEGER, which can be used in ServiceProviderCodeList and TelephoneNumberRange)
After that you can build your own parser, which can recognize this extension. But as I said, don't expect other tools to recognize it.
Right now, for testing purpose , Im just passing a string value from my CA Boulder. So to read that, this is the custom ASN1 Object STructure for TNAUthList.
public class TNAuthorizationList extends ASN1Object implements ASN1Choice{
public static final int spc = 0;
public static final int range = 1;
private ASN1Encodable obj;
private int tag;
public TNAuthorizationList(
int tag,
ASN1Encodable name)
{
this.obj = name;
this.tag = tag;
}
public TNAuthorizationList(
int tag,
String name)
{
this.tag = tag;
if (tag == spc)
{
this.obj = new DERIA5String(name);
}
else if (tag == range)
{
this.obj = new ASN1ObjectIdentifier(name);
}
else
{
throw new IllegalArgumentException("can't process String for tag: " + tag);
}
}
public static TNAuthorizationList getInstance(
Object obj)
{
if (obj == null || obj instanceof TNAuthorizationList)
{
return (TNAuthorizationList)obj;
}
if (obj instanceof ASN1TaggedObject)
{
ASN1TaggedObject tagObj = (ASN1TaggedObject)obj;
int tag = tagObj.getTagNo();
switch (tag)
{
case spc:
return new TNAuthorizationList(tag, DERIA5String.getInstance(tagObj, false));
}
}
if (obj instanceof byte[])
{
try
{
return getInstance(ASN1Primitive.fromByteArray((byte[])obj));
}
catch (IOException e)
{
throw new IllegalArgumentException("unable to parse encoded general name");
}
}
throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName());
}
public static TNAuthorizationList getInstance(
ASN1TaggedObject tagObj,
boolean explicit)
{
return TNAuthorizationList.getInstance(ASN1TaggedObject.getInstance(tagObj, true));
}
public int getTagNo()
{
return tag;
}
public ASN1Encodable getSpc()
{
return obj;
}
public String toString()
{
StringBuffer buf = new StringBuffer();
buf.append(tag);
buf.append(": ");
switch (tag)
{
case spc:
buf.append(DERIA5String.getInstance(obj).getString());
break;
default:
buf.append(obj.toString());
}
return buf.toString();
}
/**
*TNEntry ::= CHOICE {
* spc [0] ServiceProviderCodeList,
* range [1] TelephoneNumberRange,
* one E164Number
* }
*/
#Override
public ASN1Primitive toASN1Primitive() {
// TODO Auto-generated method stub
return new DERTaggedObject(false, tag, obj);
}
}
As You suggested I have passed the OID value to X509Util class and printed the Output.
ASN1Object o = X509ExtensionUtil.fromExtensionValue(cert.getExtensionValue("1.3.6.1.5.5.7.1.26"));
System.out.println("ASN1 Object: "+o);
System.out.println("get Class "+o.getClass());
and the O/P is
ASN1 Object: [SPID : 39 dc 2b]
get Class class org.bouncycastle.asn1.DLSequence
Is this fine. How do i parse this with my custom ASN1 Structure?
This is how im using ACME4j.
public class RSASignedCertificate {
private static final int KEY_SIZE = 2048;
private static final Logger LOG = Logger.getLogger(CCIDClient.class);
#SuppressWarnings("unused")
public void fetchCertificate(String domain,String spid, String email, int port,
String username, String password, String certPath) throws Exception {
// Load or create a key pair for the user's account
boolean createdNewKeyPair = true;
KeyPair domainKeyPair = null;
DomainKeyStore details = null;
KeyPair userKeyPair = null;
userKeyPair = KeyPairUtils.createKeyPair(KEY_SIZE);
DateFormat dateTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date;
details = new DomainKeyStore();
// Create Hibernate Util class Object
// dao=new HibernateDAO();
boolean isDomainExist = new HibernateDAO().isDomainExist(domain);
if (isDomainExist) {
details.setDomain(domain);
details.setEmail(email);
date = new Date();
details.setUpdatedOn(dateTime.parse(dateTime.format(date)));
boolean updateresult = new HibernateDAO().updateDetails(details);
LOG.info("User Details Updated ");
}
else {
date = new Date();
// Date currentDateTime = dateTime.parse(dateTime.format(date));
details.setEmail(email);
details.setDomain(domain);
details.setStatus("Not Registered");
details.setCreatedOn(dateTime.parse(dateTime.format(date)));
details.setUpdatedOn(dateTime.parse(dateTime.format(date)));
boolean isInserted = new HibernateDAO().insertDetails(details);
if (!isInserted) {
throw new AcmeException("Unable to insert details");
}
LOG.info("User Details inserted ");
}
// details=dao.getDetails(domain);
Session session = null;
if (userKeyPair != null) {
session = new Session("http://192.168.1.143:4000/directory", userKeyPair);
System.out.println(session.getServerUri().toString());
System.out.println(session.resourceUri(Resource.NEW_REG));
}
Registration reg = null;
try {
reg = new RegistrationBuilder().create(session);
LOG.info("Registered a new user, URI: " + reg.getLocation());
} catch (AcmeConflictException ex) {
reg = Registration.bind(session, ex.getLocation());
LOG.info("Account does already exist, URI: " + reg.getLocation());
}
date = new Date();
details.setStatus("Registered");
details.setRegistrationDate(dateTime.parse(dateTime.format(date)));
details.setUpdatedOn(dateTime.parse(dateTime.format(date)));
new HibernateDAO().updateRegistration(details);
URI agreement = reg.getAgreement();
LOG.info("Terms of Service: " + agreement);
if (createdNewKeyPair) {
boolean accepted = acceptAgreement(reg, agreement);
if (!accepted) {
return;
}
}
Authorization auth = null;
try {
auth = reg.authorizeDomain(spid);
} catch (AcmeUnauthorizedException ex) {
// Maybe there are new T&C to accept?
boolean accepted = acceptAgreement(reg, agreement);
if (!accepted) {
return;
}
// Then try again...
auth = reg.authorizeDomain(spid);
}
LOG.info("New authorization for domain " + spid);
LOG.info("Authorization " + auth);
Challenge challenge = tokenChallenge(auth);
// System.out.println("Challendg status before trigger :"+challenge.getStatus());
if (challenge == null) {
throw new AcmeException("No Challenge found");
}
if (challenge.getStatus() == Status.VALID) {
return;
}
challenge.trigger();
int attempts = 1;
// System.out.println("Challendg status after trigger :"+challenge.getStatus());
while (challenge.getStatus() != Status.VALID && attempts-- > 0) {
// System.out.println(challenge.getStatus());
if (challenge.getStatus().equals(Status.PENDING)) {
challenge.update();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
LOG.warn("interrupted", e);
e.printStackTrace();
}
}
if (challenge.getStatus() == Status.INVALID) {
LOG.error("Challenge failed... Giving up.");
throw new AcmeServerException("Challenge Failed");
}
try {
Thread.sleep(3000L);
} catch (InterruptedException ex) {
LOG.warn("interrupted", ex);
}
challenge.update();
}
if (challenge.getStatus() != Status.VALID) {
LOG.error("Failed to pass the challenge... Giving up.");
throw new AcmeServerException("Challenge Failed");
}
date = new Date();
details.setStatus("Clallenge Completed");
details.setUpdatedOn(dateTime.parse(dateTime.format(date)));
new HibernateDAO().updateChallenge(details);
domainKeyPair = KeyPairUtils.createKeyPair(KEY_SIZE);
// Generate a CSR for the domain
CSRBuilder csrb = new CSRBuilder();
csrb.addDomains(spid);
csrb.sign(domainKeyPair);
// System.out.println("CSR:" +csrb.getCSR());
LOG.info("Keys Algorithm: "
+ domainKeyPair.getPrivate().getAlgorithm());
PrivateKeyStore privatekey = new PrivateKeyStore();
privatekey.setDomain(spid);
privatekey.setEmail(email);
privatekey.setPrivateKey(domainKeyPair.getPrivate().getEncoded());
PublicKeyStore publickey = new PublicKeyStore();
publickey.setDomain(spid);
publickey.setEmail(email);
publickey.setPublicKey(domainKeyPair.getPublic().getEncoded());
// Request a signed certificate
Certificate certificate = reg.requestCertificate(csrb.getEncoded());
LOG.info("Success! The certificate for spids " + spid
+ " has been generated!");
LOG.info("Certificate URI: " + certificate.getLocation());
String nameFile = spid.replace(".", "") + ".cer";
X509Certificate sscert = CertificateUtils.createTlsSniCertificate(domainKeyPair,spid);
System.out.println("Certificate :" +sscert);
ASN1Primitive o = X509ExtensionUtil.fromExtensionValue(sscert.getExtensionValue(TNAuthorizationList.TN_AUTH_LIST_OID.getId()));
System.out.println("ASN1:Object "+o+" class: "+o.getClass());
TNAuthorizationList TNList = TNAuthorizationList.getInstance(o);
System.out.println(TNList.toString());
File createFile = new File(certPath + nameFile);
if (!createFile.exists()) {
createFile.createNewFile();
}
try (FileWriter fw = new FileWriter(createFile.getAbsoluteFile())) {
CertificateUtils.writeX509Certificate(sscert, fw);
System.out.println("Certificate " + sscert);
System.out.println("Certificate Content" + fw);
}
date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 90);
details.setIssueDate(dateTime.parse(dateTime.format(date)));
details.setUpdatedOn(dateTime.parse(dateTime.format(date)));
details.setValidUntil(dateTime.parse(dateTime.format(c.getTime())));
details.setStatus("Issued");
details.setCertPath(certPath + nameFile);
new HibernateDAO().updateCertificate(details);
}
public boolean acceptAgreement(Registration reg, URI agreement) throws AcmeException
{
reg.modify().setAgreement(agreement).commit();
LOG.info("Updated user's ToS");
return true;
}
public Challenge tokenChallenge(Authorization auth)
{
TokenChallenge chall = auth.findChallenge(TokenChallenge.TYPE);
LOG.info("File name: " + chall.getType());
//LOG.info("Content: " + chall.`);
return chall;
}

how to use paging in new graph facebook v4

I have tried the code below but I am getting an error.How can I use paging in v4 facebook after/within login?
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request2 = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
JSONObject uu= response.getJSONObject();
if (uu!=null){
Log.w(TAG, "respomse: " + response.toString());
}
GraphRequest nextPageRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
if (nextPageRequest != null) {
nextPageRequest.setCallback(new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
}
});

 
 
 nextPageRequest.executeBatchAsync(
}
}
});
Bundle parameters2 = new Bundle();
parameters2.putString("fields", "likes");
parameters2.putString("limit", "999");
request2.setParameters(parameters2);
request2.executeAsync();
});
}
}
I use this code within my User class. Every time a new user signs up using Facebook, this gets executed by calling get_user_data() within the User constructor.
For the below example to work for you too, you'll need an access token with the following permissions:
user_friends
email
Constants:
private ArrayList<HashMap> user_fb_friends;
private final String FIELDS = "id,first_name,last_name,name,gender,locale,timezone,updated_time,email,link,picture,friends{id,first_name,last_name,name,gender,updated_time,link,picture}";
private final String USER_FB_ID_TAG = "id";
private final String F_NAME_TAG = "first_name";
private final String L_NAME_TAG = "last_name";
private final String FULL_NAME_TAG = "name";
private final String GENDER_TAG = "gender";
private final String LOCALE_TAG = "locale";
private final String TIMEZONE_TAG = "timezone";
private final String UPDATED_TIME_TAG = "updated_time";
private final String EMAIL_TAG = "email";
private final String LINK_TAG = "link";
private final String PICTURE_TAG = "picture";
private final String DATA_TAG = "data";
private final String IS_SILHOUETTE_TAG = "is_silhouette";
private final String URL_TAG = "url";
private final String FRIENDS_TAG = "friends";
private final String PAGING_TAG = "paging";
private final String NEXT_TAG = "next";
private final String SUMMARY_TAG = "summary";
private final String TOTAL_COUNT_TAG = "total_count";
Actual code:
(the following code includes local setters)
private void get_user_data(){
GraphRequest request = GraphRequest.newMeRequest(
Signup_fragment.mAccessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject json = response.getJSONObject();
if(json != null){
try {
user_fb_friends = new ArrayList<>();
/*
* Start parsing the JSON
* 1. Pars the user personal details and save them on new User class
*/
setUser_fb_id(json.getString(USER_FB_ID_TAG));
setF_name(json.getString(F_NAME_TAG));
setL_name(json.getString(L_NAME_TAG));
setFull_name(json.getString(FULL_NAME_TAG));
setGender(json.getString(GENDER_TAG));
setLocale(json.getString(LOCALE_TAG));
setTimezone(json.getInt(TIMEZONE_TAG));
setUpdated_time((Date) json.get(UPDATED_TIME_TAG));
setEmail(json.getString(EMAIL_TAG));
setFb_profile_link(json.getString(LINK_TAG));
Utils.log("User prsonal data was collected (" + getFull_name() + ")");
JSONObject pic_wrapper = json.getJSONObject(PICTURE_TAG);
JSONObject pic_data = pic_wrapper.getJSONObject(DATA_TAG);
if(!pic_data.getBoolean(IS_SILHOUETTE_TAG)){
setFb_profile_pic_link(pic_data.getString(URL_TAG));
}
/*
* 2. Go over the jsonArry of friends, pars and save each friend
* in a HashMap object and store it in user_fb_friends array
*/
JSONObject friends_wrapper = json.getJSONObject(FRIENDS_TAG);
JSONArray friends_json_array = friends_wrapper.getJSONArray(DATA_TAG);
if(friends_json_array.length() > 0){
for (int i = 0; i < friends_json_array.length(); i++) {
HashMap<String, String> friend_hashmap = new HashMap<String, String>();
JSONObject friend_json = friends_json_array.getJSONObject(i);
friend_hashmap.put(USER_FB_ID_TAG, friend_json.getString(USER_FB_ID_TAG));
friend_hashmap.put(F_NAME_TAG, friend_json.getString(F_NAME_TAG));
friend_hashmap.put(L_NAME_TAG, friend_json.getString(L_NAME_TAG));
friend_hashmap.put(FULL_NAME_TAG, friend_json.getString(FULL_NAME_TAG));
friend_hashmap.put(GENDER_TAG, friend_json.getString(GENDER_TAG));
friend_hashmap.put(UPDATED_TIME_TAG, friend_json.getString(UPDATED_TIME_TAG));
friend_hashmap.put(LINK_TAG, friend_json.getString(LINK_TAG));
JSONObject friend_pic_wrapper = json.getJSONObject(PICTURE_TAG);
JSONObject friend_pic_data = friend_pic_wrapper.getJSONObject(DATA_TAG);
if(!friend_pic_data.getBoolean(IS_SILHOUETTE_TAG)){
friend_hashmap.put(URL_TAG, friend_pic_data.getString(URL_TAG));
}
user_fb_friends.add(friend_hashmap);
Utils.log("A friend was added to user_fb_friends (" + i + ")");
}
/*
* 3. Get the URL for the next "friends" JSONObject and send
* a GET request
*/
JSONObject paging_wrapper = json.getJSONObject(PAGING_TAG);
String next_friends_json_url = null;
if(paging_wrapper.getString(NEXT_TAG) != null){
next_friends_json_url = paging_wrapper.getString(NEXT_TAG);
}
JSONObject summary_wrapper = json.getJSONObject(SUMMARY_TAG);
int total_friends_count = summary_wrapper.getInt(TOTAL_COUNT_TAG);
if(next_friends_json_url != null){
/*
* Send a GET request for the next JSONObject
*/
get_paging_data(response);
}
} else {
Utils.log("friends_json_array == null");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", FIELDS);
request.setParameters(parameters);
request.executeAsync();
}
private void get_paging_data(GraphResponse response){
GraphRequest nextRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
Utils.log("get_paging_data was called");
nextRequest.setCallback(new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
JSONObject json = response.getJSONObject();
if (json != null) {
try {
JSONArray friends_json_array = json.getJSONArray(DATA_TAG);
for (int i = 0; i < friends_json_array.length(); i++) {
HashMap<String, String> friend_hashmap = new HashMap<String, String>();
JSONObject friend_json = friends_json_array.getJSONObject(i);
friend_hashmap.put(USER_FB_ID_TAG, friend_json.getString(USER_FB_ID_TAG));
friend_hashmap.put(F_NAME_TAG, friend_json.getString(F_NAME_TAG));
friend_hashmap.put(L_NAME_TAG, friend_json.getString(L_NAME_TAG));
friend_hashmap.put(FULL_NAME_TAG, friend_json.getString(FULL_NAME_TAG));
friend_hashmap.put(GENDER_TAG, friend_json.getString(GENDER_TAG));
friend_hashmap.put(UPDATED_TIME_TAG, friend_json.getString(UPDATED_TIME_TAG));
friend_hashmap.put(LINK_TAG, friend_json.getString(LINK_TAG));
JSONObject friend_pic_wrapper = json.getJSONObject(PICTURE_TAG);
JSONObject friend_pic_data = friend_pic_wrapper.getJSONObject(DATA_TAG);
if (!friend_pic_data.getBoolean(IS_SILHOUETTE_TAG)) {
friend_hashmap.put(URL_TAG, friend_pic_data.getString(URL_TAG));
}
user_fb_friends.add(friend_hashmap);
Utils.log("A friend was added to user_fb_friends (" + i + ")");
}
JSONObject paging_wrapper = json.getJSONObject(PAGING_TAG);
String next_friends_json_url = null;
if (paging_wrapper.getString(NEXT_TAG) != null) {
next_friends_json_url = paging_wrapper.getString(NEXT_TAG);
}
JSONObject summary_wrapper = json.getJSONObject(SUMMARY_TAG);
if (next_friends_json_url != null) {
/*
* 3. Send a GET request for the next JSONObject
*/
get_paging_data(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
response = nextRequest.executeAndWait();
}
Before you go ahead and try to pars your JSON, first check what your JSON will look like. You can check that using Facebook's Graph Explorer at: https://developers.facebook.com/tools/explorer/
IMPORTANT: Only friends who installed this app are returned in API v2.0 and higher. total_count in summary represents the total number of friends, including those who haven't installed the app. More >>