angularjs - springboot+angularjs JWT 身份验证
问题描述
我在生成 jwt 令牌时遇到问题。我正在使用 Springboot 和 AngularJs。我花了很多时间寻找任何解决方案,但一无所获。我还想问(如果可以的话),我怎样才能在应用程序中保留令牌。我应该使用 $localStorage 还是 $Window 或其他东西?
@RequestMapping(value = "/user-login")
public ResponseEntity<Map<String, Object>> login(@RequestParam String email, @RequestParam String password) throws IOException {
String token = null;
User appUser = userRepository.findByEmail(email);
Map<String, Object> tokenMap = new HashMap<String, Object>();
if (appUser != null && appUser.getPassword().equals(password)) {
token = Jwts.builder().setSubject(email).claim("roles", appUser.getRoles()).setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, "secretkey").compact();
tokenMap.put("token", token);
tokenMap.put("user", appUser);
return new ResponseEntity<Map<String, Object>>(tokenMap, HttpStatus.OK);
} else {
tokenMap.put("token", null);
return new ResponseEntity<Map<String, Object>>(tokenMap, HttpStatus.UNAUTHORIZED);
}
}
角度控制器
angular.module('app')
.controller('LoginController', function ($http, AuthService, $rootScope, $scope, $location){
var vm = this;
$scope.login = function () {
// requesting the token by usename and passoword
$http({
url: 'user-login',
method: "POST",
params: {
email: $scope.email,
password: $scope.password
}
})
.then(function success(res){
$scope.password = null;
// checking if the token is available in the response
if (res.token) {
vm.message = '';
// setting the Authorization Bearer token with JWT token
$http.defaults.headers.common['Authorization'] = 'Bearer ' + res.token;
// setting the user in AuthService
AuthService.user = res.user;
$rootScope.authenticated = true;
// going to the home page
$location.path('/home');
}
else {
// if the token is not present in the response then the
// authentication was not successful. Setting the error message.
vm.message = 'Authetication Failed !';
}
},function error (error) {
vm.message = 'Authetication Failed !';
});
}
});
我总是收到空令牌和 401 状态。代码似乎正确。我在哪里犯错的任何想法?
解决方案
推荐阅读
- excel - 更换工作表并丢失范围参考
- vue.js - 将 Bootstrap 与 VueJS 一起使用时未捕获的 TypeError
- android - 无法从 Fragment B 获取 dat 到 Fragment A
- c# - 玩家每获得 10 分,钻石币加 1
- python - 如何在网络抓取中将地理编码 api 密钥与 python 集成
- javascript - 除了@click,我如何使用 v-on="$listeners"?
- r - R中的精确召回曲线
- kotlin - java.util.Iterator java.lang.Iterable.iterator() '关于一个空对象的引用我需要帮助理解
- r - R regmatches regexpr 想要排除分隔符
- python - 由于未加载渐变,微调 SavedModel 失败