我正在尝试使用护照为我的新应用设置登录名,但是我遇到了一些困难,无论我做什么req.isAuthenticated()
总是错误的。我已尝试按照对其他此类问题的其他答复中的建议对中间件进行重新排序,但这无济于事,而且它已经按照正确的顺序排列了。
摩根输出:
POST /login 302 80.428 ms - 23
GET / 302 0.573 ms - 28
GET /login 200 0.544 ms - 12
这是我的代码:
const passport = require("passport")
const initializePassport = require("./passportConfig")
initializePassport(passport)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
cors({
origin: `http://${REACT_ENDPOINT}:${REACT_PORT}`,
credentials: true,
})
);
app.use(flash());
app.use(cookieParser("secretcode"));
app.use(
session({
cookie: {
secure: true,
maxAge: 86400,
sameSite: "none",
},
secret: "secretcode",
resave: true,
saveUninitialized: true,
})
);
app.use(passport.initialize());
app.use(passport.session());
我尝试将secure, resave, saveUninitialized
设置为true和false,没有明显差异。
这是passportConfig:
function initialize(passport) {
const authenticateUser = (username, password, done) => {
User.findOne({ username: username }, async (err, user) => {
if (err) throw err;
if (!user) return done(null, false, { message: "No user with that username!" });
try {
if (await bcrypt.compare(password, user.password)) {
console.log(user);
return done(null, user);
} else {
return done(null, false, { message: "Password is incorrect" });
}
} catch (e) {
return done(e);
}
});
};
passport.use(
new LocalStrategy(
{
usernameField: "username",
passwordField: "password",
},
authenticateUser
)
);
passport.serializeUser(({ id }, done) => {
User.findById(id, (err, user) => {
console.log(user);
done(null, user.id);
});
});
passport.deserializeUser((id, done) => {
console.log(id);
User.findOne({ _id: id }, (err, user) => {
done(null, user);
});
});
}
bcrypt.compare之后的console.logs
和serializeUser中的app.post(
"/login",
checkNotAuthenticated,
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true,
})
);
app.get("/login", (req, res) => {
res.send("please login");
});
app.get("/", checkAuthenticated, (req, res) => {
res.send("logged in");
});
function checkAuthenticated(req, res, next) {
console.log(req.isAuthenticated());
if (req.isAuthenticated()) return next();
res.redirect("/login");
}
都可以正常工作并返回正确的用户。但是稍后在我的路由中:
checkAuthenticated
在req.isAuthenticated()
中,bcrypt.compare
始终为假。但是序列化并User.findOne
给我正确的用户。
我尝试同时使用findById
和const mongoose = require("mongoose");
const User = new mongoose.Schema({
username: String,
password: String,
});
module.exports = mongoose.model("User", User);
两者之间没有区别。
用户模型:
function Get-VSMarketPlaceExtension {
[CmdLetBinding()]
Param(
[Parameter(ValueFromPipeline = $true,Mandatory = $true)]
[string[]]
$extensionName
)
begin {
$body=@{
filters = ,@{
criteria =,@{
filterType=7
value = $null
}
}
flags = 1712
}
}
process {
foreach($Extension in $extensionName) {
$response = try {
$body.filters[0].criteria[0].value = $Extension
$Query = $body|ConvertTo-JSON -Depth 4
(Invoke-WebRequest -Uri "https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=6.0-preview" -ErrorAction Stop -Body $Query -Method Post -ContentType "application/json")
} catch [System.Net.WebException] {
Write-Verbose "An exception was caught: $($_.Exception.Message)"
$_.Exception.Response
}
$statusCodeInt = [int]$response.StatusCode
if ($statusCodeInt -ge 400) {
Write-Warning "Erreur sur l'appel d'API : $($response.StatusDescription)"
return
}
$ObjResults = ($response.Content | ConvertFrom-Json).results
If ($ObjResults.resultMetadata.metadataItems.count -ne 1) {
Write-Warning "l'extension '$Extension' n'a pas été trouvée."
return
}
$Extension = $ObjResults.extensions
$obj2Download = ($Extension.versions[0].properties | Where-Object key -eq 'Microsoft.VisualStudio.Services.Payload.FileName').value
[PSCustomObject]@{
displayName = $Extension.displayName
extensionId = $Extension.extensionId
deploymentType = ($obj2Download -split '\.')[-1]
version = [version]$Extension.versions[0].version
LastUpdate = [datetime]$Extension.versions[0].lastUpdated
IsValidated = ($Extension.versions[0].flags -eq "validated")
extensionName = $Extension.extensionName
publisher = $Extension.publisher.publisherName
SourceURL = $Extension.versions[0].assetUri +"/" + $obj2Download
FileName = $obj2Download
}
}
}
}