@Alisa94

Почему не удаётся авторизоваться?

Добрый день. Я пытаюсь разделить на разные файлы приложение для просмотра(viewer) от autodesk forge, но мне не удаётся это сделать, каждый раз возникает какая-то ошибка, а сейчас вообщем не понимаю, в чём проблема.

По этой ссылке вы можете посмотреть все файлы, которые есть у меня в проекте(кроме node_modules).

А вот и код ошибки

Server listening on port 3000
TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["Authorization"]
    at ClientRequest.setHeader (_http_outgoing.js:485:3)
    at new ClientRequest (_http_client.js:206:14)
    at Object.request (https.js:300:10)
    at RedirectableRequest._performRequest (/home/suro/My Works/FORGE/01.02Viewer/node_modules/follow-redirects/index.js:186:24)
    at new RedirectableRequest (/home/suro/My Works/FORGE/01.02Viewer/node_modules/follow-redirects/index.js:69:8)
    at Object.wrappedProtocol.request (/home/suro/My Works/FORGE/01.02Viewer/node_modules/follow-redirects/index.js:363:14)
    at dispatchHttpRequest (/home/suro/My Works/FORGE/01.02Viewer/node_modules/axios/lib/adapters/http.js:141:25)
    at new Promise (<anonymous>)
    at httpAdapter (/home/suro/My Works/FORGE/01.02Viewer/node_modules/axios/lib/adapters/http.js:18:10)
    at dispatchRequest (/home/suro/My Works/FORGE/01.02Viewer/node_modules/axios/lib/core/dispatchRequest.js:59:10)


Любая помощь будет полезна, спасибо.
  • Вопрос задан
  • 830 просмотров
Решения вопроса 1
@Abcdefgk
Вообще, Axios - довольно забавный тип, в нем можно устанавливать "заголовки по умолчанию".
И как не странно, это работает и на сервере.
Вот такой, допустим, файл server.js
const path = require('path');
const express = require('express');           // For web server
const bodyParser = require('body-parser');    // Receive JSON format
const querystring = require('querystring');

// Set up Express web server
var app = express();
app.use(bodyParser.json());
// this line say of server, that we run server.js he open html file from public directory
app.use(express.static(path.join(__dirname, 'public'))); // it was static(__ + 'public or www')

// let's importing config.js file where are the configuration for dotenv/env and credentials_id/secret/url/PORT and scopes
const config = require('./config');

const PORT = config.credentials.PORT; // import from bim start.js
const scopes = 'data:read data:write data:create bucket:create bucket:read';

var indRouter = require('./routes/indRouter');
indRouter(app);

app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.statusCode).json(err);
});

// This is for web server to start listening to port 3000
app.listen(PORT, () => { 
  if (process.env.FORGE_CLIENT_ID == null || process.env.FORGE_CLIENT_SECRET == null) {
    console.log('*****************\nWARNING: Client ID & Client Secret not defined as environment variables.\n*****************');
  }
  console.log(`Server listening on port ${PORT}`);
});

В папке routes лежить вот такой файл indRouter.js
var oauth = require('./oauth');
var bucketCreate = require('./bucketCreate');
var Axios = require('axios');
var publ = require('./publ');
var detail = require('./detail');

module.exports = function(app) {
	
	app.get('/api/forge/oauth', function (req, res) {
		oauth()
			.then(function (response) {
				// Success
				var access_token = response.data.access_token;
				Axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
				//console.log(response);
				res.redirect('/api/forge/datamanagement/bucket/create');
      })
			.catch(function (error) {
				// Failed
				console.log(error);
				res.send('Failed to authenticate');
			});
	});
	
	app.get('/api/forge/datamanagement/bucket/create', function (req, res) {
		bucketCreate()
			.then(function (response) {
				// Success
				//console.log(response);
				res.redirect('/api/forge/datamanagement/bucket/detail');
      })
			.catch(function (error) {
				if (error.response && error.response.status == 409) {
						console.log('Bucket already exists, skip creation.');
						res.redirect('/api/forge/datamanagement/bucket/detail');
				}
				// Failed
				console.log(error);
				res.send('Failed to create a new bucket');
			});
	});
	
	app.get('/api/forge/oauth/public', function (req, res) {
    // Limit public token to Viewer read only
    publ()
			.then(function (response) {
				// Success
				//console.log(response);
				res.json({ access_token: response.data.access_token, expires_in: response.data.expires_in });
			})
			.catch(function (error) {
				// Failed
				console.log(error);
				res.status(500).json(error);
			});
	});
	
	app.get('/api/forge/datamanagement/bucket/detail', function (req, res) {
		detail()
			.then(function (response) {
				// Success
				console.log(response);
				res.redirect('/upload.html');
      })
      .catch(function (error) {
				// Failed
				console.log(error);
				res.send('Failed to verify the new bucket');
      });
	});
	
};

И рядом с ним лежат файлы
oauth.js
const Axios = require('axios');
const querystring = require('querystring');

const config = require('../config');

module.exports = function() {
  return Axios({
    method: 'POST',
    url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
    headers: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    data: querystring.stringify({
      client_id: config.credentials.client_id,
      client_secret: config.credentials.client_secret,
      grant_type: 'client_credentials',
      scope: config.scopes.internal
    })
  });
};

bucketCreate.js
const Axios = require('axios');
const config = require('../config');

// Prefix with your ID so the bucket key is unique across all buckets on all other accounts
const bucketKey = config.credentials.client_id.toLowerCase() + '_my_first_full_viewer_bucket';
const policyKey = 'transient'; // Expires in 24hr

  // Create an application shared bucket using access token from previous route
  // We will use this bucket for storing all files in this tutorial

module.exports = function() {
  return Axios({
    method: 'POST',
    url: 'https://developer.api.autodesk.com/oss/v2/buckets',
    headers: {
      'content-type': 'application/json',
      //Authorization: 'Bearer ' + access_token
    },
    data: JSON.stringify({
      'bucketKey': bucketKey,
      'policyKey': policyKey
    })
  });
};

publ.js
const Axios = require('axios');
const querystring = require('querystring');
const config = require('../config');

module.exports = function() {
	return Axios({
    method: 'POST',
    url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
    headers: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    data: querystring.stringify({
			client_id: config.credentials.client_id,
			client_secret: config.credentials.client_secret,
			grant_type: 'client_credentials',
			scope: 'viewables:read'
    })
  });
};

detail.js
var Axios = require('axios');
const config = require('../config');

// Prefix with your ID so the bucket key is unique across all buckets on all other accounts
const bucketKey = config.credentials.client_id.toLowerCase() + '_my_first_full_viewer_bucket';

module.exports = function() {
	return Axios({
		method: 'GET',
		url: 'https://developer.api.autodesk.com/oss/v2/buckets/' + encodeURIComponent(bucketKey) + '/details',
		//headers: {
				//Authorization: 'Bearer ' + access_token
		//}
  });
};

В первом обработчике (файл indRouter.js) установлен заголовок по умолчанию Authorization с токеном
и больше его нигде писать не надо - он уже во всех запросах от Axios есть.
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@de1m
Вас вот эта строчка не смущает?
TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["Authorization"]

Я так понимая, что сервер от клиента что-то не то в header'e для авторизации получает.
Надо смотреть, что там должно приходить и что приходит на самом деле.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
19 апр. 2024, в 05:01
999999 руб./за проект
19 апр. 2024, в 03:52
1000 руб./за проект
19 апр. 2024, в 03:01
1000 руб./за проект