我有一个 React 应用程序和一个 NodeJS 服务器。我设置了一个包含 JWT 的 httpOnly-cookie 以进行身份验证。这有效。问题是:我需要一些逻辑客户端来检查用户是否登录。当用户登录时,我可以将此“状态”存储在内存中(例如 useState),但是当浏览器重新加载时,此状态消失了(虽然 cookie 仍然存在)。
我尝试使用js-cookie但显然这不起作用,因为它是一个 httpOnly cookie。
在浏览器中打开 React 应用程序时,如何检查 - 无需向我的服务器执行(测试) axios 请求 - 用户是否已登录?
编辑:这个问题 的答案建议将令牌存储在 LocalStorage 中,但其他资源(如这个问题答案中的讨论)表示 cookie 是可行的方法。
需要明确的是,我不需要直接访问cookie 中的令牌,cookie 是随每个 axios 请求 ( {withCredentials: true}) 一起发送的,并且它按预期工作。但我只需要知道cookie是否已设置(因此用户已登录)。
我是 React Native 的初学者,我正在创建一个应用程序。我已经做了一些关于如何制作安全的反应本机应用程序的研究,但我没有找到太多信息。我自己提出了一个“解决方案”,但我想确保这是正确的方法。因此,如果可能的话,我需要一些反应本机/javascript/安全专家的帮助,以快速检查我的方法是否正确?
我在本文中包含了 3 个问题,但显然它们是相关的。我已经把它们加粗了。请随意回答一个或多个问题,我感谢每一个答案!
我正在用本机反应创建一个应用程序。为了让用户能够使用该应用程序,用户应该创建一个帐户并登录。我使用 JSON Web 令牌作为访问令牌来授权从应用程序向服务器发出的请求,并识别用户(我将用户 ID 存储在 JSON Web 令牌中)。
在我的服务器上,我首先检查访问令牌是否有效。如果是,我会从访问令牌中获取用户 ID,并使用该用户 ID 来识别用户。
为了额外的安全性,我还使用刷新令牌,因为访问令牌的有效期只有 10 分钟。当用户发送带有过期访问令牌的请求时,服务器会返回 401 未授权状态。
为了使我的代码更“易于管理”,我在 React Native 中创建了一个包装函数。我用这个包装函数包装每个“请求函数”(向服务器发出 GET/POST/PUT/DELETE 请求的每个函数)。该包装函数检查请求的响应。如果响应状态为200,则将响应返回给代码。如果响应状态为 401,则将刷新令牌发送到特定端点以获取新的访问令牌。当访问令牌到达应用程序时,将使用新的访问令牌再次发出先前的请求。包装函数还将新的访问令牌存储在(临时)redux(钥匙串或共享首选项)中。1. 包装函数是个好主意吗?对我来说,它更易于管理,因为现在我正在重用代码。
每次用户打开应用程序时,都会请求新的访问令牌,当用户关闭应用程序时,当前的访问令牌将被删除,即使它尚未过期。这样,我想确保每个应用程序“会话”都以新的访问令牌开始。2.这样可以吗?或者,当我仍然拥有(可能)有效的访问令牌时,我应该阻止对服务器不必要的请求吗?
在我的 React Native 应用程序中,此包装函数位于上下文组件中。这个“身份验证”上下文包装了 App.js 中的其他组件,如下所示:
<AuthenticationProvider>
<AppNavigator />
</AuthenticationProvider>
Run Code Online (Sandbox Code Playgroud)
这样,我的包装函数就可以被所有其他组件访问。我的身份验证上下文如下所示:
const AuthenticationContext = createContext({
accessToken: null,
wrapperFunction: () => {}
})
const AuthenticationProvider = (props) => {
let accessToken = null
const refreshToken = useSelector(state => state.auth.refreshToken)
const wrapperFunction = () => { …Run Code Online (Sandbox Code Playgroud) 我已按照此处的说明安装 android studio 和 android sdk。
我已将以下几行添加到 ~/.bash_profile,并运行 source ~/.bash_profile。
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
Run Code Online (Sandbox Code Playgroud)
路径是正确的,我已经在 Android Studio > Preferences > System Settings > Android SDK 中检查过了。
问题是什么?当我运行 source ~/.bash_profile,然后回显 $ANDROID_HOME 时,我会得到一些输出。但是,如果我关闭终端并重新启动它,然后运行 echo $ANDROID_HOME,则没有任何输出。
如果在这里和其他网站上发现了类似的问题,但似乎没有任何效果。编辑导出行,在终端中直接执行“export ...”而不是 bash_profile, ... 。这一切都行不通。
有人有什么建议可以帮助我吗?
我有一个科学数据库,目前有 4,300,000 条记录。它是一个科学数据库,由 API 提供支持。到 2020 年 6 月,我可能会有大约 100,000,000 条记录。
这是表“输出”的布局:
ID | sensor_ID | speed | velocity | direction
-----------------------------------------------------
1 | 1 | 10 | 1 | up
2 | 2 | 12 | 2 | up
3 | 2 | 11.5 | 1.5 | down
4 | 1 | 9.5 | 0.8 | down
5 | 3 | 11 | 0.75 | up
...
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这是虚拟数据。但是输出是一个有 5 列的表:ID、sensor_ID、速度、速度和方向。
我想要实现的是一个体面的分页和过滤方法。我想创建一个网站(在 nodejs 中),其中将显示 +4,000,000 条记录(目前),每页 10,000 条记录。我还希望能够过滤 …
我正在尝试使用 redux 持久保存在我的 React Native 应用程序的服务中来访问 Redux 存储。
我需要一个特定的令牌来设置 websocket 连接。
到目前为止我的代码:
./redux/Store.js:
const persistedReducer = combineReducers({
tokens: persistReducer(secureConfig, TokensReducer),
});
const store = createStore(persistedReducer);
const configureStore = () => {
const persistor = persistStore(store);
return { persistor, store };
};
export default configureStore;
Run Code Online (Sandbox Code Playgroud)
./redux/reducers/TokenReducer
const initialState = {
accessToken: null,
refreshToken: null
}
const TokensReducer = (state = initialState, action) {
// reducer
};
export default TokensReducer;
Run Code Online (Sandbox Code Playgroud)
./service/websocket.js
import configureStore from '../redux/Store';
const { store } = configureStore();
console.log(store.getState().tokens); …Run Code Online (Sandbox Code Playgroud) 我在nodejs中有以下postgresql连接文件:
// postgresql.js
"use strict";
const { Pool } = require('pg');
module.exports = new Promise((resolve, reject) => {
const pool = new Pool({
host: '127.0.0.1',
port: 5432,
user: 'postgres',
password: 'postgres',
database: 'postgres',
connectionTimeoutMillis: 0,
idleTimeoutMillis: 0,
min: 10,
max: 20,
});
resolve({ pool });
});
Run Code Online (Sandbox Code Playgroud)
我使用 Promise 是因为稍后我将开始使用Google Cloud Secret Manager。秘密是异步获取的,因此服务器启动时无法建立数据库连接。
在我的控制器文件中,我像这样使用它:
// apicontroller.js
"use strict";
const postgresql = require('./postgresql');
app.get('/api/test', async (req, res, next) => {
// resolve the postgresql promise
const { pool } = …Run Code Online (Sandbox Code Playgroud) 我想当我将代码推送到github时,通过github操作自动部署github项目。我的 yaml 文件如下所示:
name: push-and-deploy-to-server
on:
push:
branches: [ main ]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: appleboy/scp-action@master
with:
host: ${{ secrets.SSH_HOST }}
port: 22
username: ${{ secrets.SSH_USERNAME }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
source: "."
target: "."
- uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SSH_HOST }}
port: 22
username: ${{ secrets.SSH_USERNAME }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
npm install
pm2 restart index.js
Run Code Online (Sandbox Code Playgroud)
我有一台带有 SSH 密钥对的服务器。公钥已添加到服务器的authorized_keys中,我可以通过终端通过SSH连接到服务器。
当我将代码推送到 github 存储库时,该操作就会运行。我收到以下错误:
Drone-scp 错误:ssh:握手失败:ssh:无法进行身份验证,已尝试方法 [无公钥],没有保留支持的方法
奇怪的是:发生此错误后,我无法再通过 SSH 连接到我的服务器,即使通过我的控制台我也收到“权限被拒绝(公钥)”的消息。所以在运行 github 操作之前,一切正常,之后就失败了。 …
通过 fetch,我从服务器获取了 JWT。收到这个 JWT 是因为当我执行 console.log(resData.token) 时,令牌会显示在控制台中。但我无法将令牌保存在异步存储中。回复是这样的:
{“_40”:0,“_55”:空,“_65”:0,“_72”:空}
我认为当 aynstorage.setItem 运行时,获取尚未完成,但我如何等待它先完成?
import React, { useState } from 'react';
import { Text, TextInput, Button, SafeAreaView } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
const SignInScreen = props => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const SignInHandler = async () => {
const req = await fetch('http://localhost:8080/auth/signin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({username: username, password: password})
});
const res = await req; …Run Code Online (Sandbox Code Playgroud) 我正在创建一个可触摸的按钮,以对原生动画做出反应。当按下按钮时,它应该缩小一点。当压力释放后,它应该会恢复正常。
这是我的代码:
export const TouchableButton = (props) => {
const { onPress, text, icon } = props
const animatedValue = new Animated.Value(0)
const animatedValueInterpolateScale = animatedValue.interpolate({
inputRange: [0, 1],
outputRange: [1, 0.95]
})
const pressInHandler = () => {
Animated.timing(
animatedValue,
{
toValue: 1,
duration: 150
}
).start()
}
const pressOutHandler = () => {
Animated.timing(
animatedValue,
{
toValue: 0,
duration: 150
}
).start()
}
return (
<TouchableWithoutFeedback onPress={onPress} onPressIn={pressInHandler} onPressOut={pressOutHandler}>
<View style={{ alignItems: 'center' }}>
<Animated.View style={{ width: '100%', …Run Code Online (Sandbox Code Playgroud) 我有以下代码(完整示例):
import React, { useState, useEffect } from 'react';
import { SafeAreaView, View, TextInput, Button, StyleSheet } from 'react-native';
const App = () => {
const [textblocks, setTextblocks] = useState([]);
const CreateTextBlockHandler = () => {
let array = [...textblocks];
array.push({text: ''});
setTextblocks(array);
};
const SaveTextHandler = (index, text) => {
let array = [...textblocks];
array[index].text = text;
setTextblocks(array);
};
const RenderTextInputs = () => {
return textblocks.map((item, index) => {
return (
<View key={index}>
<TextInput style={styles.textinput} placeholder="text" value={textblocks[index].text} onChangeText={value …Run Code Online (Sandbox Code Playgroud) 我有一个带有 2 个屏幕的堆栈导航器,“消息”和“消息”。在“消息”屏幕上,我想了解与我聊天的所有人以及对话中的最后一条消息。我将所有对话存储在 redux 中,而不是在服务器上。我的 redux 状态如下所示:
const state = {
user = [
{
userId: 1,
username: John,
messages: [...array of messages send to John or from John...]
},
{
userId: 2,
username: Jane,
messages: [...array of messages send to Jane or from Jane...]
}
...
]
}
Run Code Online (Sandbox Code Playgroud)
在“消息”屏幕上,我有一个 FlatList 组件,它在 redux 状态下遍历用户数组:
const users = useSelector(state => state.messages.users)
const renderUserItem = user => {
return (
<View>
<Text>{user.username}</Text>
<Text>{user.messages[user.messages.length-1].message</Text>
</View>
)
}
<FlatList
data={messages}
renderItem={({item, index}) => renderUserItem(item)} …Run Code Online (Sandbox Code Playgroud) 我有以下代码(完整示例):
import React, { useState, useEffect } from 'react';
import { SafeAreaView, View, Button, StyleSheet, Animated } from 'react-native';
import { PanGestureHandler, State } from 'react-native-gesture-handler';
const App = () => {
const [blocks, setBlocks] = useState([]);
const CreateBlockHandler = () => {
let array = blocks;
array.push({
x: new Animated.Value(0),
y: new Animated.Value(0)
});
setBlocks(array);
RenderBlocks();
};
const MoveBlockHandler = (index, event) => {
Animated.spring(blocks[index].x, { toValue: event.nativeEvent.x }).start();
Animated.spring(blocks[index].y, { toValue: event.nativeEvent.y }).start();
};
const RenderBlocks = () …Run Code Online (Sandbox Code Playgroud) react-native ×7
node.js ×3
reactjs ×3
postgresql ×2
android ×1
async-await ×1
cookies ×1
json ×1
macos ×1
redux ×1
sql ×1
ssh ×1