Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 无法获取令牌有效性_Spring_Spring Boot_Security_Jpa_Jwt - Fatal编程技术网

Spring 无法获取令牌有效性

Spring 无法获取令牌有效性,spring,spring-boot,security,jpa,jwt,Spring,Spring Boot,Security,Jpa,Jwt,所以,这里是我的HomeController页面代码,我在其中使用authenticationFeignClient访问jwt认证微服务 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import o

所以,这里是我的HomeController页面代码,我在其中使用authenticationFeignClient访问jwt认证微服务

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.returnordermanagement.returnOrderPortal.Client.AuthenticationFeignClient;
import com.returnordermanagement.returnOrderPortal.Model.AuthenticationRequest;
import com.returnordermanagement.returnOrderPortal.Model.AuthenticationResponse;
import com.returnordermanagement.returnOrderPortal.service.LoginService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class HomeController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private AuthenticationRequest authenticationRequest;

    @Autowired
    private AuthenticationResponse authenticationResponse;

    @Autowired
    private AuthenticationFeignClient authenticationFeignClient;

    @RequestMapping("/")
    public String loginPage() {
        log.info("login page");
        return "login.jsp";
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        log.info("Inside Login method");
        authenticationRequest.setUsername(username);
        authenticationRequest.setPassword(password);
        log.info("Invoking Authentication Microservice");
        authenticationResponse = authenticationFeignClient.createAuthenticationToken(authenticationRequest);

        String jwtToken = authenticationResponse.getJwtToken();
        Boolean isValid = authenticationResponse.getValid();
        int userId = 10;
        loginService.createUser(userId, username, password, jwtToken, isValid);
        log.info("Validating Authentication Response");
        if (authenticationResponse.getValid()) {
            log.info("validation successfull");
            return "home.jsp";
        }
        return "login.jsp";

    }
}
当我运行上面的代码authenticationResponse时,我从authenticationFeignClient获得的代码不会返回令牌,并且是有效的

验证外部客户端

package com.returnordermanagement.returnOrderPortal.Client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.returnordermanagement.returnOrderPortal.Model.AuthenticationRequest;
import com.returnordermanagement.returnOrderPortal.Model.AuthenticationResponse;

@FeignClient(name = "authenticationFeignClient", url = "http://localhost:9004/")
public interface AuthenticationFeignClient {

    @PostMapping("/login")
    public AuthenticationResponse createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest);

}
authu模型类

import org.springframework.stereotype.Component;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Component
public class AuthenticationResponse {
    private int userID;
    private String jwtToken;
    private Boolean valid;

}
下面是jwt身份验证控制器的代码,从中我对用户进行身份验证,并返回一个包含令牌和isvalid-boolena值的响应

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import com.returnordermanagement.jwtAuthentication.exception.BadCredentialException;
import com.returnordermanagement.jwtAuthentication.model.AuthenticationRequest;
import com.returnordermanagement.jwtAuthentication.model.AuthenticationResponse;
import com.returnordermanagement.jwtAuthentication.model.JwtUser;
import com.returnordermanagement.jwtAuthentication.repository.JwtUserRepository;
import com.returnordermanagement.jwtAuthentication.service.JwtTokenUtilService;
import com.returnordermanagement.jwtAuthentication.service.JwtUserDetailsService;
import com.returnordermanagement.jwtAuthentication.service.JwtValidateService;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class JwtAuthenticationController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtTokenUtilService jwtTokenUtilService;

    @Autowired
    private JwtUserRepository jwtUserRepository;

    @SuppressWarnings("unused")
    @Autowired
    private JwtValidateService jwtValidateService;

    @PostMapping("/login")
    public AuthenticationResponse createAuthenticationToken(
            @RequestBody AuthenticationRequest authenticationRequest) throws BadCredentialException {

        log.info("authentication of user= " + authenticationRequest.getUsername());
        JwtUser jwtUser = new JwtUser(authenticationRequest.getUsername(), authenticationRequest.getPassword());
//      saving the user in the jwt user repository
        log.info("user saved");
        jwtUserRepository.save(jwtUser);

        log.info("Login authentication");
        /*
         * Manually Authenticate User with Spring Security :
         * 
         * is passing the UsernamePasswordAuthenticationToken to the default
         * AuthenticationProvider, which will use the userDetailsService to get the user
         * based on username and compare that user's password with the one in the
         * authentication token.
         */
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
                    authenticationRequest.getUsername(), authenticationRequest.getPassword()));
        } catch (Exception e) {
            throw new BadCredentialException("username/password not correct ");
        }

        final UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(authenticationRequest.getUsername());
        final String jwtToken = jwtTokenUtilService.generateToken(userDetails);

//       create a authentication response entity . the model for this is already made with fields token,validity
        AuthenticationResponse authenticationResponse = new AuthenticationResponse(jwtToken, true);
        log.info(authenticationResponse.getToken() + "................." + authenticationResponse.getValidity());
        log.info("successfully authenticated");
        return authenticationResponse;

    }

    @GetMapping("/validate")
    public AuthenticationResponse getAuthenticationResponse(@RequestHeader("Authorization") final String jwtToken) {
        log.info("Validating the jwt token ");
        log.info("validation successfull");

        /*
         * AuthenticationResponse authenticationResponse = null;
         * authenticationResponse.setToken(jwtToken.substring(7)); if
         * (jwtTokenUtilService.validateToken(jwtToken.substring(7))) {
         * 
         * authenticationResponse.setValidity(true); } else {
         * authenticationResponse.setValidity(false); }
         * 
         * return authenticationResponse;
         */

        return jwtValidateService.validate(jwtToken);
    }

    /*
     * validating token extraction from authorization header --> check the validity
     * of token --> return an athenticationResponse Instance with two attributes
     * String jwtToken , Boolean valid;
     * 
     */

}

this is the out what i receive from the above auth microservice when i call this sing the feign client 
2021-06-02 07:11:50.668  INFO 3976 --- [nio-9004-exec-1] c.r.j.c.JwtAuthenticationController      : user saved
2021-06-02 07:11:50.857  INFO 3976 --- [nio-9004-exec-1] c.r.j.c.JwtAuthenticationController      : Login authentication
2021-06-02 07:11:51.320  INFO 3976 --- [nio-9004-exec-1] c.r.j.c.JwtAuthenticationController      : eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJha2FzaCIsImV4cCI6MTYyMjU5OTkxMSwiaWF0IjoxNjIyNTk4MTExfQ.FwKHKSn98GSCZ_7-BRylW5dQN9omSd45AzXMy-vuNHM.................true
2021-06-02 07:11:51.320  INFO 3976 --- [nio-9004-exec-1] c.r.j.c.JwtAuthenticationController      : successfully authenticated
所以,我能够得到

  • 代币=eyJhbGciOiJIUzI1NiJ9.EYJZDWIJHA2FZACIMV4CCI6MYMJU5OTKXMSWIAWF0IJOXNJIYNTK4MTEXFQ.FwKHKSn98GSCZ_7-BRylW5dQN9omSd45AzXMy-vuNHM
  • 有效=true
由于我已将其作为身份验证响应返回,因此它应返回令牌和isvalid布尔值,但我收到了此错误

2021-06-02 07:11:33.322  INFO 19112 --- [nio-9000-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms
2021-06-02 07:11:33.479  INFO 19112 --- [nio-9000-exec-1] c.r.r.controller.HomeController          : login page
2021-06-02 07:11:50.241  INFO 19112 --- [nio-9000-exec-2] c.r.r.controller.HomeController          : Inside Login method
2021-06-02 07:11:50.241  INFO 19112 --- [nio-9000-exec-2] c.r.r.controller.HomeController          : Invoking Authentication Microservice
2021-06-02 07:11:51.507 ERROR 19112 --- [nio-9000-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because "isValid" is null] with root cause

java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because "isValid" is null

你给我们看的代码更新了吗?您使用具有2个参数的构造函数,但在AuthenticationResponse中有3个成员:
newAuthenticationResponse(jwtToken,true)
。为什么AuthenticationResponse被注释为@Component?