我想使用Nats websocket,但我不知道如何获得用户信息,所以我使用jwt,它工作,但它不工作时,我用我的代码生成用户jwt。
nats服务器配置文件
websocket
{
port: 8080
no_tls: true
# authorization {
# # If this is specified, the client has to provide the same username
# # and password to be able to connect.
# # username: "my_user_name"
# # password: "my_password"
#
# # If this is specified, the password field in the CONNECT has to
# # match this token.
# # token: "my_token"
#
# # This overrides the main's authorization timeout. For consistency
# # with the main's authorization configuration block, this is expressed
# # as a number of seconds.
# # timeout: 2.0
#}
}
# Operator named my_org
operator: eyJ0eXAiOiJKV1QiLCJhbGciOiJlZDI1NTE5LW5rZXkifQ.eyJqdGkiOiI3VVkzSkNaVUlVQUU0STZJWllBQ0NZUEdDWDdQQUlHRzczQklNTzVBT1NZMjJXQ1JZWDdRIiwiaWF0IjoxNjY4NDE3NDkzLCJpc3MiOiJPQzRLV0xGNU5CQkhPVjVLRFJGS0NITFkySEpBRFNYQUg2VEJHSk1XSEFVSFg3VlVOTkNTRVdJUyIsIm5hbWUiOiJteV9vcmciLCJzdWIiOiJPQzRLV0xGNU5CQkhPVjVLRFJGS0NITFkySEpBRFNYQUg2VEJHSk1XSEFVSFg3VlVOTkNTRVdJUyIsIm5hdHMiOnsic2lnbmluZ19rZXlzIjpbIk9DUFdTV0NQSlJNMlRDUjVIVjZFNkNFVklRV09MNExLNEJPS1VQRk5DNzNJVktZM0xIN0VVRTZZIl0sImFjY291bnRfc2VydmVyX3VybCI6Im5hdHM6Ly8wLjAuMC4wOjQyMjIiLCJzeXN0ZW1fYWNjb3VudCI6IkFDU0dDWENUVFpLWlVCRkFIN1lFR01HTkhQRFRPQlRJRUdONFlHS1JWT1hXT1FOM1Y2T1NVS1Q1Iiwic3RyaWN0X3NpZ25pbmdfa2V5X3VzYWdlIjp0cnVlLCJ0eXBlIjoib3BlcmF0b3IiLCJ2ZXJzaW9uIjoyfX0.axLP53rM3O2R6XNMagyX4vnBoYCp7DCA2lptVlX2i4lLdbN9x5Vm4eYP-7yG7kMqDG9rPG6HmgCyYoQndqpuAw
# System Account named SYS
system_account: ACSGCXCTTZKZUBFAH7YEGMGNHPDTOBTIEGN4YGKRVOXWOQN3V6OSUKT5
# configuration of the nats based resolver
resolver {
type: full
# Directory in which the account jwt will be stored
dir: './jwt'
# In order to support jwt deletion, set to true
# If the resolver type is full delete will rename the jwt.
# This is to allow manual restoration in case of inadvertent deletion.
# To restore a jwt, remove the added suffix .delete and restart or send a reload signal.
# To free up storage you must manually delete files with the suffix .delete.
allow_delete: false
# Interval at which a nats-server with a nats based account resolver will compare
# it's state with one random nats based account resolver in the cluster and if needed,
# exchange jwt and converge on the same set of jwt.
interval: "2m"
# Timeout for lookup requests in case an account does not exist locally.
timeout: "1.9s"
}
# Preload the nats based resolver with the system account jwt.
# This is not necessary but avoids a bootstrapping system account.
# This only applies to the system account. Therefore other account jwt are not included here.
# To populate the resolver:
# 1) make sure that your operator has the account server URL pointing at your nats servers.
# The url must start with: "nats://"
# nsc edit operator --account-jwt-server-url nats://localhost:4222
# 2) push your accounts using: nsc push --all
# The argument to push -u is optional if your account server url is set as described.
# 3) to prune accounts use: nsc push --prune
# In order to enable prune you must set above allow_delete to true
# Later changes to the system account take precedence over the system account jwt listed here.
resolver_preload: {
ACSGCXCTTZKZUBFAH7YEGMGNHPDTOBTIEGN4YGKRVOXWOQN3V6OSUKT5: eyJ0eXAiOiJKV1QiLCJhbGciOiJlZDI1NTE5LW5rZXkifQ.eyJqdGkiOiJMWUI0S0tCN0dKQTYyQTZMVk1BS1hFRlRWUE1DUkRQQVhBNktBSEZNTlZWWkIzSktCVlJRIiwiaWF0IjoxNjY4NDE3NDY5LCJpc3MiOiJPQ1BXU1dDUEpSTTJUQ1I1SFY2RTZDRVZJUVdPTDRMSzRCT0tVUEZOQzczSVZLWTNMSDdFVUU2WSIsIm5hbWUiOiJTWVMiLCJzdWIiOiJBQ1NHQ1hDVFRaS1pVQkZBSDdZRUdNR05IUERUT0JUSUVHTjRZR0tSVk9YV09RTjNWNk9TVUtUNSIs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hY2NvdW50IiwidmVyc2lvbiI6Mn19.DTH_ubEJpwPIj2tmr1eg8nI_HgKvFFqhQ0iL17fT8iy1bJ1AR_jnXg7CKNakYQrdb4pjEBzzpMoH_mbguSdGAQ,
}
当我使用nsc客户端工具它的工作,
x一个一个一个一个x一个一个二个x
当我使用我的代码时,它不起作用
package main
import (
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nats.go"
"github.com/nats-io/nkeys"
"time"
)
func main() {
ukp, err := nkeys.CreateUser()
if err != nil {
return
}
upub, err := ukp.PublicKey()
if err != nil {
return
}
seed, err := ukp.Seed()
if err != nil {
return
}
akp, _ := nkeys.FromSeed([]byte("SAAFREANAV7DLYTGDCST76AHUOAMK7CTK5RNJWPERHWEFPR7NXEHRTHUWI"))
userJWT := generateUserJWT(upub, akp)
jwtAuthOption := nats.UserJWTAndSeed(userJWT, string(seed))
nc, err := nats.Connect("nats://localhost:4222", jwtAuthOption)
if err != nil {
panic(err)
}
defer nc.Close()
}
func generateUserJWT(userPublicKey string, accountSigningKey nkeys.KeyPair) (userJWT string) {
uc := jwt.NewUserClaims(userPublicKey)
uc.Expires = time.Now().Add(time.Hour).Unix() // expire in an hour
var err error
uc.IssuerAccount, err = accountSigningKey.PublicKey()
if err != nil {
return ""
}
vr := jwt.ValidationResults{}
uc.Validate(&vr)
if vr.IsBlocking(true) {
panic("Generated user claim is invalid")
}
userJWT, err = uc.Encode(accountSigningKey)
if err != nil {
return ""
}
return
}
这是参考资料
https://docs.nats.io/running-a-nats-service/nats_admin/security/jwt#create-user-jwt https://github.com/ConnectEverything/rethink_connectivity_examples/tree/main/episode7
我的代码生成jwt其死机授权违规
这是我FE代码
import './App.css';
import {connect, jwtAuthenticator,credsAuthenticator, StringCodec} from 'nats.ws'
import {useEffect, useState} from "react";
const sc = StringCodec()
function App() {
const c=`-----BEGIN NATS USER JWT-----
eyJ0eXAiOiJKV1QiLCJhbGciOiJlZDI1NTE5LW5rZXkifQ.eyJqdGkiOiJWNFRMQU9aQjY2M1NJT0JCV1RCVkpWVVJOQkdLTUJBUERGVVk2WVUzM1JHQTRXRFBSSkdBIiwiaWF0IjoxNjY4NDkxODE4LCJpc3MiOiJBQTVZTzRRQVVQREhEWVFQR1lKMlRQN1dEV1RGVkNHUlVXVzdFSTVLQUhHM1RRWlVHMkdRVTZYSyIsIm5hbWUiOiJteS11c2VyIiwic3ViIjoiVURXRkFQVVUzWlAyQ1VFVkRWWkpBRjJRM0hLNlJLSU5YS0xQWjNYV0VFWkxJRE00RjdWMzZXM0MiLCJuYXRzIjp7InB1YiI6eyJhbGxvdyI6WyJmb28uXHUwMDNlIiwiYmFyLlx1MDAzZSJdfSwic3ViIjp7ImFsbG93IjpbIl9JTkJPWC5cdTAwM2UiXX0sInN1YnMiOi0xLCJkYXRhIjoxMDczNzQxODI0LCJwYXlsb2FkIjotMSwidHlwZSI6InVzZXIiLCJ2ZXJzaW9uIjoyfX0.6Zg8ekHENudDY2gT5hVfXomnQ1tGfHT7O__FrewjWXH3oaWPy81Qr7_U1ZzmuWPirTq4JsZjoOnV9TxmrwywCA
------END NATS USER JWT------
************************* IMPORTANT *************************
NKEY Seed printed below can be used to sign and prove identity.
NKEYs are sensitive and should be treated as secrets.
-----BEGIN USER NKEY SEED-----
SUAIRSUPV65OG3S5C66DIMLNY2IXNUSHT6QEBFMWXGBM7G3EGPJO3XHELE
------END USER NKEY SEED------
*************************************************************
`
const [nc, setConnection] = useState(undefined)
const [lastError, setError] = useState("")
const [messages, setMessages] = useState([])
let key = 0
const me = {id:"dddd",name:"ff"};
const addMessage = (err, msg) => {
if (err){
console.log(err)
}
key++;
const {subject, reply} = msg;
const data = sc.decode(msg.data)
console.log("msg==",subject,' data=',data)
const m = {subject, reply, data, key, time: new Date().toUTCString()}
messages.unshift(m)
const a = messages.slice(0, 10)
messages.unshift(a)
setMessages(a)
}
const who = (err,msg)=>{
msg.respond(me)
const {subject, reply} = msg;
const data = sc.decode(msg.data)
console.log("who==",subject,' data=',data)
}
const entered = (err,msg)=>{
const {subject, reply} = msg;
const data = sc.decode(msg.data)
console.log("en==",subject,' data=',data)
}
const exited = (err,msg)=>{
const {subject, reply} = msg;
const data = sc.decode(msg.data)
console.log("exit==",subject,' data=',data)
}
useEffect(() => {
console.log(nc)
if (nc === undefined) {
//connect({servers: ["nats://127.0.0.1:4222"],
connect({servers: ["ws://127.0.0.1:8083"],
//work //authenticator:jwtAuthenticator("eyJ0eXAiOiJKV1QiLCJhbGciOiJlZDI1NTE5LW5rZXkifQ.eyJqdGkiOiJCQ1kyRjUyRUxIU1kzV0RYUkhUU0FLUjU2TEZCWU4yUjdNSU5CWENNUUVZQ0JJNUVXQzNBIiwiaWF0IjoxNjY4NDE3NTI2LCJpc3MiOiJBQkRVWE9WTkdLV1o1QUlGR1g1VUdRSFJCUVo3S0dIWk9URDdOVTRWTVBKU1BRTkdXNkJNQjJQTCIsIm5hbWUiOiJtYXRoIiwic3ViIjoiVUE0RTNSRVU1Nlo3MjM2U0hTUURQSUY1UlhWRzJXVlkzV0NPRlJGRENSQkRTWkNWQkJPRFJQVkgiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e30sInN1YnMiOi0xLCJkYXRhIjotMSwicGF5bG9hZCI6LTEsImlzc3Vlcl9hY2NvdW50IjoiQUNYRElYRElJSVVUT1YzWDZITVVWSEUyTEJNUDI0N1FHS0IyWkFCQTdWSElGWjdKRU1TVUxTSkwiLCJ0eXBlIjoidXNlciIsInZlcnNpb24iOjJ9fQ.tDfuREQDIFiIOlAD1fe7jkrVPiaRSoAwcRa_e4G3AVby97XSssEN_EQCeT60WomOo1fHIFV9hgMCuPHQAaL_Ag", new TextEncoder().encode("SUALJXSMUDYDDKWMWLREDHEEBA7HZA5FJVJFVUYMELSQNT2BJJ3J665RDQ")),
//work //authenticator:jwtAuthenticator("eyJ0eXAiOiJKV1QiLCJhbGciOiJlZDI1NTE5LW5rZXkifQ.eyJqdGkiOiJUMlI3RURSVVNESUxJUUNKVFRGUVhLNVJaRUsyNl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IjotMSwicGF5bG9hZCI6LTEsImlzc3Vlcl9hY2NvdW50IjoiQUNTR0NYQ1RUWktaVUJGQUg3WUVHTUdOSFBEVE9CVElFR040WUdLUlZPWFdPUU4zVjZPU1VLVDUiLCJ0eXBlIjoidXNlciIsInZlcnNpb24iOjJ9fQ.6-pWmq1QUkmDGH6pZuXSm6pgE_VgHoJjukCMIQN6p3j5vFV5YrRWO48IDzKobUm1De4wkZHgGJZiFctM2PpDAA", new TextEncoder().encode("SUAFPCMKO6X6K2Z4GHKK7OXCLI3Q7VWOCJBIROLTX6ILSW2W7HZBJEDBJ4")),
//authenticator:credsAuthenticator(new TextEncoder().encode(c)),
waitOnFirstConnect: true,noEcho:true,
}).then(
(nc) => {
setConnection(nc)
nc.subscribe('>', {callback: addMessage})
nc.subscribe('user.who',{callback:who})
nc.subscribe('user.*.entered',{callback:entered})
nc.subscribe('user.*.exit',{callback:exited})
nc.publish('user.bob@bob.com.entered',sc.encode(me))
}
).catch((err) => {
setError(err)
console.log(lastError)
})
}
})
const state = nc ? 'connected' : "not yet con"
return (
<div className="container">
<h1>{state}</h1>
</div>
);
}
export default App;
1条答案
按热度按时间mpgws1up1#
只是为了确认一下:你在添加用户
math
后使用nsc push
你的更改了吗?你用解析器配置了你的nats服务器.这很好,但是你的解析器需要帐号信息来验证你的用户.