【发布时间】:2016-02-09 19:07:01
【问题描述】:
我阅读了很多有关 JWT 的内容,但我不确定我编写的代码。
我在开头有“之前”过滤器,就像这样:
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 调用中添加标头 X-API-TOKEN,我想我做了一些破旧的事情,因为我已经读过它应该在每个请求中添加,所以在角度调用中我已添加:
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 代码是否足够安全?
【问题讨论】:
标签: angularjs jwt spark-java