{
	"info": {
		"_postman_id": "2af93349-7f74-4c19-921e-d64de3c857d2",
		"name": "Fortress API - User Authentication",
		"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
		"_exporter_id": "19401943"
	},
	"item": [
		{
			"name": "User Authentication",
			"item": [
				{
					"name": "0 - abrir URL en navegador",
					"event": [
						{
							"listen": "test",
							"script": {
								"exec": [
									"console.info('copiar y pegar esta URL en un browser');",
									"console.info('****************************************************');",
									"console.info(pm.environment.get(\"url\")+\"/oauth2/v1/auth?scope=certificate&client_id=\"+pm.environment.get(\"client_id\")+\"&redirect_uri=\"+pm.collectionVariables.get(\"redirect_uri\"));",
									"",
									"",
									"console.info('INSTRUCCIONES TRAS SUPERAR LOS FACTORES DE PROTECCIÓN DE USO DEL CERTIFICADO SELECCIONADO:');",
									"console.info('  - copiar el queryParam \"code\" incluido en la URL, por ejemplo: \"ee847760b62e4c80a138c742cc297ec7\"');",
									"console.info('  - usar el \"code\" como valor de la variable \"code\".');"
								],
								"type": "text/javascript"
							}
						}
					],
					"request": {
						"method": "GET",
						"header": [],
						"url": {
							"raw": "{{url}}/api/v1/ping",
							"host": [
								"{{url}}"
							],
							"path": [
								"api",
								"v1",
								"ping"
							]
						}
					},
					"response": []
				},
				{
					"name": "1 - get auth token",
					"event": [
						{
							"listen": "prerequest",
							"script": {
								"exec": [
									""
								],
								"type": "text/javascript"
							}
						},
						{
							"listen": "test",
							"script": {
								"exec": [
									"",
									"let jsonData = pm.response.json();",
									"pm.collectionVariables.set(\"access_token\", jsonData[\"access_token\"]);",
									"",
									"console.info('certificate issuer: ' + jsonData[\"certificate\"][\"issuer\"]);",
									"console.info('certificate subject: ' + jsonData[\"certificate\"][\"subject\"]);",
									"console.info('certificate subjectMap > SURNAME: ' + jsonData[\"certificate\"][\"subjectMap\"][\"SURNAME\"]);",
									"console.info('certificate subjectMap > SERIALNUMBER: ' + jsonData[\"certificate\"][\"subjectMap\"][\"SERIALNUMBER\"]);",
									"console.info('certificate subjectMap > CN: ' + jsonData[\"certificate\"][\"subjectMap\"][\"CN\"]);",
									"console.info('certificate subjectMap > GIVENNAME: ' + jsonData[\"certificate\"][\"subjectMap\"][\"GIVENNAME\"]);",
									""
								],
								"type": "text/javascript"
							}
						}
					],
					"request": {
						"method": "POST",
						"header": [],
						"body": {
							"mode": "formdata",
							"formdata": [
								{
									"key": "client_id",
									"value": "{{client_id}}",
									"type": "text"
								},
								{
									"key": "client_secret",
									"value": "{{client_secret}}",
									"type": "text"
								},
								{
									"key": "redirect_uri",
									"value": "{{redirect_uri}}",
									"type": "text"
								},
								{
									"key": "grant_type",
									"value": "authorization_code",
									"type": "text"
								},
								{
									"key": "code",
									"value": "{{code}}",
									"type": "text"
								}
							]
						},
						"url": {
							"raw": "{{url}}/oauth2/v1/token",
							"host": [
								"{{url}}"
							],
							"path": [
								"oauth2",
								"v1",
								"token"
							]
						},
						"description": "## Seguridad OAuth 2.0 Access Token\n\nEl API está securizada con OAuth 2.0, y con este método podrás obtener el access token necesario para consumir los métodos de firma disponibles en el API.\n\nPara ello vas a necesitar:\n\n* clientId\n* clientSecret\n\nAmbos datos son gestionados desde el dashboard de Fortress, en la configuración de Sistemas Clientes.\n\n* redirect_uri\n\nEl sistema comprobará que la URL a la que vamos a redirigir al usuario final está previamente autorizada. Esta autorización de igual forma se gestiona desde el dashboard de Fortress, en la configuración del sistema cliente.\n\nPor ejemplo:\n\n```\nhttps://mysystem.com/responseSignature\n```\ntambién se permiten patrones como el siguiente:\n\n```\n*.mysystem.com\nhttps://mysystem.com/*\n```\no bien permitir cualquier URL de retorno (recomendado solo para entornos de pruebas):\n```\n*\n```\n\n* grant_type\n\nDefine el ámbito de uso del token. Para el caso de uso de firmas con certificados de usuario el grant_type debe ser **client_credentials**.\n\n### Uso del método\n\nPOST {url}/oauth2/v1/token\n\nBody contentType/form-data\n\npasando los siguientes atributos:\n\n```\nclient_id=\"string\"\nclient_secret=\"string\"\nredirect_uri=\"string\"\ngrant_type=\"string\"\n```\n\n### Response\n\nRepuestas 200 OK con el siguiente contentType/JSON en el body:\n\n```json\n{\n    \"access_token\": \"string\",\n    \"token_type\": \"Bearer\",\n    \"expires_in\": 0\n}\n```\n\nPara el uso de los siguientes métodos del API necesitaremos el ```access_token```obtenido en la response.\n\nEn esta colección postman de ejemplo, lo guardamos automáticamente en la variable de la colección ```access_token```."
					},
					"response": [
						{
							"name": "200 OK",
							"originalRequest": {
								"method": "POST",
								"header": [],
								"body": {
									"mode": "formdata",
									"formdata": [
										{
											"key": "client_id",
											"value": "{{client_id}}",
											"type": "text"
										},
										{
											"key": "client_secret",
											"value": "{{client_secret}}",
											"type": "text"
										},
										{
											"key": "redirect_uri",
											"value": "{{redirect_uri}}",
											"type": "text"
										},
										{
											"key": "grant_type",
											"value": "authorization_code",
											"type": "text"
										},
										{
											"key": "code",
											"value": "{{code}}",
											"type": "text"
										}
									]
								},
								"url": {
									"raw": "{{url}}/oauth2/v1/token",
									"host": [
										"{{url}}"
									],
									"path": [
										"oauth2",
										"v1",
										"token"
									]
								}
							},
							"status": "OK",
							"code": 200,
							"_postman_previewlanguage": "json",
							"header": [
								{
									"key": "Date",
									"value": "Wed, 21 Jun 2023 13:19:59 GMT"
								},
								{
									"key": "Server",
									"value": "Apache"
								},
								{
									"key": "Strict-Transport-Security",
									"value": "max-age=63072000; includeSubDomains; preload"
								},
								{
									"key": "X-Content-Type-Options",
									"value": "nosniff"
								},
								{
									"key": "Referrer-Policy",
									"value": "same-origin"
								},
								{
									"key": "Permissions-Policy",
									"value": "geolocation=(),midi=(),sync-xhr=(),microphone=(),camera=*,magnetometer=(),gyroscope=(),fullscreen=(self),payment=()"
								},
								{
									"key": "Content-Type",
									"value": "application/json;charset=UTF-8"
								},
								{
									"key": "Vary",
									"value": "Accept-Encoding"
								},
								{
									"key": "X-Robots-Tag",
									"value": "noindex, noarchive, nosnippet"
								},
								{
									"key": "Content-Encoding",
									"value": "gzip"
								},
								{
									"key": "Via",
									"value": "1.1 sandbox.viafirma.com"
								},
								{
									"key": "X-Frame-Options",
									"value": "ALLOW-FROM https://sandbox.viafirma.com/"
								},
								{
									"key": "Keep-Alive",
									"value": "timeout=5, max=100"
								},
								{
									"key": "Connection",
									"value": "Keep-Alive"
								},
								{
									"key": "Transfer-Encoding",
									"value": "chunked"
								}
							],
							"cookie": [],
							"body": "{\n    \"access_token\": \"180f455b632a4ecda5241767c3d79bc0\",\n    \"token_type\": \"Bearer\",\n    \"expires_in\": 35975,\n    \"user_code\": \"xxxxx\",\n    \"certificate\": {\n        \"code\": \"xxxxxxxxx\",\n        \"dateIssued\": 1641899214000,\n        \"dateExpired\": 1768129614000,\n        \"serialNumber\": \"xxxxxxxx\",\n        \"issuer\": \"CN=AC FNMT Usuarios, OU=Ceres, O=FNMT-RCM, C=ES\",\n        \"subject\": \"CN=xxxxxx - xxxxx, SURNAME=xxxxx, GIVENNAME=xxxxxx, SERIALNUMBER=IDCES-xxxxxx, C=ES\",\n        \"issuerMap\": {\n            \"C\": \"ES\",\n            \"OU\": \"Ceres\",\n            \"CN\": \"AC FNMT Usuarios\",\n            \"O\": \"FNMT-RCM\"\n        },\n        \"subjectMap\": {\n            \"SURNAME\": \"xxxxxx\",\n            \"C\": \"ES\",\n            \"SERIALNUMBER\": \"IDCES-xxxxx\",\n            \"CN\": \"xxxxxx - xxxxx\",\n            \"GIVENNAME\": \"xxxxx\"\n        },\n        \"delegated\": false,\n        \"level\": \"MEDIUM\",\n        \"status\": \"ACTIVE\",\n        \"certificatePassword\": false,\n        \"passwordErrorCount\": 0,\n        \"policies\": [],\n        \"user\": {\n            \"code\": \"xxxxx\",\n            \"name\": \"xxxxx\",\n            \"email\": \"xxxxx\",\n            \"mobile\": \"xxxxx\",\n            \"userStatus\": \"ACTIVE\",\n            \"multifactorAuth\": false,\n            \"authCache\": false,\n            \"dateActivated\": 1487160409760,\n            \"language\": \"en\",\n            \"role\": {\n                \"id\": \"1\",\n                \"name\": \"ROLE_ADMIN\",\n                \"description\": \"Administrador\"\n            },\n            \"allowDelegations\": false,\n            \"timezone\": \"Europe/Madrid\",\n            \"notifyUseLimits\": false,\n            \"raOperator\": false\n        },\n        \"email\": \"xxxxx\",\n        \"notActivate\": false,\n        \"smsNotification\": false\n    }\n}"
						},
						{
							"name": "400 - Invalid grant - code was already redeemed",
							"originalRequest": {
								"method": "POST",
								"header": [],
								"body": {
									"mode": "formdata",
									"formdata": [
										{
											"key": "client_id",
											"value": "{{client_id}}",
											"type": "text"
										},
										{
											"key": "client_secret",
											"value": "{{client_secret}}",
											"type": "text"
										},
										{
											"key": "redirect_uri",
											"value": "{{redirect_uri}}",
											"type": "text"
										},
										{
											"key": "grant_type",
											"value": "authorization_code",
											"type": "text"
										},
										{
											"key": "code",
											"value": "{{code}}",
											"type": "text"
										}
									]
								},
								"url": {
									"raw": "{{url}}/oauth2/v1/token",
									"host": [
										"{{url}}"
									],
									"path": [
										"oauth2",
										"v1",
										"token"
									]
								}
							},
							"status": "Bad Request",
							"code": 400,
							"_postman_previewlanguage": "json",
							"header": [
								{
									"key": "Date",
									"value": "Wed, 21 Jun 2023 13:40:26 GMT"
								},
								{
									"key": "Server",
									"value": "Apache"
								},
								{
									"key": "Strict-Transport-Security",
									"value": "max-age=63072000; includeSubDomains; preload"
								},
								{
									"key": "X-Content-Type-Options",
									"value": "nosniff"
								},
								{
									"key": "Referrer-Policy",
									"value": "same-origin"
								},
								{
									"key": "Permissions-Policy",
									"value": "geolocation=(),midi=(),sync-xhr=(),microphone=(),camera=*,magnetometer=(),gyroscope=(),fullscreen=(self),payment=()"
								},
								{
									"key": "Content-Type",
									"value": "application/json;charset=UTF-8"
								},
								{
									"key": "Content-Length",
									"value": "74"
								},
								{
									"key": "X-Robots-Tag",
									"value": "noindex, noarchive, nosnippet"
								},
								{
									"key": "Via",
									"value": "1.1 sandbox.viafirma.com"
								},
								{
									"key": "X-Frame-Options",
									"value": "ALLOW-FROM https://sandbox.viafirma.com/"
								},
								{
									"key": "Connection",
									"value": "close"
								}
							],
							"cookie": [],
							"body": "{\n    \"error\": \"invalid_grant\",\n    \"error_description\": \"Code was already redeemed.\"\n}"
						},
						{
							"name": "400 - Invalid grant - bad request or code not found",
							"originalRequest": {
								"method": "POST",
								"header": [],
								"body": {
									"mode": "formdata",
									"formdata": [
										{
											"key": "client_id",
											"value": "{{client_id}}",
											"type": "text"
										},
										{
											"key": "client_secret",
											"value": "{{client_secret}}",
											"type": "text"
										},
										{
											"key": "redirect_uri",
											"value": "{{redirect_uri}}",
											"type": "text"
										},
										{
											"key": "grant_type",
											"value": "authorization_code",
											"type": "text"
										},
										{
											"key": "code",
											"value": "{{code}}",
											"type": "text"
										}
									]
								},
								"url": {
									"raw": "{{url}}/oauth2/v1/token",
									"host": [
										"{{url}}"
									],
									"path": [
										"oauth2",
										"v1",
										"token"
									]
								}
							},
							"status": "Bad Request",
							"code": 400,
							"_postman_previewlanguage": "json",
							"header": [
								{
									"key": "Date",
									"value": "Wed, 21 Jun 2023 13:41:10 GMT"
								},
								{
									"key": "Server",
									"value": "Apache"
								},
								{
									"key": "Strict-Transport-Security",
									"value": "max-age=63072000; includeSubDomains; preload"
								},
								{
									"key": "X-Content-Type-Options",
									"value": "nosniff"
								},
								{
									"key": "Referrer-Policy",
									"value": "same-origin"
								},
								{
									"key": "Permissions-Policy",
									"value": "geolocation=(),midi=(),sync-xhr=(),microphone=(),camera=*,magnetometer=(),gyroscope=(),fullscreen=(self),payment=()"
								},
								{
									"key": "Content-Type",
									"value": "application/json;charset=UTF-8"
								},
								{
									"key": "Content-Length",
									"value": "60"
								},
								{
									"key": "X-Robots-Tag",
									"value": "noindex, noarchive, nosnippet"
								},
								{
									"key": "Via",
									"value": "1.1 sandbox.viafirma.com"
								},
								{
									"key": "X-Frame-Options",
									"value": "ALLOW-FROM https://sandbox.viafirma.com/"
								},
								{
									"key": "Connection",
									"value": "close"
								}
							],
							"cookie": [],
							"body": "{\n    \"error\": \"invalid_grant\",\n    \"error_description\": \"Bad Request.\"\n}"
						}
					]
				}
			],
			"description": "## Firma de PDF con certificados de usuario centralizados\n\nEn esta carpeta se han incluido los casos de uso para cubrir la funcionalidad mínima requerida para la siguientes necesidades.\n\n* el usuario accede a su puesto (PC, portátil, móvil).\n* el sistema con el que el usuario interactuará se encarga, entre otras funcionalidades, de (1) generar el PDF que debe ser firmado, y (2) consumir las APIs del sistema de firma centralizado de Viafirma.\n* el usuario debe autorizar explícitamente el uso de su certificado superando el factor o factores de protección definidos por el administrador del sistema de firma centralizado.\n\n### Prerequisitos\n\n* el usuario debe estar previamente registrado en el sistema de firma centralizado.\n* el usuario debe tener un certificado digital activo.\n* el certificado debe estar activo.\n\n### Ejecución de casos de uso\n\nLa ejecución de los casos de uso no puede automatizarse en su totalidad, debiendo realizar una tarea manual en uno de los pasos, correspondiente al proceso atendido por el propietario del certificado para autorizar su uso.\n\nOrden de ejecución:\n\n* ejecutar casos 1 y 2\n* copiar salida de consola de ejecución del caso 2, seguir instrucciones en un navegador; requiere usuario registrado en Viafirma.\n* tras finalizar la tarea manual previa, ejecutar casos 4 y 5."
		}
	],
	"event": [
		{
			"listen": "prerequest",
			"script": {
				"type": "text/javascript",
				"exec": [
					""
				]
			}
		},
		{
			"listen": "test",
			"script": {
				"type": "text/javascript",
				"exec": [
					""
				]
			}
		}
	],
	"variable": [
		{
			"key": "access_token",
			"value": null
		},
		{
			"key": "code",
			"value": "",
			"type": "string"
		},
		{
			"key": "redirect_uri",
			"value": "http://localhost:8080/fortress_response"
		},
		{
			"key": "user_code",
			"value": ""
		}
	]
}