1

Ive been trying all day to get data from my Asp.Net Api but with no avail. I login and get an authentication token from the server and store it locally but when I try to perform any action that requires authentication, the server returns a 401 response. Is there something Im doing wrong in my code? When I use a tool like postman, everything works okay but not in my app. This is my login

try {
      response = await API.post(AuthUrl, credentials)
      if(response.status >= 200 || response.status <= 299){
        let Auth = {
          Username: response.data.Username,
          Roles: response.data.Roles,
          Expires: response.data.Expires,
          Token: response.data.Token
        };
        localStorage.setItem(window.location.host, JSON.stringify(Auth));
    }
}

This is my axios encapsulator

export default axios.create({
    baseURL: BaseUrl,
    responseType: "json",
    auth: `Bearer ${localStorage.getItem(window.location.host) == null? "" : JSON.parse(localStorage.getItem(window.location.host)).Token}`
})

and this is how im consuming it

try{
                const response = await API.get(getUrl)
                setLoading(false);
               //........Do something with response
}

This is what is logged at the server

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44307/api/classes/getclasses/  
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: CORS policy execution successful.
Microsoft.AspNetCore.Routing.EndpointMiddleware:Information: Executing endpoint 'SchoolManager.Web.Controllers.ClassesController.GetClasses (SchoolManager.Web)'
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "GetClasses", controller = "Classes", page = "", area = ""}. Executing controller action with signature System.Collections.Generic.IEnumerable`1[SchoolManager.Dtos.Tenancy.ClassDto] GetClasses(System.String, System.String) on controller SchoolManager.Web.Controllers.ClassesController (SchoolManager.Web).
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: CORS policy execution successful.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes (Bearer).
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: AuthenticationScheme: Bearer was challenged.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action SchoolManager.Web.Controllers.ClassesController.GetClasses (SchoolManager.Web) in 146.8824ms
Microsoft.AspNetCore.Routing.EndpointMiddleware:Information: Executed endpoint 'SchoolManager.Web.Controllers.ClassesController.GetClasses (SchoolManager.Web)'
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 218.2724ms 401 
Formula12
  • 305
  • 1
  • 3
  • 14
  • Could be a CORS issue. Did you check https://stackoverflow.com/questions/31942037/how-to-enable-cors-in-asp-net-core – Rohit Dec 31 '19 at 01:28
  • From my API endpoint, it shows CORS is executed successfully but then fails to pass authentication. Im thinking that the authentication token is not being sent to the server. Though when I put a breakpoint over it, the token is being retrieved from `localStorage`. Take a look at the logging in my edit – Formula12 Jan 01 '20 at 01:25
  • It certainly is a CORS isssue. You have to enable CORS in your server too and try changing responseType to application/json. Also, Postman doesn't care about CORS requests. – Prateek Oraon Jan 01 '20 at 01:39
  • But are you aware that the server is accepting authentication requests and sending back the token? – Formula12 Jan 01 '20 at 05:38
  • Or is there a better way to perform API requests and save sessions rather than using axios? My react app is just an API consumer. It doesn't have any application logic of its own. – Formula12 Jan 02 '20 at 07:45
  • can you try adding the header parameter in your axios.create something like this ```headers: {'Authorization': "bearer " + token}``` instead on ```auth: `Bearer``` REF : https://github.com/axios/axios#creating-an-instance – Rohit Jan 03 '20 at 03:38

1 Answers1

3

The way the axios.create method is used is not right. Ref: https://github.com/axios/axios#request-config

The documentation clearly shows that config auth: indicates that HTTP Basic auth should be used, and supplies credentials. For Bearer tokens and such, use Authorization custom headers instead so in your case you can do something like this

export default axios.create({
baseURL: BaseUrl,
responseType: "json",
headers: {'Authorization': "bearer " + JSON.parse(localStorage.getItem(window.location.host)).Token}})
Rohit
  • 370
  • 2
  • 11