Programing

passport.js RESTful 인증

lottogame 2020. 6. 7. 00:40
반응형

passport.js RESTful 인증


웹 인터페이스 대신 RESTful API를 통해 passport.js를 사용하여 인증 (예 : 로컬 및 Facebook)을 어떻게 처리합니까?

특정 문제는 일반적인 res.send ({data : req.data})를 사용하여 콜백에서 RESTful 응답 (JSON)으로 데이터가 전달되는 것을 처리하고 Facebook으로 리디렉션되는 초기 / login 엔드 포인트를 설정하는 것입니다 (/ login은 JSON 응답이 아니기 때문에 AJAX를 통해 액세스합니다-콜백을 통해 Facebook으로 리디렉션됩니다).

https://github.com/halrobertson/test-restify-passport-facebook을 찾았 지만 이해하는 데 문제가 있습니다.

또한 passport.js는 인증 자격 증명을 어떻게 저장합니까? 서버 (또는 서비스입니까?)는 MongoDB에 의해 지원되며 자격 증명 (로그인 및 소금에 절인 해시)이 거기에 저장 될 것으로 기대하지만 passport.js에 이러한 유형의 기능이 있는지는 알 수 없습니다.


여기에는 많은 질문이 있으며 Node 및 passport.js의 맥락에서 질문이 있지만 실제 기술은 특정 기술로이를 수행하는 방법보다 워크 플로우에 관한 것입니다.

추가 보안을 위해 약간 수정 된 @Keith 예제 설정을 사용합시다.

  • 의 웹 서버 https://example.com는 단일 페이지 Javascript 클라이언트 앱을 제공합니다.
  • RESTful 웹 서비스는 https://example.com/api리치 클라이언트 앱에 서버 지원을 제공합니다.
  • Node 및 passport.js에 서버가 구현되었습니다.
  • 서버에는 "users"테이블이있는 데이터베이스 (모든 종류)가 있습니다.
  • 사용자 이름 / 암호 및 Facebook Connect는 인증 옵션으로 제공됩니다
  • 리치 클라이언트는 REST 요청을 https://example.com/api
  • 의 웹 서비스를 사용 https://example.com/api하지만의 웹 서버에 대해 모르는 다른 클라이언트 (예 : 전화 앱)가있을 수 있습니다 https://example.com.

보안 HTTP를 사용하고 있습니다. 암호와 인증 토큰과 같은 민감한 정보가 클라이언트와 서버간에 전달되므로 공개적으로 사용 가능한 모든 서비스의 필수 요소입니다.

아이디 / 비밀번호 인증

먼저 일반 인증이 어떻게 작동하는지 봅시다.

  • 사용자는 https://example.com
  • 서버는 초기 페이지를 렌더링하는 풍부한 Javascript 애플리케이션을 제공합니다. 페이지에는 로그인 양식이 있습니다.
  • 이 단일 페이지 앱의 많은 섹션은 사용자가 로그인하지 않아서 데이터로 채워지지 않았습니다.이 모든 섹션에는 "로그인"이벤트에 대한 이벤트 리스너가 있습니다. 이 모든 것은 클라이언트 쪽 일이며 서버는 이러한 이벤트를 알지 못합니다.
  • 사용자는 로그인 및 비밀번호를 입력하고 제출 버튼을 누르면 Javascript 핸들러가 트리거되어 클라이언트 측 변수에 사용자 이름 및 비밀번호를 기록합니다. 그런 다음이 핸들러는 "로그인"이벤트를 트리거합니다. 다시 말하지만 이것은 모든 클라이언트 측 작업이며 자격 증명이 아직 서버로 전송되지 않았습니다 .
  • "login"이벤트의 리스너가 호출됩니다. 이들 각각은 이제 https://example.com/api페이지에서 렌더링 할 사용자 특정 데이터를 얻기 위해 RESTful API에 하나 이상의 요청을 보내야 합니다. RESTful 한 서비스는 한 요청에서 다음 요청으로 클라이언트 상태를 유지할 수 없으므로 웹 서비스로 전송하는 모든 단일 요청에는 HTTP 기본 인증 형식의 사용자 이름과 비밀번호가 포함됩니다 . 웹 서비스는 보안 HTTP에 있으므로 전송 중에 비밀번호가 안전하게 암호화됩니다.
  • 의 웹 서비스는 https://example.com/api각각 인증 정보가있는 많은 개별 요청 수신합니다. 각 요청의 사용자 이름과 비밀번호는 사용자 데이터베이스와 비교하여 확인되며 요청이 발견되면 요청 된 함수가 올바르게 실행되고 데이터가 JSON 형식으로 클라이언트에 리턴됩니다. 사용자 이름과 비밀번호가 일치하지 않으면 401 HTTP 오류 코드 형식으로 클라이언트에 오류가 전송됩니다.
  • 클라이언트가 모든 요청에 ​​대해 사용자 이름과 비밀번호를 보내도록하는 대신 RESTful 서비스에서 "get_access_token"함수를 사용하여 사용자 이름과 비밀번호를 가져와 고유 한 토큰이있는 토큰으로 응답합니다. 관련 날짜. 이 토큰은 각 사용자와 함께 데이터베이스에 저장됩니다. 그런 다음 클라이언트는 후속 요청에서 액세스 토큰을 보냅니다. 그런 다음 사용자 이름과 비밀번호 대신 데이터베이스에 대해 액세스 토큰의 유효성이 검사됩니다.
  • 전화 앱과 같은 비 브라우저 클라이언트 응용 프로그램은 위와 동일하게 사용자에게 자격 증명을 입력 한 다음 요청이있을 때마다 웹 서비스에 자격 증명 (또는 액세스 토큰)을 보내도록 요청합니다.

이 예에서 중요한 점은 RESTful 웹 서비스가 모든 요청에 ​​대해 인증을 요구 한다는 것 입니다.

이 시나리오의 추가 보안 계층은 사용자 인증 외에 클라이언트 응용 프로그램 인증을 추가합니다. 예를 들어 웹 서비스를 사용하는 웹 클라이언트, iOS 및 Android 앱이있는 경우 인증 된 사용자가 누구인지에 관계없이 서버가 지정된 요청의 세 클라이언트 중 어느 클라이언트인지 알기를 원할 수 있습니다. 이를 통해 웹 서비스가 특정 기능을 특정 클라이언트로 제한 할 수 있습니다. 이를 위해 API 키와 비밀을 사용할 수 있습니다. 이에 대한 아이디어는 이 답변참조하십시오 .

페이스 북 인증

Facebook을 통한 로그인에는 Facebook 자체의 타사가 있으므로 위의 워크 플로는 Facebook 연결에서 작동하지 않습니다. 로그인 절차는 사용자가 자격 증명이 우리의 통제 범위 밖에서 입력되는 Facebook 웹 사이트로 리디렉션되도록 요구합니다.

어떻게 변화하는지 봅시다 :.

  • 사용자는 https://example.com
  • 서버는 초기 페이지를 렌더링하는 풍부한 Javascript 애플리케이션을 제공합니다. 페이지에 "페이스 북으로 로그인"버튼이 포함 된 로그인 양식이 있습니다.
  • 사용자는 "페이스 북으로 로그인"버튼을 클릭합니다 (예 :) https://example.com/auth/facebook.
  • https://example.com/auth/facebook경로가 passport.js에 의해 처리합니다 (참조 문서 )
  • All the user sees is that the page changes and now they are in a Facebook hosted page where they need to login and authorize our web application. This is completely outside of our control.
  • The user logs in to Facebook and gives permission to our application, so Facebook now redirects back to the callback URL that we configured in the passport.js setup, which following the example in the documentation is https://example.com/auth/facebook/callback
  • The passport.js handler for the https://example.com/auth/facebook/callback route will invoke the callback function that receives the Facebook access token and some user information from Facebook, including the user's email address.
  • With the email we can locate the user in our database and store the Facebook access token with it.
  • The last thing you do in the Facebook callback is to redirect back to the rich client application, but this time we need to pass the username and the access token to the client so that it can use them. This can be done in a number of ways. For example, Javascript variables can be added to the page through a server-side template engine, or else a cookie can be returned with this information. (thanks to @RyanKimber for pointing out the security issues with passing this data in the URL, as I initially suggested).
  • So now we start the single page app one more time, but the client has the username and the access token.
  • The client application can trigger the "login" event immediately and let the different parts of the application request the information that they need from the web service.
  • All the requests sent to https://example.com/api will include the Facebook access token for authentication, or the application's own access token generated from Facebook's token via a "get_access_token" function in the REST API.
  • The non-browser apps have it a bit more difficult here, because OAuth requires a web browser for logging in. To login from a phone or desktop app you will need to start a browser to do the redirect to Facebook, and even worse, you need a way for the browser to pass the Facebook access token back to the application via some mechanism.

I hope this answers most of the questions. Of course you can replace Facebook with Twitter, Google, or any other OAuth based authentication service.

I'd be interested to know if someone has a simpler way to deal with this.


I greatly appreciate @Miguel's explanation with the complete flow in each cases, but I'd like to add some on the Facebook Authentication part.

Facebook provides a Javascript SDK which you can use to get the access token on client-end directly, which is then passed to the server and used to further pull all the user information from Facebook. So you don't need any re-directs basically.

Moreover, you can use the same API end-point for mobile applications as well. Just use the Android / iOS SDK for Facebook, obtain the Facebook access_token on the client end and pass it to the server.

Regarding the stateless nature as explained, when get_access_token is used to generate a token and passed to the client, this token is also stored on the server. So it's as good as a session token and I believe this makes it stateful ?

Just my 2 cents..


Here is an awesome article I found that can help you authenticate with:

  • Facebook
  • Twitter
  • Google
  • Local Auth

Easy Node Authentication: Setup and Local

참고URL : https://stackoverflow.com/questions/14572600/passport-js-restful-auth

반응형