public string Get(int applicationId, LoggedInApplication app, int orgId) { if (app.IsProvider) { throw new BaseApiException("Access denied"); } // Check whether organisation is not active if (!app.Organization.IsActive) { throw new BaseException("Access denied"); } // Check whether applicaiton belongs to user if (app.ID != applicationId) { throw new BaseException("Accees denied"); } var result = _softwareStatements.Where(i => i.ApplicationID == applicationId).FirstOrDefault(i => i.ExpiredBy == null); // if not valid statements - generate a new one if (result == null) { throw new BaseApiException("No valid statements found"); } return(result.Content); }
public List <appDetails> GetProviders(string[] schemas, LoggedInApplication LoggedInApp) { if (LoggedInApp.IsProvider) { throw new BaseException("Access denied"); } var logoUrl = ConfigurationManager.AppSettings["UrlToImageInEmail"]; var resultModel = new List <appDetails>(); // Get all consumer licenses var allConsumerLicenses = _licenses.Where(i => i.ApplicationID == LoggedInApp.ID).ToList(); foreach (var schemaKey in schemas) { // Get schema with public key var schema = _schemas.FirstOrDefault(i => i.PublicID == schemaKey); if (schema == null) { throw new BaseException("Not found"); } // Get consumer licenses for schema var consumerLicenses = allConsumerLicenses.Where(i => i.DataSchemaID == schema.ID); var modelsForSchema = GetResponseModel(consumerLicenses, schema, logoUrl); // Build result model resultModel.AddRange(modelsForSchema); } return(resultModel); }
public SoftwareStatement GetNewStatement(int applicationId, int loggedInUserId, int organizationId) { var app = _applications.FirstOrDefault(i => i.ID == applicationId); // NOTE: ClientUri would be OriginHost from first token. In API - from token, which used to authorize var firstAppToken = _applicationTokens.FirstOrDefault(i => i.ApplicationID == app.ID); if (firstAppToken == null) { throw new BaseException("Unable to find application token."); } var loggedInApp = new LoggedInApplication() { ID = app.ID, Name = app.Name, PublicID = app.PublicID, IsIndustryGood = app.IsIntroducedAsIndustryGood && app.IsVerifiedAsIndustryGood, Organization = new LoggedInOrganization { ID = organizationId }, TokenUsedToAuthorize = firstAppToken.Token }; var softwareStatementForHost = GetSignedAndEncodedToken(loggedInApp); return(new SoftwareStatement { ApplicationID = applicationId, Content = softwareStatementForHost, CreatedAt = GetDate, CreatedBy = loggedInUserId }); }
public LoggedInApplication GetLoggedInApp(string referer, string apiKey) { var appToken = _tokens.FirstOrDefault(i => i.Token == apiKey); // Return error if token was not found if (appToken == null || appToken.IsExpired) { throw new BaseException($"Authorization token {apiKey} does not exists or expired."); } var application = _applications.FirstOrDefault(i => i.ID == appToken.ApplicationID); // Return error if application was not found or not active if (application == null || !application.IsActive) { throw new BaseException($"Application with token {apiKey} was not found or not active."); } // Get organization var organization = _organisations.FirstOrDefault(i => i.ID == application.OrganizationID); // Return error if organization is not active if (!organization.IsActive) { throw new BaseException("Organization is inactive."); } // Request referer must be the same as registered host for this token var originUri = new Uri(appToken.OriginHost); var providedUri = new Uri(referer); var providedReferer = $"{providedUri.Scheme}//{providedUri.Authority}"; var allowedReferer = $"{originUri.Scheme}//{originUri.Authority}"; var isValid = string.Equals(providedReferer, allowedReferer, StringComparison.CurrentCultureIgnoreCase); if (!isValid) { throw new BaseException($"Access denied. Provided referer '{referer}' is not associated with token '{apiKey}'"); } // Setup details about 'logged in' application var result = new LoggedInApplication { ID = application.ID, Name = application.Name, PublicID = application.PublicID, IsProvider = application.IsProvider, IsIndustryGood = application.IsIntroducedAsIndustryGood && application.IsVerifiedAsIndustryGood, Organization = organization.ToLoggedInOrg(), TokenUsedToAuthorize = apiKey }; return(result); }
protected override void Initialize(HttpControllerContext controllerContext) { var requestUrl = string.Empty; try { base.Initialize(controllerContext); requestUrl = controllerContext.Request?.RequestUri?.AbsolutePath; // Get referer var providedUri = Request.Headers.Referrer; if (providedUri == null) { throw new BaseException("Referrer required"); } Log.Info($"Starting request for {providedUri}"); // Get app token var authKey = controllerContext.Request.Headers.Authorization; if (authKey == null) { throw new BaseException("Authorizaton token required"); } Log.Info("API key found"); var apiKey = HttpUtility.UrlDecode(authKey.ToString()); LoggedInApplication = _applicationsService.GetLoggedInApp(providedUri.ToString(), apiKey); } catch (BaseException ex) { Log.Info($"[{requestUrl}] {ex.Message}"); throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent(ex.Message) }); } catch (Exception ex) { Log.Error($"[{requestUrl}] {ex}"); throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("Unexpected error") }); } }
public void CreateLicenseAgreement(LicenseDetails licenseDetails, LoggedInApplication loggedInApp) { if (!loggedInApp.IsProvider) { throw new BaseException("Access denied"); } var providedSchemas = licenseDetails.accepted_schemas.Split(' '); foreach (var schemaPublicId in providedSchemas) { // Get schema var schema = _dataSchemas.FirstOrDefault(i => i.PublicID == schemaPublicId); if (schema == null) { // Return error is schema was not found throw new BaseApiException($"Specified schema '{schemaPublicId}' was not found"); } // Setup Jwt reader var tokenHandler = new JwtSecurityTokenHandler(); // Read Jwt token var jwt = (JwtSecurityToken)tokenHandler.ReadToken(licenseDetails.software_statement); SecurityToken validatedToken; // Verify signature in jwt tokenHandler.ValidateToken(licenseDetails.software_statement, TokenValidationParameters, out validatedToken); // Retrieve from jwt public id for consumer application var consumerPublicId = jwt.Payload["software_id"].ToString(); var consumerAppPublicId = new Guid(consumerPublicId); // Get provider service var providerApp = _applications.FirstOrDefault(i => i.ID == loggedInApp.ID); // Get consumer application var consumerApp = _applications.FirstOrDefault(i => i.PublicID == consumerAppPublicId); if (consumerApp == null) { throw new BaseApiException($"Specified consumer '{consumerPublicId}' not found"); } // Both parties should have published data agreement for schema which must match var agreement = CreateAgreementIfNotExists(licenseDetails, consumerApp, schema, schemaPublicId, providerApp); // Skip this scope if agreement already exists if (agreement == null) { continue; } // Save new license agreement _licenseAgreements.Add(agreement); // TODO: Audit log //AuditLog.Log(AuditStream.LegalAgreements, "License agreement created", // new {LoggedInApplication.Name, LoggedInApplication.TokenUsedToAuthorize, OrgId = LoggedInApplication.Organization.ID}, // new {agreement.ID, schemaName = schema.PublicID}); // Get schema file var schemaFile = _schemaFiles.FirstOrDefault(i => i.DataSchemaID == schema.ID); // Setup url to schema var urlToSchema = _urls.ToDownloadSchema(schemaFile.ID); // Setup url to download license agreement var linkToDownloadLicense = $"{_host}{_linkToDownloadAgreement}{agreement.ID}"; // Notify legal officers about new license agreement _notificationService.LegalOfficer.LicenseAgreementCreatedInBackground(agreement.ID, linkToDownloadLicense, urlToSchema, _host); } }
private SchemaValidationResult GetValidationResult(SoftwareStatementSchema schemaDetails, Application consumerApp, LoggedInApplication loggedInApp) { var providerApp = _applications.FirstOrDefault(i => i.ID == loggedInApp.ID); var schema = _dataSchemas.FirstOrDefault(i => i.PublicID == schemaDetails.public_id); // Return error if schema with such id was not found if (schema == null) { var errorMessage = $" Provided schema '{schemaDetails.public_id}' does not exist."; return(GetErrorValidationResult(schemaDetails.public_id, errorMessage)); } // Get consumer approved requests var consumerRequests = _consumerRegistrationRequests.Where(i => i.ConsumerApplicationID == consumerApp.ID) .Where(i => i.Status == (int)ConsumerProviderRegistrationStatus.Approved); // Check whether there is a consumer request linked the provider & schema if (GetRequestThatForProvider(consumerRequests, schema.ID, providerApp.ID) != null) { return(GetSuccessValidationResult(schema.PublicID)); } // Both parties must have published data agreement which must match return(ConsumerRequestHasToBeApproved(schemaDetails.licenseId, consumerApp, providerApp, schema)); }
public StatementValidationResult GetValidationResult(string softwareStmt, string scope, LoggedInApplication loggedInApp) { if (!loggedInApp.IsProvider) { throw new BaseException("Access denied"); } // Setup response model var result = new StatementValidationResult { isSuccessfull = true, schemas = new List <SchemaValidationResult>() }; var tokenHandler = new JwtSecurityTokenHandler(); SecurityToken validatedToken; // Verify signature in jwt tokenHandler.ValidateToken(softwareStmt, TokenValidationParameters, out validatedToken); // Retrieve Jwt var jwt = (JwtSecurityToken)tokenHandler.ReadToken(softwareStmt); // Retrieve consumer application id var consumerPublicId = jwt.Payload["software_id"].ToString(); // Retrieve consumer application name var consumerAppName = jwt.Payload["client_name"].ToString(); var consumerAppPublicId = new Guid(consumerPublicId); // Get consumer application var consumerApp = _applications.FirstOrDefault(i => i.PublicID == consumerAppPublicId); // Return error if application was not found if (consumerApp == null) { var errMsg = $"Software details are not approved. Software '{consumerAppName}' with id '{consumerPublicId}' is not found"; throw new BaseException(errMsg); } // Get schemas that need to validate var requestedScope = scope.Split(' ').ToList(); // Get schemas from provided software statement var schemasFromStmt = JsonConvert.DeserializeObject <List <SoftwareStatementSchema> >(jwt.Payload["schemas"].ToString()); foreach (var schema in requestedScope) { // Get requested schema from schemas provided in software statement var schemaDetails = schemasFromStmt.FirstOrDefault(i => i.public_id == schema); // Return error if requested schema is not present in software statement if (schemaDetails == null) { var errorMessage = $" Provided schema '{schema}' does not present in software statement."; result.schemas.Add(GetErrorValidationResult(schema, errorMessage)); continue; } // Add schema validation result to response model result.schemas.Add(GetValidationResult(schemaDetails, consumerApp, loggedInApp)); } return(result); }
public string GetSignedAndEncodedToken(LoggedInApplication loggedInApp) { // Get application var consumerApplication = _applications.FirstOrDefault(i => i.ID == loggedInApp.ID); // Get applciation token var applicationToken = _applicationTokens.FirstOrDefault(i => i.Token == loggedInApp.TokenUsedToAuthorize); // Get schemas from approved var providerLicenseIds = _consumerRegistrationRequests.Where(i => i.ConsumerApplicationID == consumerApplication.ID) .Where(i => i.Status == (int)ConsumerProviderRegistrationStatus.Approved) .Select(i => i.OrganizationLicenseID); var schemasFromProviderLicenses = new List <int>(); foreach (var providerLicenseId in providerLicenseIds) { var providerLicense = _organisationLicenses.GetById(providerLicenseId); schemasFromProviderLicenses.Add(providerLicense.DataSchemaID); } // Get schemas for each agreements var schemasFromAgreements = schemasFromProviderLicenses.Distinct().ToList(); // Filter schemas var schemaIds = schemasFromAgreements.Distinct(); // Setup software statement schemas var schemas = new List <SoftwareStatementSchema>(); foreach (var schemaId in schemaIds) { var schema = _dataSchemas.FirstOrDefault(i => i.ID == schemaId); var schemaDetails = schema.ToStmtSchema(); schemas.Add(schemaDetails); } // Software statement will expire in 5 years for now. var time = GetDate.AddYears(5) - new DateTime(1970, 1, 1); var expireEpoch = (int)time.TotalSeconds; var signingCredentials = new SigningCredentials(GetSigningKey(), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); // Create Software Statement. var header = new JwtHeader(signingCredentials); var payload = new JwtPayload(); payload.AddClaim(new Claim("software_id", consumerApplication.PublicID.ToString())); payload.AddClaim(new Claim("client_name", consumerApplication.Name)); payload.AddClaim(new Claim("client_uri", applicationToken.OriginHost)); payload.AddClaim(new Claim("iss", "42e01f09-0dea-42b2-b5e1-0f1e87547329")); payload.AddClaim(new Claim("sub", "10e5766e-aff1-4b2e-b926-1a1b4ccf566c")); payload.AddClaim(new Claim("aud", "urn:oauth:scim:reg:generic")); payload.AddClaim(new Claim("exp", expireEpoch.ToString())); payload.AddClaim(new Claim("schemas", JsonConvert.SerializeObject(schemas))); payload.Base64UrlEncode(); var jwt = new JwtSecurityToken(header, payload); // Sign Software Statement. var tokenHandler = new JwtSecurityTokenHandler(); var signedAndEncodedToken = tokenHandler.WriteToken(jwt); return(signedAndEncodedToken); }