springboot + angularjs JWT身份验证

时间:2020-10-22 13:59:22

标签: angularjs spring-boot 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状态。 该代码似乎正确。有什么想法让我犯错吗?

0 个答案:

没有答案