Axios无法通过API进行身份验证 [英] Axios not authenticating to API

查看:125
本文介绍了Axios无法通过API进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整天都在尝试从我的Asp.Net Api中获取数据,但无济于事.我登录并从服务器获取身份验证令牌,并将其存储在本地,但是当我尝试执行任何需要身份验证的操作时,服务器将返回401响应.我的代码中我做错什么了吗?当我使用邮递员之类的工具时,一切正常,但在我的应用程序中却无法使用.这是我的登录名

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));
    }
}

这是我的axios封装器

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}`
})

这就是我的消费方式

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

这是服务器上记录的内容

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 

推荐答案

使用axios.create方法的方法不正确.参考: https://github.com/axios/axios#request-config

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

文档清楚地表明config auth:指示应使用HTTP Basic身份验证,并提供凭据.对于Bearer令牌等,请改用 Authorization 自定义标头,因此在您的情况下,您可以执行以下操作

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}})

这篇关于Axios无法通过API进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆