nextjs和远程api中的受保护页面
我买了一个nextjs主题(),需要实现身份验证逻辑。nextjs和远程api中的受保护页面,api,authentication,jwt,authorization,next.js,Api,Authentication,Jwt,Authorization,Next.js,我买了一个nextjs主题(),需要实现身份验证逻辑。 API已经准备好了。所以,只需将我的jwt令牌存储在cookie中,如果未设置令牌,则将页面重定向到登录页面。 我无法理解控制我的令牌的逻辑 作为api服务助手,我编写了以下代码: import cookie from 'cookie'; const { API_URL } = process.env; // `API_URL: ${API_URL}`; const API_TOKEN = 'API_TOKEN'; export def
API已经准备好了。所以,只需将我的jwt令牌存储在cookie中,如果未设置令牌,则将页面重定向到登录页面。
我无法理解控制我的令牌的逻辑 作为api服务助手,我编写了以下代码:
import cookie from 'cookie';
const { API_URL } = process.env; // `API_URL: ${API_URL}`;
const API_TOKEN = 'API_TOKEN';
export default class ApiService {
static async fetch(url, options, token) {
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
if (token) {
headers['Authorization'] = 'Bearer ' + token;
}
try {
const response = await fetch(`${API_URL}/${url}`, {
headers,
...options
})
const json = await response.json();
if (json.success) {
return json.data;
} else {
throw new Error(json.message);
}
} catch (err) {
return err;
}
}
constructor(ctx) {
this.ctx = ctx;
this.token = null;
this.user = null;
const { req } = this.ctx;
var cookies = cookie.parse(req.headers.cookie || '');
if (API_TOKEN in cookies) this.token = cookies[API_TOKEN];
}
async login(uname, pword, instance = 'portal') {
const response = await ApiService.fetch('auth/login', {
method: 'POST',
body: JSON.stringify({ uname, pword, instance })
})
if (response.success) {
this.token = response.data.token;
const { res } = this.ctx;
res.setHeader('Set-Cookie', cookie.serialize(API_TOKEN, String(this.token), {
httpOnly: true,
maxAge: 60 * 60 * 24 // 1 week
}));
const user = await this.me();
return user;
} else {
throw new Error(response.message);
}
}
async me(force = false) {
if (force || this.user == null) {
const response = await this.get('auth/me');
if (response.success) {
this.user = response.data;
} else {
//throw new Error(response.message);
}
}
return this.user;
}
async request(method, url, body) {
if (this.token == null) return { success: false, message: 'TOKEN_NOT_FOUND' };
const options = { method };
if (body) {
options["body"] = JSON.stringify(body);
}
const response = await ApiService.fetch(url, options, this.token);
return response;
}
async get(url) {
const response = await this.request('GET', url);
return response;
}
async post(url, body) {
const response = await this.request('POST', url, body);
return response;
}
async put(url, body) {
const response = await this.request('PUT', url, body);
return response;
}
async delete(url) {
const response = await this.request('DELETE', url);
return response;
}
}
在_app.js文件中的getInitialProps中调用该类
let user = null;
const api = new ApiService(ctx);
console.log("API_TOKEN", api.token);
if (api.token == null) {
Router.push('/pages/login', '/login');
//ctx.res.writeHead(302, {
// Location: '/login'
//});
// ctx.res.end();
}
try {
user = await api.me();
} catch (error) {
console.log("API ERROR", error)
}
需要帮助了解如何实现外部api和创建受保护的页面吗