- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
不需要授权的查询成功,但是需要JWT授权的查询失败。
在浏览器控制台中,我收到以下错误消息:
[GraphQL 错误]:消息:函数 get_account_info 的权限被拒绝,位置:[object Object],路径:getAccountInfo
这是我在服务器控制台中得到的错误:
在 101.18 毫秒内作为访客出现 1 个错误::{ getAccountInfo { username interface native customNative tutorial email __typename } }
错误显示 as guest
的事实意味着角色设置不正确(否则它会显示为 as loggedin
)。我很确定这个错误不是由于 SQL 方面的原因,而是在我的 JS 代码中,但为了以防万一,我在下面提供了一些 SQL 代码。
我安装了 GraphQL Developer Tools 并看到这是请求中发送的内容:
请求
请注意,Cookie 具有authorization=[some token]。这是否意味着没有授权 header ,因为它出于某种原因位于 Cookie 下?如果是这样,如何正确设置 header ?或者还有其他我做错的地方吗?
我很确定 SQL 没问题,但这里只是为了以防万一。
CREATE FUNCTION private.generate_jwt_for_user(username text)
RETURNS json_web_token
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
n_moderator bigint;
BEGIN
SELECT count(*) INTO n_moderator
FROM private.moderator
WHERE account = username;
IF n_moderator = 0
THEN
RETURN ('loggedin', username)::json_web_token; -- x::Y means cast x to type Y
ELSE
RETURN ('moderator', username)::json_web_token;
END IF;
END;
$$;
CREATE FUNCTION public.get_account_info()
RETURNS private.account_info
LANGUAGE SQL
SECURITY DEFINER
STABLE
AS $$
SELECT *
FROM private.account_info
WHERE username = current_setting('jwt.claims.username')
$$;
// Meteor startup script. Runs reactRoutes, and puts the result in the 'content' div in index.html.
import { Meteor } from 'meteor/meteor'
import { render } from 'react-dom'
import Routes from './routes'
import React from 'react'
import ApolloClient from 'apollo-boost'
import { HttpLink } from 'apollo-link-http'
import { ApolloLink, from } from 'apollo-link'
import { ApolloProvider } from 'react-apollo'
// Connect to the database using Apollo
// Add middleware that adds a Json Web Token (JWT) to the request header
const httpLink = new HttpLink({ uri: '/graphql' });
const authMiddleware = new ApolloLink((operation, forward) => {
// add the authorization to the headers
const token = localStorage.getItem('token')
operation.setContext(({ headers = {} }) => ({
headers: {
...headers,
authorization: 'Bearer ' + token || null,
}
}));
return forward(operation);
})
const client = new ApolloClient({
link: from([
authMiddleware,
httpLink
]),
});
// <ApolloProvider> allows React to connect to Apollo
// <Routes> allows client-side routing
// The rendered page inserted into the HTML under 'content'
Meteor.startup(() => {
render(
<ApolloProvider client={client}>
<Routes/>
</ApolloProvider>,
document.getElementById('content'))
})
对于偶尔带有 TODO 注释的长代码表示歉意,这项工作仍在进行中。
import React from 'react'
import jwtDecode from 'jwt-decode'
import { withApollo, graphql } from 'react-apollo'
import gql from 'graphql-tag'
import Nav from './auxiliary/nav'
import Translate from 'react-translate-component'
class UserAppBody extends React.Component {
constructor(props) {
super(props)
this.state = {
activeLanguageId: null
}
}
setLanguage(langId) {
this.setState({
activeLanguageId: langId
})
}
render() {
let native = null
let username = false
// TODO: remove all userId references in app
let tutorial = false
if (this.props.accountInfo) {
console.log("jwt: " + localStorage['token'])
if (this.props.accountInfo.loading) { return <Translate component="div" content="loading.loading" /> }
console.log(this.props.accountInfo)
username = this.props.accountInfo.getAccountInfo.username
tutorial = this.props.accountInfo.getAccountInfo.tutorial
native = this.props.accountInfo.getAccountInfo.native
}
return (
<div id="app-container">
<Nav callbackLogOut={this.props.logOut} username={username} />
{/* Insert the children according to routes.jsx (this.props.children), along with the childrens' props.
username should come from query due to being wrapped by graphql for wrapped case; otherwise username is bool: false. */}
{React.cloneElement(
this.props.children,
{
username: username,
hasSeenTutorial: tutorial,
native: native,
activeLanguageId: this.state.activeLanguageId,
callbackLanguage: this.setLanguage.bind(this),
callbackUser: this.props.setUser,
callbackLogOut: this.props.logOut
}
)}
</div>
)
}
}
// UserAppBody will be wrapped in AppBody if user is logged in, this setup comes before the wrapping
// Calling graphql on this turns it into a function which returns a React element (needed below)
const accountInfoQuery = gql`query{
getAccountInfo {
username
interface
native
customNative
tutorial
email
}
}`
const accountInfoQueryConfig = {
name: 'accountInfo'
}
const SignedInAppBody = graphql(accountInfoQuery, accountInfoQueryConfig)(UserAppBody)
class AppBody extends React.Component {
constructor(props) {
super(props)
const raw_jwt = localStorage.getItem('token')
this.state = {
isLoggedIn: !!raw_jwt // true if there is a jwt in local storage, false otherwise
}
}
setUser(raw_jwt) {
const jwt = jwtDecode(raw_jwt)
// Check if the token has expired
// Note that getTime() is in milliseconds, but jwt.exp is in seconds
const timestamp = (new Date).getTime()
if (!!jwt && timestamp < jwt.exp * 1000) {
// If the token is still valid:
// Store the token in memory, to be added to request headers
localStorage.setItem('token', raw_jwt)
// Set the state, to change the app
this.setState({
isLoggedIn: true
})
// Automatically refresh the token
this.refreshTimer = setInterval(this.refresh, 1000*60*20) // Refresh every 20 minutes
console.log('timer set up')
} else {
// If the token is no longer valid, log out to clear information
this.logOut()
}
}
logOut() {
// Clear everything from setUser (state, memory, refreshing)
localStorage.removeItem('refreshToken')
localStorage.removeItem('token')
clearInterval(this.refreshTimer)
console.log('logging out')
// second argument is a callback that setState will call when it is finished
this.setState( { isLoggedIn: false }, this.props.client.resetStore() )
}
refresh() {
// Get a new token using the refresh code
this.props.refresh({variables: {input: {refreshToken: localStorage.getItem('refreshToken')}}})
.then((response) => {
// Store the new token
const raw_jwt = response.data.refresh.jsonWebToken
localStorage.setItem('token', raw_jwt)
}).catch((error) => {
// If we can't connect to the server, try again
if (error.networkError) {
console.log('network error?') //TODO
//this.refresh()
} else { //TODO
// If we connected to the server and refreshing failed, log out
console.log('error, logging out')
console.log(error)
this.logOut()
}
})
}
componentWillMount() {
const raw_jwt = localStorage.getItem('token')
if (!!raw_jwt) {
console.log('found json web token, running setUser as App compenent mounts')
this.setUser(raw_jwt)
this.refresh()
}
}
render() {
let AppBodyClass
if (this.state.isLoggedIn) {
AppBodyClass = SignedInAppBody
} else {
AppBodyClass = UserAppBody
}
return <AppBodyClass children={this.props.children} setUser={this.setUser.bind(this)} logOut={this.logOut.bind(this)} />
}
}
const refresh = gql`mutation($input:RefreshInput!) {
refresh(input:$input) {
jsonWebToken
}
}`
const refreshConfig = {
name: 'refresh'
}
export default withApollo(graphql(refresh, refreshConfig)(AppBody))
最佳答案
Note that Cookie has authorization=[some token]. Does this mean that there is no authorization header because it is living under Cookie for some reason? If so, how do I set the header correctly? Or is there anything else that I'm doing wrong?
这很奇怪,但是您的客户端代码似乎是正确的;尝试使用不同的开发工具来查看实际发送的内容。 “Bearer”这个词也被去掉了,很奇怪。
The fact that the error says as guest means that the role hasn't been set correctly (otherwise it would say as loggedin). I'm fairly sure this error isn't due to something on the SQL side, but rather in my JS code, but I've provided some SQL code below just in case.
将JWT token放入jwt.io工具,可以看到token的主体是:
{
"cid": 8,
"sub": "s[AN EMAIL ADDRESS]m",
"iss": "http://mws-mla.com",
"permissions": 1,
"iat": 1522070876,
"exp": 1522675676
}
这缺少“角色”声明,因此 PostGraphile 不会尝试更改角色。然而,这似乎与您在 PostgreSQL 中生成的 JWT 不一致,所以我怀疑这个 cookie 具有误导性。我相信您根本没有发送授权 header 。
尝试调试您的身份验证中间件:
const authMiddleware = new ApolloLink((operation, forward) => {
// add the authorization to the headers
const token = localStorage.getItem('token')
operation.setContext(context => {
const ctx = {
...context,
headers: {
...context.headers,
authorization: 'Bearer ' + token || null,
}
};
console.log(ctx);
return ctx;
});
return forward(operation);
})
(注意:您之前只将 header 保留在上下文中,在上面的代码中,我现在也传递了其他属性。)
关于postgresql - "[GraphQL error]: Message: permission denied for function"在 header 中使用 JWT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55396549/
reqwest v0.9 将 serde v1.0 作为依赖项,因此实现 converting serde_json errors into reqwest error . 在我的代码中,我使用 se
我有这个代码: let file = FileStorage { // ... }; file.write("Test", bytes.as_ref()) .map_err(|e| Mu
我只是尝试用angular-cli创建一个新项目,然后运行服务器,但是它停止并显示一条有趣的消息:Error: No errors。 我以这种方式更新了(希望有帮助):npm uninstall -g
我从我的 javascript 发送交易 Metamask 打开传输对话框 我确定 i get an error message in metamask (inpage.js:1 MetaMask -
这个问题在这里已经有了答案: How do you define custom `Error` types in Rust? (3 个答案) How to get a reference to a
我想知道两者之间有什么大的区别 if let error = error{} vs if error != nil?或者只是人们的不同之处,比如他们如何用代码表达自己? 例如,如果我使用这段代码: u
当我尝试发送超过 50KB 的图像时,我在 Blazor 服务器应用程序上收到以下错误消息 Error: Connection disconnected with error 'Error: Serv
我有一个error-page指令,它将所有异常重定向到错误显示页面 我的web.xml: [...] java.lang.Exception /vi
我有这样的对象: address: { "phone" : 888, "value" : 12 } 在 WHERE 中我需要通过 address.value 查找对象,但是在 SQL 中有函数
每次我尝试编译我的代码时,我都会遇到大量错误。这不是我的代码的问题,因为它在另一台计算机上工作得很好。我尝试重新安装和修复,但这没有帮助。这是整个错误消息: 1>------ Build starte
在我的代码的类部分,如果我写一个错误,则在不应该的情况下,将有几行报告为错误。我将'| error'放在可以从错误中恢复的良好/安全位置,但是我认为它没有使用它。也许它试图在某个地方恢复中间表情? 有
我遇到了 csv 输入文件整体读取故障的问题,我可以通过在 read_csv 函数中添加 "error_bad_lines=False" 来删除这些问题来解决这个问题。 但是我需要报告这些造成问题的文
在 Spring 中,验证后我们在 controller 中得到一个 BindingResult 对象。 很简单,如果我收到验证错误,我想重新显示我的表单,并在每个受影响的字段上方显示错误消息。 因此
我不知道出了什么问题,因为我用 Java 编程了大约一年,从来没有遇到过这个错误。在一分钟前在 Eclipse 中编译和运行工作,现在我得到这个错误: #A fatal error has been
SELECT to_char(messages. TIME, 'YYYY/MM/DD') AS FullDate, to_char(messages. TIME, 'MM/DD
我收到这些错误: AnonymousPath\Anonymized.vb : error BC30037: Character is not valid. AnonymousPath\Anonymiz
我刚刚安装了 gridengine 并在执行 qstat 时出现错误: error: commlib error: got select error (Connection refused) erro
嗨,我正在学习 PHP,我从 CRUD 系统开始,我在 Windows 上安装了 WAMP 服务器,当我运行它时,我收到以下错误消息。 SCREAM: Error suppression ignore
我刚刚开始一个新项目,我正在学习核心数据教程,可以找到:https://www.youtube.com/watch?v=zZJpsszfTHM 我似乎无法弄清楚为什么会抛出此错误。我有一个名为“Exp
当我使用 Jenkins 运行新构建时,出现以下错误: "FilePathY\XXX.cpp : fatal error C1853: 'FilePathZ\XXX.pch' precompiled
我是一名优秀的程序员,十分优秀!