angularjs spark-java JWT认证安全吗?

angularjs spark-java JWT authetication is it safe?

我读了很多关于 JWT 的资料,但是我不确定我写的代码。
我在开头有 "Before" 过滤器,结果如下所示:

before("/protected/*", (request, response) -> {
        try {
             parseJWT(request.headers("X-API-TOKEN"));
        } catch (Exception e) {
            halt(401, "You are not welcome here");
            //don't trust the JWT!
        }
    });

我有 post 方法来验证用户并在响应中设置 X-API-TOKEN(它很简单只是为了测试,通常我会在数据库中有用户数据):

  post("/login", (req, res) -> {
        Gson gson = new Gson();
        User user = gson.fromJson(req.body(), User.class);
        if ((!user.getUsername().equals("foo") ||
                !user.getPassword().equals("bar"))) {
            halt(401, "You are not welcome here");
        }
        String jwt =
                createJWT(UUID.randomUUID().toString(), user.getUsername(), user.getUsername(),
                        15000); // just 15 secounds for test
        res.header("X-API-TOKEN", jwt);
        return res;
    });

createJWT 和 parseJWT 方法取自本教程: How to Create and Verify JWTs in Java

登录页面:

    form ng-submit="submit()">
      input ng-model="user.username" type="text" name="user" placeholder="Username" />
      input ng-model="user.password" type="password" name="pass" placeholder="Password" />
      input type="submit" value="Login" />
    /form>

和我的身份验证控制器:

    myModule.controller('UserCtrl', function (`$`scope, `$`http, `$`window) {
    `$`scope.submit = function () {
    `$`http
       .post('/login', `$`scope.user)
       .success(function (data, status, headers, config) {
     `$`window.sessionStorage.token = headers('X-API-TOKEN');
     `$`scope.message = 'Welcome protected';
    })
    .error(function (data, status, headers, config) {
    // Erase the token if the user fails to log in
    delete `$`window.sessionStorage.token;
    // Handle login errors here
    `$`scope.message = 'Error: Invalid user or password';
    `$`window.location.href = '#/auth';
    });
    };
    });

现在每次我访问受保护的站点时,我都需要向每个 http 调用添加 header X-API-TOKEN,我想我做了一些错误的事情,因为我已经读到应该在每个请求中添加它,所以在 angular 调用中我添加了:

      var config = {headers:  { 
             'X-API-TOKEN': `$`window.sessionStorage.token
           }
    };
      `$`http.get("/protected/elo", config)
      .success(function(response) {`$`scope.message = response;})
        .error(function (data, status, headers, config) {
                // Erase the token if the user fails to log in
                delete `$`window.sessionStorage.token;
                // Handle login errors here
                `$`scope.message = 'Error: Invalid user or password';
               `$`window.location.href = '#/auth';
              });;

我有两个问题:
1.如何在所有请求中自动添加X-API-TOKEN?
2. 如果我打开 ssl 代码是否足够安全?

  1. 您可以使用 $http.defaults.headers.common 将 header 添加到每个请求。参见 angular documentation。登录成功后应该配置。

    您还可以将令牌存储在 cookie 中以实现“记住我”功能。

  2. 如果您打开 SSL,那么这对于大多数用途来说应该足够安全。你仍然可以在服务器上添加更多的安全检查,比如检查 IP 地址(记住一些用户有动态 IP 号码)

我也推荐egghead.io course on using JWT with Angular