Du bist nicht angemeldet.

Stilllegung des Forums
Das Forum wurde am 05.06.2023 nach über 20 Jahren stillgelegt (weitere Informationen und ein kleiner Rückblick).
Registrierungen, Anmeldungen und Postings sind nicht mehr möglich. Öffentliche Inhalte sind weiterhin zugänglich.
Das Team von spieleprogrammierer.de bedankt sich bei der Community für die vielen schönen Jahre.
Wenn du eine deutschsprachige Spieleentwickler-Community suchst, schau doch mal im Discord und auf ZFX vorbei!

Werbeanzeige

Schorsch

Supermoderator

  • »Schorsch« ist der Autor dieses Themas

Beiträge: 5 145

Wohnort: Wickede

Beruf: Softwareentwickler

  • Private Nachricht senden

1

17.03.2017, 15:00

CSRF Token Mismatch, Python - Nodejs

Hallöle,
ich habe einen Nodejs Server welcher eine REST API bereitstellt. Hier wird zusätzlich ein Angular-Frontend ausgeliefert. Der Part passt soweit ohne Probleme. Jetzt möchte/muss/soll ich von einer Python-Flask Anwendung auf Services der REST API zugreifen. In Nodejs nutze ich lusca für CSRF Tokens. Die Konfiguration dafür:

Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
    app.use(lusca({
      csrf: {
        angular: true
      },
      xframe: 'SAMEORIGIN',
      hsts: {
        maxAge: 31536000, //1 year, in seconds
        includeSubDomains: true,
        preload: true
      },
      xssProtection: true
    }));


In Python versuche ich jetzt folgendermaßen auf die API zuzugreifen:

Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
@app.route("/test")
def test_login():
    client = requests.session()
    response = client.get('http://localhost:3000/login/')
    csrftoken = client.cookies['XSRF-TOKEN']
    login_data = {"username":'test', "password":'test', "X-XSRF-TOKEN":csrftoken}
    url = 'http://localhost:3000/api/auth/local'
    header = {"X-XSRF-TOKEN":csrftoken, "referrer":'http://localhost:3000/login/'}
    cookie = {"XSRF-TOKEN":csrftoken}
    response = client.post(url, data=login_data, headers=header, cookies=cookie)
    print(response)
    return (response.text, response.status_code)


Ich bekomme jedes mal einen Token mismatch. Wenn ich das Token in Python ausgebe stimmt es auch nicht mit dem überein welches in der Datenbank liegt. Wird da irgendetwas zusätzlich verschlüsselt oder? Ich stehe grad echt auf dem Schlauch und gerate langsam etwas unter Zeitdruck.

edit:
Mehr Code:
Login Formular:

Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <h1>Login</h1>
      <!--<p>Default account is <code>test@example.com</code> / <code>test</code></p>
     <p>Admin account is <code>admin@example.com</code> / <code>admin</code></p>-->
    </div>
    <div class="col-sm-12">
      <form class="form" name="form" ng-submit="vm.login(form)" novalidate>
 
        <div class="form-group">
          <label>Email</label>
 
          <input type="email" name="email" class="form-control" ng-model="vm.user.email" required>
        </div>
 
        <div class="form-group">
          <label>Password</label>
 
          <input type="password" name="password" class="form-control" ng-model="vm.user.password" required>
        </div>
 
        <div class="form-group has-error">
          <p class="help-block" ng-show="form.email.$error.required && form.password.$error.required && vm.submitted">
             Please enter your email and password.
          </p>
          <p class="help-block" ng-show="form.email.$error.email && vm.submitted">
             Please enter a valid email.
          </p>
 
          <p class="help-block">{{ vm.errors.login }}</p>
        </div>
 
        <div>
          <button class="btn btn-inverse btn-lg btn-login" type="submit">
            Login
          </button>
          <a class="btn btn-default btn-lg btn-register" ui-sref="signup">
            Register
          </a>
        </div>
 
      </form>
    </div>
  </div>
  <hr>
</div>


Login Controller:

Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
'use strict';
// @flow
interface User {
  name: string;
  email: string;
  password: string;
}
 
export default class LoginController {
  user: User = {
    name: '',
    email: '',
    password: ''
  };
  errors = {login: undefined};
  submitted = false;
  Auth;
  $state;
 
  /*@ngInject*/
  constructor(Auth, $state) {
    this.Auth = Auth;
    this.$state = $state;
  }
 
  login(form) {
    this.submitted = true;
 
    if (form.$valid) {
      this.Auth.login({
        email: this.user.email,
        password: this.user.password
      })
      .then(() => {
        // Logged in, redirect to home
        this.$state.go('main');
      })
      .catch(err => {
        this.errors.login = err.message;
      });
    }
  }
}


Auth Service:

Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
'use strict';
// @flow
class _User {
  _id: string = '';
  name: string = '';
  email: string = '';
  role: string = '';
  $promise = undefined;
}
 
export function AuthService($location, $http, $cookies, $q, appConfig, Util, User) {
  'ngInject';
  var safeCb = Util.safeCb;
  var currentUser: _User = new _User();
  var userRoles = appConfig.userRoles || [];
  /**
   * Check if userRole is >= role
   * @param {String} userRole - role of current user
   * @param {String} role - role to check against
   */
  var hasRole = function(userRole, role) {
    return userRoles.indexOf(userRole) >= userRoles.indexOf(role);
  };
 
  if($cookies.get('token') && $location.path() !== '/logout') {
    currentUser = User.get();
  }
 
  var Auth = {
    /**
     * Authenticate user and save token
     *
     * @param  {Object}   user     - login info
     * @param  {Function} callback - function(error, user)
     * @return {Promise}
     */
    login({email, password}, callback?: Function) {
      return $http.post('/auth/local', { email, password })
        .then(res => {
          $cookies.put('token', res.data.token);
          currentUser = User.get();
          return currentUser.$promise;
        })
        .then(user => {
          safeCb(callback)(null, user);
          return user;
        })
        .catch(err => {
          Auth.logout();
          safeCb(callback)(err.data);
          return $q.reject(err.data);
        });
    },
 
    /**
     * Delete access token and user info
     */
    logout() {
      $cookies.remove('token');
      currentUser = new _User();
    },
 
    /**
     * Create a new user
     *
     * @param  {Object}   user     - user info
     * @param  {Function} callback - function(error, user)
     * @return {Promise}
     */
    createUser(user, callback?: Function) {
      return User.save(user,
        function(data) {
          $cookies.put('token', data.token);
          currentUser = User.get();
          return safeCb(callback)(null, user);
        },
        function(err) {
          Auth.logout();
          return safeCb(callback)(err);
        }).$promise;
    },
 
    /**
     * Change password
     *
     * @param  {String}   oldPassword
     * @param  {String}   newPassword
     * @param  {Function} callback    - function(error, user)
     * @return {Promise}
     */
    changePassword(oldPassword, newPassword, callback?: Function) {
      return User.changePassword({ id: currentUser._id }, { oldPassword, newPassword }, function() {
        return safeCb(callback)(null);
      }, function(err) {
        return safeCb(callback)(err);
      }).$promise;
    },
 
    /**
     * Gets all available info on a user
     *
     * @param  {Function} [callback] - function(user)
     * @return {Promise}
     */
    getCurrentUser(callback?: Function) {
      var value = _.get(currentUser, '$promise')
        ? currentUser.$promise
        : currentUser;
 
      return $q.when(value)
        .then(user => {
          safeCb(callback)(user);
          return user;
        }, () => {
          safeCb(callback)({});
          return {};
        });
    },
 
    /**
     * Gets all available info on a user
     *
     * @return {Object}
     */
    getCurrentUserSync() {
      return currentUser;
    },
 
    /**
     * Check if a user is logged in
     *
     * @param  {Function} [callback] - function(is)
     * @return {Promise}
     */
    isLoggedIn(callback?: Function) {
      return Auth.getCurrentUser(undefined)
        .then(user => {
          let is = _.get(user, 'role');
 
          safeCb(callback)(is);
          return is;
        });
    },
 
    /**
     * Check if a user is logged in
     *
     * @return {Bool}
     */
    isLoggedInSync() {
      return !!_.get(currentUser, 'role');
    },
 
     /**
      * Check if a user has a specified role or higher
      *
      * @param  {String}     role     - the role to check against
      * @param  {Function} [callback] - function(has)
      * @return {Promise}
      */
    hasRole(role, callback?: Function) {
      return Auth.getCurrentUser(undefined)
        .then(user => {
          let has = hasRole(_.get(user, 'role'), role);
 
          safeCb(callback)(has);
          return has;
        });
    },
 
    /**
      * Check if a user has a specified role or higher
      *
      * @param  {String} role - the role to check against
      * @return {Bool}
      */
    hasRoleSync(role) {
      return hasRole(_.get(currentUser, 'role'), role);
    },
 
     /**
      * Check if a user is an admin
      *   (synchronous|asynchronous)
      *
      * @param  {Function|*} callback - optional, function(is)
      * @return {Bool|Promise}
      */
    isAdmin() {
      return Auth.hasRole
        .apply(Auth, [].concat.apply(['admin'], arguments));
    },
 
     /**
      * Check if a user is an admin
      *
      * @return {Bool}
      */
    isAdminSync() {
      return Auth.hasRoleSync('admin');
    },
 
    /**
     * Get auth token
     *
     * @return {String} - a token string used for authenticating
     */
    getToken() {
      return $cookies.get('token');
    }
  };
 
  return Auth;
}


Hier funktioniert alles. Ich vermute ich mache einfach einen total dämlichen Fehler.
„Es ist doch so. Zwei und zwei macht irgendwas, und vier und vier macht irgendwas. Leider nicht dasselbe, dann wär's leicht.
Das ist aber auch schon höhere Mathematik.“

Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von »Schorsch« (17.03.2017, 17:57)


Tobiking

1x Rätselkönig

  • Private Nachricht senden

2

17.03.2017, 18:43

Auf Anhieb fällt mir da nichts auf. Du könntest aber mal bei beiden Varianten mit Wireshark den Netzwerkverkehr aufzeichnen und vergleichen. Irgendwo muss da ein Unterschied stecken.

Schorsch

Supermoderator

  • »Schorsch« ist der Autor dieses Themas

Beiträge: 5 145

Wohnort: Wickede

Beruf: Softwareentwickler

  • Private Nachricht senden

3

18.03.2017, 12:10

An Wireshark hatte ich gar nicht gedacht. Guter Hinweis. Danke.
„Es ist doch so. Zwei und zwei macht irgendwas, und vier und vier macht irgendwas. Leider nicht dasselbe, dann wär's leicht.
Das ist aber auch schon höhere Mathematik.“

Schorsch

Supermoderator

  • »Schorsch« ist der Autor dieses Themas

Beiträge: 5 145

Wohnort: Wickede

Beruf: Softwareentwickler

  • Private Nachricht senden

4

24.03.2017, 15:12

Falls es für irgendjemanden von Interesse ist. Ich habe mich mal weiter in den Generator und den resultierenden Code eingearbeitet, sowie mehr über CSRF Tokens gelesen. Zuallererst habe ich Dinge durcheinander geworfen. Ein Response vom Server liefert mit einen CSRF Token. Dieser muss für den nächsten Request benutzt werden. Dabei kann das Encoding wichtig sein. Im Cookie benutzen die Dinger ein URL Encoding welches für den Header dekodiert werden muss. Weiterhin ging es bei mir für den Login noch um einen Authentifizierungstoken. Dieses wird nach erfolgreichem Login zurück gegeben und soll dann bei weiteren Requests mit übertragen werden. Das ist natürlich unabhängig vom CSRF Token. Die Probleme an sich waren also im Prinzip die Unterscheidung verschiedener Tokens, die Kodierung der Tokens und der Wechsel vom CSRF Token.
„Es ist doch so. Zwei und zwei macht irgendwas, und vier und vier macht irgendwas. Leider nicht dasselbe, dann wär's leicht.
Das ist aber auch schon höhere Mathematik.“

Werbeanzeige