node.js에서 로그인 인증을 구현하는 방법
이 노드 서버가 실행 중입니다.
var server=http.createServer(function(request, responsehttp) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var POST = qs.parse(body);
processquery(POST, request, responsehttp);
});
} else {
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
console.log(query);
processquery(query, request, responsehttp);
}
});
이 서버에 대한 로그인 양식을 추가하고 싶습니다. 사용자가 인증되면 표시됩니다.
function processquery(query, request, responsehttp){
var returnResult = function (data){
responsehttp.end(JSON.stringify(data));
};
if (!query.command) {
fileprocess(request, responsehttp);
}
responsehttp.writeHead(200, {"Content-Type": "application/json"});
switch(query.command) {
case 'logout':
logout(query, returnResult);
break;
case 'login':
login(query, returnResult);
break;
}
}
명령이 주어지지 않으면 클라이언트에 파일을 반환하는 프로세스 쿼리 기능이므로 클라이언트에서 서버로 로그인 명령을 보낼 수 있지만 사용자 이름 암호로 로그인 명령을 받으면 서버가해야 할 일, 로그인 요청을 전달하는 방법 로그인 성공 또는 실패를 반환합니다.이 부분을 작성하려면 도움이 필요합니다.
내가 시도한 것.
function login(request, callback) {
if(request.username==users[request.username] && request.password==users[request.username].password) {
users[request.username].auth=true;
var data = {result:'success','message':'login successful'};
callback(data);
} else {
var data = {result:'error','message':'login incorrect'};
callback(data);
}
}
로그인 기능에 추가를 시도하고 변수를 요청하고 request.session이 정의되지 않았다고 말하는 request.session 변수를 설정하려고 시도했습니다.
모든 사용자에 대해 로그인 인증을 적절하게 유지할 수있는이 로그인 모듈을 작성하는 방법을 제안하십시오.
Express.js로 수행하는 방법은 다음과 같습니다.
1) 사용자 인증 여부 확인 : 사용자 인증 이 필요한 모든 경로에서 사용하는 CheckAuth라는 미들웨어 기능이 있습니다.
function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.send('You are not authorized to view this page');
} else {
next();
}
}
다음과 같은 내 경로에서이 기능을 사용합니다.
app.get('/my_secret_page', checkAuth, function (req, res) {
res.send('if you are viewing this page it means you are logged in');
});
2) 로그인 경로 :
app.post('/login', function (req, res) {
var post = req.body;
if (post.user === 'john' && post.password === 'johnspassword') {
req.session.user_id = johns_user_id_here;
res.redirect('/my_secret_page');
} else {
res.send('Bad user/pass');
}
});
3) 로그 아웃 경로 :
app.get('/logout', function (req, res) {
delete req.session.user_id;
res.redirect('/login');
});
더 Express.js에 대해 알아 여기에 자신의 사이트를 확인하려면 다음 expressjs.com/en/guide/routing.html을 더 복잡한 것들에 대한 필요가 있다면, 체크 아웃 everyauth은 (는 페이스 북, 트위터를 들어, 사용 가능한 인증 방법을 많이 가지고 등; 여기 에 좋은 튜토리얼 ).
실제로 이것은 질문의 답은 아니지만 이것이 더 나은 방법입니다.
I suggest you to use connect/express as http server, since they save you a lot of time. You obviously don't want to reinvent the wheel. In your case session management is much easier with connect/express.
Beside that for authentication I suggest you to use everyauth. Which supports a lot of authentication strategies. Awesome for rapid development.
All this can be easily down with some copy pasting from their documentation!
To add to Farid's pseudo-answer,
Consider using Passport.js over everyauth.
The answers to this question provide some insight to the differences.
There are plenty of benefits to offloading your user authentication to Google, Facebook or another website. If your application's requirements are such that you could use Passport as your sole authentication provider or alongside traditional login, it can make the experience easier for your users.
@alessioalex answer is a perfect demo for fresh node user. But anyway, it's hard to write checkAuth middleware into all routes except login, so it's better to move the checkAuth from every route to one entry with app.use. For example:
function checkAuth(req, res, next) {
// if logined or it's login request, then go next route
if (isLogin || (req.path === '/login' && req.method === 'POST')) {
next()
} else {
res.send('Not logged in yet.')
}
}
app.use('/', checkAuth)
I tried this answer and it didn't work for me. I am also a newbie on web development and took classes where i used mlab but i prefer parse which is why i had to look for the most suitable solution. Here is my own current solution using parse on expressJS.
1)Check if the user is authenticated: I have a middleware function named isLogginIn which I use on every route that needs the user to be authenticated:
function isLoggedIn(req, res, next) {
var currentUser = Parse.User.current();
if (currentUser) {
next()
} else {
res.send("you are not authorised");
}
}
I use this function in my routes like this:
app.get('/my_secret_page', isLoggedIn, function (req, res)
{
res.send('if you are viewing this page it means you are logged in');
});
2) The Login Route:
// handling login logic
app.post('/login', function(req, res) {
Parse.User.enableUnsafeCurrentUser();
Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
res.redirect('/books');
}, function(error) {
res.render('login', { flash: error.message });
});
});
3) The logout route:
// logic route
app.get("/logout", function(req, res){
Parse.User.logOut().then(() => {
var currentUser = Parse.User.current(); // this will now be null
});
res.redirect('/login');
});
This worked very well for me and i made complete reference to the documentation here https://docs.parseplatform.org/js/guide/#users
Thanks to @alessioalex for his answer. I have only updated with the latest practices.
참고URL : https://stackoverflow.com/questions/7990890/how-to-implement-login-auth-in-node-js
'program story' 카테고리의 다른 글
간단한 PHP 개발 서버가 있습니까? (0) | 2020.10.20 |
---|---|
C #에서 절대 경로에 대한 상대 경로? (0) | 2020.10.20 |
EmberJS : 동일한 경로에서 여러 모델을로드하는 방법은 무엇입니까? (0) | 2020.10.20 |
ES6를 사용한 VS 코드 (0) | 2020.10.20 |
Spring Security에서 'X-Frame-Options'응답 헤더를 비활성화하는 방법은 무엇입니까? (0) | 2020.10.20 |