如何获得令牌?,

时间:2020-04-09 21:01:58

标签: java hibernate jpa jax-rs

我有一个名为(AuthenticationAXService)的服务(JAX-RS),我在其中生成令牌,但是我想在此类之外使用该令牌?

    private Student student;

    @POST
    @Consumes("application/json") 
    @Produces("application/json")
    public Response authenticateUser(Credentials credentials) {
        try {
            String username = credentials.getUsername();
            String password = credentials.getPassword();
            //System.out.println("credentials " + username);
            // Authenticate the user using the credentials provided         
            Student student = authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            //save token into db
            Calendar tokenExpires = Calendar.getInstance();
            tokenExpires.add(Calendar.MINUTE, 2); 
            student.setToken(token);
            student.setTokenExpires(tokenExpires.getTime());
            studentMethods.updateUser(student);

            // Return the token on the response
            return Response.ok(token).build();
        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

生成令牌的方法:

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
        Random random = new SecureRandom();
        String token = new BigInteger(130, random).toString(32);
        return token;
    }

我想要的是如何获取此令牌,因为我想在此类之外使用它,所以我想在UserService类的查询中使用它,以过滤带有用户令牌的内容,例如:

    public List<Book> returnBooks() {
        TypedQuery<Book> query = em.createQuery("SELECT s.books from Student s where s.token = :token", Book.class);
        query.setParameter("token", student.getToken());
        List<Book> resultList = query.getResultList();
        return resultList;  
    }

0 个答案:

没有答案