2

I have a controller which tries to get a token.

I got this error in postman when I execute it in the view PRETTY

Unexpected 'e'

But if I go to the view RAW I can see the token like this.

eyJraWQiOiIxIiwiYWxnIjoiUlMyNTYifQ.eyJpc3MiOiJJc3N1ZXIiLCJhdWQiOiJBdWRpZW5jZSIsImV4cCI6MTQ3NTQ1OTMyNiwianRpIjoiTmF3d000bDVGRmFRZ0dBQkwzS3N5USIsImlhdCI6MTQ3NTQ1ODcyNiwibmJmIjoxNDc1NDU4NjA2LCJzdWIiOiJzdWJqZWN0IiwiZW1haWwiOiJtYWlsQGV4YW1wbGUuY29tIn0.f97SFDaAjUyUDK_UQgwgnCTewd0yw6tWK6DFLzpALFq177f1QMTYPbVdiIG1ViJ0FNJ6fUCleCd8BmrToUn25VSmRv799dtcz-xaN1kOgw90NQ00kPUhnDXG01-7hImkHfbmZZWORukP2yPK1sHWzpdjg9fJOvRZpZ6ZWli4HeuYRJqsFOv7PvwmGH9JnfRTf_2tboL-oAYBpT367eh60TggrvMgmrO_Taj5M7qGG0GpbwuVh_HTAkaKv7T2WmuZ2JPANhe5JvY_DDaqChtwd0IPREAhK3Xr-nTOIuwbQ0Y1hhOGfvDmikQj6DXnCERYixP6eR1dhC8n3bKvXyaVmA

This is the code of my controller.

@Path("/demo")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response testMethod() throws JSONException, IOException {
    RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
    rsaJsonWebKey.setKeyId("k1");
    JwtClaims claims = new JwtClaims();
    claims.setIssuer("Issuer");  
    claims.setAudience("Audience");
    claims.setExpirationTimeMinutesInTheFuture(10);    
    claims.setGeneratedJwtId(); 
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(2); 
    claims.setSubject("subject"); 
    claims.setClaim("email","mail@example.com"); 
    JsonWebSignature jws = new JsonWebSignature();

    jws.setPayload(claims.toJson());
    jws.setKey(rsaJsonWebKey.getPrivateKey());
    jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());

    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    String jwt = jws.getCompactSerialization();
    if(jwt == null){
        return Response.status(204).entity(jwt).build();
    }
    return Response.status(200).entity(jwt).build();
}

I ignore the error in postman but I get the same error when try to execute it in Chrome.

I try to call my RESTful controller with angular like this, but I always get into the onError method with the message within the response parameter.

angular.min.js:118 SyntaxError: Unexpected token e in JSON at position 0

This is the code in angular

app.service('TokenService', function($http){
    this.getToken = function(){
      function onSuccess(response){
          console.log('got it');
      }

      function onError(response){
          console.log('fail');
      }

      return $http({
          method : 'GET',
          url : 'http:localhost:8080/rest/demo',
          header: {'Content-Type' : 'application/json'}
      }).then(onSuccess, onError);
    }
}

My reference of the code for the token is from here with Jose4j

UPDATE

I solved this. I still think the way I did it initially it should work also, but I don't still understand why I get the error.

I created a pojo named Token with a property token as String then I changed this

return Response.status(200).entity(jwt).build();

to this:

Token token = new Token();
token.setToken(jwt);
return Response.status(200).entity(token).build();

This is my workaround to return a real json object.

Maximus Decimus
  • 4,901
  • 22
  • 67
  • 95

1 Answers1

0

I know it's much too late now, but I've faced the same problem and got it fixed with your solution, so Thanks.

Just for the sake of whoever came across this issue later. In my case I do it like this.

HashMap<String, String> credential = new HashMap<>();
credential.put("token", jwtToken);
apiResp = ResponseEntity.ok(jwtToken);

Btw, I also seem to figured out the problem which is Angular might expect that response from server is JSON object by default then parse it to JavaScript object for us. So we got our error because we return string as a response entity and it can't parse string to an object. That's why putting the token in POJO solved it.

The other way around is setting return type from client-side like this.

login(username: string, password: string): Observable<any> {
    let body = {username, password};
    let res = this.http.post(
      `${API.AUTHENTICATION}`, body, {
        responseType: 'text'
      });
  
    return res;
  }

Now, JS will know that the response is of string type and it won't try to parse it to an object anymore.

KradasA4
  • 165
  • 1
  • 2
  • 11