Home > OS >  Keycloak - React.js cannot call API
Keycloak - React.js cannot call API

Time:03-15

I have a simple React.js application. I want to test if it can call an endpoint from my API. Both my API and React.js application are using Keycloak for Authentication.

Here is my API endpoint:

[HttpGet]
[Route("authorization")]
[Authorize(Roles = "prototype-user")]
public string TestAuthorization()
{
    return "Authorization is working!";
}

This displays the Authorization is working message when tested in Postman. All other endpoints works well in postman.

Now, I tried calling this endpoint in my React.js application which is also using Keycloak. Here is my code snippet

constructor(props) {
    super(props);
    this.state = {
        result: [],
        token: null
    };

    //this is passed from another component derived from keycloak.idToken
    this.state.token = this.props.token 
}

componentDidMount(){
    var url = this.getBaseUrl()   "/authorization";
    fetch(url, {
        method: "get",
        credentials: "include",
        headers: {
            'Authorization': `token ${this.state.token}`,
        },
    }).then(
        res=>res.json())
    .then(
        result=>{
            this.setState({result:result})
        }
    ).catch(error =>
        alert(error)
    )
}

This returns an error saying SyntaxError:JSON.parse: unexpected character at line 1 column 1 of JSON data and not even entering my API breakpoint.

Can anyone tell me what is wrong with this? I am new to React.js so I do not have any idea how to solve this issue. I already looked for other references but cannot find any.

Thank you!

CodePudding user response:

Already solved this answer trough changing token to `bearer in the authorization header.

componentDidMount() {
    var url = this.getBaseUrl()   "/authorization";
    fetch(url, {
        method: "get",
        credentials: "include",
        headers: {
            'Authorization': `Bearer ${this.state.token}`,
        },
    }).then((response) => {
        if (response.status == 200) {
            return response.json()
        } else {
            throw new Error(response.status)
        }
    })
        .then(result => {
            this.setState({ result: result })
        }).catch(error =>
            alert(error)
        )
}
  • Related