/// <summary> /// Validates the passed in token should be honored /// Returns the response. /// Throws an exception containing a response if it fails /// Throws BadArgumentException if the request is bad /// FailedException if there was some other problem /// </summary> /// <param name="request"></param> /// <returns>context information from the token</returns> public TokenValidateResponse ValidateToken(TokenValidateRequest request) { ValidateRequest(request); string jwtEncodedString = request.JwtToken; string protectedUrl = request.AccessedResource; // convert string to POCO JwtSecurityToken jwtToken = new JwtSecurityToken(jwtEncodedString); TokenEntity jwtTokenEntity = _repository.GetById(jwtToken.Id); if (jwtTokenEntity == null) { throw new NotFoundException(String.Format( "JWT TokenId={0} Token not found", jwtToken.Id)); } ValidateTokenSignature(jwtEncodedString, jwtTokenEntity); // validate the basic token and the URL ValidateEncodedJwt(jwtToken, jwtTokenEntity); ValidateResourceAllowed(jwtToken, jwtTokenEntity, request.AccessedResource); TokenEntity postValidationEntity = ValidateExpirationPolicy(jwtTokenEntity); // assuming we validated and found it TokenValidateResponse response = new TokenValidateResponse() { ProtectedResource = jwtTokenEntity.ProtectedResource, Context = jwtTokenEntity.Context }; // save the updated usage count and any audit information _logger.LogDebug("Saving updated entity {0}", postValidationEntity); _repository.Update(postValidationEntity); return(response); }
public void ValidateTokenNotEffective() { TokenCreateRequest request = ttu.BuildTokenCreateRequest(); // make effective and expiration time in the past request.EffectiveTime = DateTime.Now.AddDays(+20); TokenCreateResponse createResult = serviceUnderTest.CreateToken(request); JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken receivedToken = tokenHandler.ReadJwtToken(createResult.JwtToken); // create validation request from the data used to create the token TokenValidateRequest validateThis = ttu.BuildTokenValidateRequest(createResult.JwtToken, request.ProtectedResource); try { // should fail as expired TokenValidateResponse response = serviceUnderTest.ValidateToken(validateThis); Assert.False(true, "Did not catch exception when token not yet effective"); } catch (ViolationException e) { // TODO should validate the message or something... _output.WriteLine("Caught expected exception: " + e.Message + " " + e.ServiceResponse); } }
public void ValidateTokenCountExceeded() { TokenCreateRequest request = ttu.BuildTokenCreateRequest(); TokenCreateResponse createResult = serviceUnderTest.CreateToken(request); Assert.NotNull(createResult.JwtToken); JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken receivedToken = tokenHandler.ReadJwtToken(createResult.JwtToken); Assert.NotNull(receivedToken); // create validation request from the data used to create the token TokenValidateRequest validateThis = ttu.BuildTokenValidateRequest(createResult.JwtToken, request.ProtectedResource); // first one should succeed TokenValidateResponse response1 = serviceUnderTest.ValidateToken(validateThis); // Lets jam a context validation into this test also. probably should be broken out into its own test in the future Assert.NotNull(response1.Context); try { // usage count was set to one so should now fail TokenValidateResponse response2 = serviceUnderTest.ValidateToken(validateThis); // Lets jam a context validation into this test also. probably should be broken out into its own test in the future Assert.False(true, "Did not catch exception when usage count exceeded"); } catch (ViolationException e) { _output.WriteLine("Caught expected exception: " + e.Message + " " + e.ServiceResponse); } }
private void DeserializeSerializeCompare(string jsonRep) { // convert the JSON to objects. Convert the objects to JSON. TokenValidateResponse hydrated = JsonConvert.DeserializeObject <TokenValidateResponse>(jsonRep); Assert.NotNull(hydrated); output.WriteLine("Original=" + jsonRep); string serialized = JsonConvert.SerializeObject(hydrated, Formatting.Indented); output.WriteLine("Serialized=" + serialized); // compare original JSON with results of deserialize / serialize var nodeSet1 = JsonConvert.DeserializeObject <JObject>(jsonRep); var nodeSet2 = JsonConvert.DeserializeObject <JObject>(serialized); Assert.True(JToken.DeepEquals(nodeSet1, nodeSet2), "Original JSON and results of deserialize,serialize are different token graphs"); }
public void ValidateRequestInvalid() { // set none of mandatory properties TokenValidateRequest request = new TokenValidateRequest(); try { TokenValidateResponse response = serviceUnderTest.ValidateToken(request); Assert.True(false, "Should have thrown an exception"); } catch (BadArgumentException e) { // TODO should assert all the properties called out Assert.NotNull(e.ServiceResponse); _output.WriteLine("validation messages included " + e.ServiceResponse); } }
public async Task <TokenValidateResponse> ValidateToken(TokenValidateRequest request) { var response = new TokenValidateResponse(); var project = await _projectRepository.Select(x => x.Uid == request.ProjectUid && x.IsActive); if (project.IsNotExist()) { response.SetInvalid(); response.ErrorMessages.Add("project_not_found"); return(response); } var now = DateTime.UtcNow; var token = await _tokenRepository.Select(x => x.AccessToken == request.Token && x.ExpiresAt > now); if (token.IsNotExist()) { response.SetInvalid(); return(response); } if (token.OrganizationId != project.OrganizationId) { response.SetInvalid(); return(response); } if (await _organizationRepository.Any(x => x.Id == project.OrganizationId && !x.IsActive)) { response.SetInvalid(); return(response); } response.Status = ResponseStatus.Success; return(response); }
public IActionResult Validate([FromBody] TokenValidateRequest value) { TokenValidateResponse response = _validationService.ValidateToken(value); return(Ok(response)); }