我读了很多关于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方法来对用户进行自动测试,并在respoonse中设置X令牌(它只是为了测试而变的简单,我将在数据库中获得用户数据):
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方法取自本教程:如何在Java中创建和验证JWT
登录页面:
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令牌,我想我做了一些工作,因为我读过应该在每个请求中添加它,所以在角调用中我添加了:
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';
});;我有两个问题:
发布于 2016-02-09 11:07:01
https://stackoverflow.com/questions/35256775
复制相似问题