使用Nginx使用Spotify进行授权

问题描述 投票:4回答:1

我有一个运行三项服务的docker app:

  • 客户端 - >反应前端
  • 网--- ---烧瓶后端
  • nginx - > - 两者的反向代理

这是(简化的)项目结构:

docker-compose-dev.yml
services/
        client/
              src/
                 app.jsx
                 components/ 
                           spotify-auth.js
                           Spotify.jsx
         nginx/
              dev.conf
         web/

这是我在构建时定义暴露端口的地方:

多克尔 - 撰写,dev.yml

  web:
    build:
      context: ./services/web
      dockerfile: Dockerfile-dev
    volumes:
      - './services/web:/usr/src/app'
    ports:
      - 5001:5000 <----------------
    environment:
      - FLASK_ENV=development
      - APP_SETTINGS=project.config.DevelopmentConfig
    depends_on:  
      - web-db

  nginx:
    build:
      context: ./services/nginx
      dockerfile: Dockerfile-dev
    restart: always
    ports:
      - 80:80     <----------------
      - 8888:8888 <----------------
    depends_on:
      - web
      - client

  client:
    build:
      context: ./services/client
      dockerfile: Dockerfile-dev
    volumes:
      - './services/client:/usr/src/app'
      - '/usr/src/app/node_modules'
    ports:
      - 3007:3000   <----------------
    environment:
      - NODE_ENV=development
      - REACT_APP_WEB_SERVICE_URL=${REACT_APP_WEB_SERVICE_URL}
    depends_on:
      - web

REDIRECT

反过来,Client服务需要使用Spotify进行身份验证,Redirect URI需要https://developer.spotify.com,在enter image description here列入白名单。对我来说,我有几个选择:

server { listen 80; listen 8888; location / { // frontend at localhost:3000 proxy_pass http://client:3000; proxy_redirect default; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /users { // backend at localhost:5000 proxy_pass http://web:5000; proxy_redirect default; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /auth { # this authentication is for the app, not spotify proxy_pass http://web:5000; proxy_redirect default; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } }

这是我的nginx文件,我尝试组织正确的端口:

dev.conf

js

最后,有我的jsxand和Implicit Grant文件用于:

  1. 使用Spotify进行身份验证-----> localhost
  2. 将我的应用程序重定向回'/'export const stateKey = 'spotify_auth_state'; export const client_id = 'my_client_id'; // Your client id export const redirect_uri = 'http://localhost:3000'; // my redirect uri //export const redirect_uri = 'http://localhost:8888'; // my second try for uri export const scope ='user-read-private user-read-email user-read-playback-state playlist-modify-public playlist-modify-private';

Spotify的-auth.js

class SpotifyAuth extends Component {  
  constructor (props) {
    super(props);
    this.state = {
      isAuthenticatedWithSpotify: false
    };
    this.state.handleRedirect = this.handleRedirect.bind(this);
    this.loginSpotifyUser = this.loginSpotifyUser.bind(this);
  };

  function generateRandomString(length) {
    let text = '';
    const possible =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for (let i = 0; i < length; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return text;
  }

  getHashParams() {
    const hashParams = {};
    const r = /([^&;=]+)=?([^&;]*)/g;
    const q = window.location.hash.substring(1);
    let e = r.exec(q);
    while (e) {
      hashParams[e[1]] = decodeURIComponent(e[2]);
      e = r.exec(q);
    }
    return hashParams;
  }

  componentDidMount() {
    const params = this.getHashParams();

    const access_token = params.access_token;
    const state = params.state;
    const storedState = localStorage.getItem(stateKey);
    //localStorage.setItem('spotifyAuthToken', access_token);
    //localStorage.getItem('spotifyAuthToken');
    if (access_token && (state == null || state !== storedState)) {
      alert('There was an error during the authentication');
    } else {
      localStorage.removeItem(stateKey);
    }   
    // DO STUFF WITH ACCESS TOKEN HERE -- send ajax to backend routes    
  };

  handleRedirect() {
    const state = generateRandomString(16);
    localStorage.setItem(stateKey, state);

    let url = 'https://accounts.spotify.com/authorize';
    url += '?response_type=token';
    url += '&client_id=' + encodeURIComponent(client_id);
    url += '&scope=' + encodeURIComponent(scope);
    url += '&redirect_uri=' + encodeURIComponent(redirect_uri);
    url += '&state=' + encodeURIComponent(state);

    window.location = url;
    // post data to backend
    const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/auth/spotify}`;
    axios.post(url, data)
    .then((res) => {
      this.loginSpotifyUser(res.data.auth_token);
    })
    .catch((err) => { console.log(err); });    
  };

  loginSpotifyUser(token) {
    window.localStorage.setItem('spotifyAuthToken', token);
    this.setState({ isAuthenticatedWithSpotify: true });
    this.props.createMessage('Welcome to Spotify', 'success');
  };

  render() {
    return (
      <div className="button_container">
        <button className="sp_button" onClick={this.handleRedirect}>
          <strong>CONNECT YOUR SPOTIFY ACCOUNT</strong>
        </button>
      </div>
      )
    }
}

export default SpotifyAuth;

Spotify.jsx

render() {
  return (
  <div>  
    <Switch>
       <Route exact path='/' render={() => (
          <SpotifyAuth/>
        )} 
       />
    </Switch>
   </div>

和渲染,像这样:

App.jsx

INVALID_CLIENT: Invalid redirect URI 

错误:

设置并运行所有这些后,我得到:

env

日志:

在构建之前,我导出了这个$ export REACT_APP_WEB_SERVICE_URL=http://localhost 变量:

logs

服务建成后,我得到了client_1 | You can now view client in the browser. client_1 | client_1 | Local: http://localhost:3000/ web_1 | * Environment: development web_1 | * Debug mode: on web_1 | * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) nginx_1 | 172.21.0.1 - - [27/Mar/2019:03:58:56 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36" "-" nginx_1 | 172.21.0.1 - - [27/Mar/2019:03:58:56 +0000] "GET /static/js/0.chunk.js HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36" "-" nginx_1 | 172.21.0.1 - - [27/Mar/2019:03:58:56 +0000] "GET /static/js/bundle.js HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36" "-" nginx_1 | 172.21.0.1 - - [27/Mar/2019:03:58:56 +0000] "GET /static/js/main.chunk.js HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36" "-"

localhost:8888

注意:

如果我尝试在Spotify.jsx使用Spotify,该应用程序设法使用localhost:8888/auth/login进行身份验证,但随后所有位置都以localhost:3000开头,依此类推,这是不可取的。


题:

为什么client,我的redirect uri不会像Spotify那样工作?我错过了什么?

这是docker在像这样的docker-compose.yml项目上进行身份验证的最可靠方式吗?

reactjs docker nginx spotify
1个回答
4
投票

你的问题:

你的client有配置端口映射3007:3000host:container容器。请注意,Docker-compose端口映射是Compose file referencenginx),这意味着主机的端口3007映射到容器的端口3000。

这样,您尝试连接到主机中不可用的容器端口,尽管http://localhost:3000对此感到满意,因为它与您的客户端位于同一网络上,因此它可以访问它并重定向请求。

如果是这种情况:

  • http://localhost:3007不起作用,因为它在主机端关闭。
  • redirect_uri打开您的客户端,因为它被重定向到您的客户端容器,但除非您将此URL列入白名单并更改了您的http://localhost:8888,否则您将无法使用Spotify身份验证。
  • nginx打开您的客户端,因为您将docker-compose设置为反向代理,并且它可以访问客户端端口3000,因为它位于同一网络上。

你的解决方案

您的解决方案是更改3000:3000,因此客户端映射到端口nginx。然后Spotify auth应该没问题,因为端口是打开的并且URL已正确配置。

额外:

关于您对设计的意见请求,nginx对您的设计感觉有点不足。如果您设置了反向代理,那么您重定向到的服务将隐藏在无法从外部访问的安全网络中。这样,您可以在client上配置SSL,并忘记其余服务上的HTTP。但是,如果可以从其他端口访问此类服务,则进行此类配置是没有用的。

在生产设置中,您需要关闭docker-compose中的webnginx端口(字面意思是删除端口映射.Nginx在访问容器时没有问题,因为它位于同一网络上,与您的主机不同)并且只留下rewrite暴露在现实世界中。

您可能还想设置http://localhost/client规则,其中客户端和服务器分别挂在http://localhost/serverhttp://localhost:3000/地址上,但是nginx会重写请求并将其代理到适当的容器,因此容器实际上会看到请求来到Stack Exchange - Nginx reverse proxy + URL rewrite。您可以在qazxswpoi上看到有关如何配置所有这些的示例。

© www.soinside.com 2019 - 2024. All rights reserved.