简体   繁体   中英

mvc web api authentication token cors problem

Good day,

I am working with asp.net api and Angular.

When I am trying to get my authentication token from my api, I receive errors

d

I have a controller that returns an authentication token for my application.This is the logic for the controller

        [HttpPost]
    [Route("authenticate")]
    public async System.Threading.Tasks.Task<IHttpActionResult> AuthenticateAsync(LoginRequest login)
    {
        if (login == null)
            throw new HttpResponseException(HttpStatusCode.BadRequest);

        var result = await SignInManager.PasswordSignInAsync(login.Username, login.Password, false, shouldLockout: false);
       var strCurrentUserId = User.Identity.GetUserId();
        switch (result)
        {
            case SignInStatus.Success:
                {
                    LoginAprovado loginAprovado = new LoginAprovado
                    {
                        Token = TokenGenerator.GenerateTokenJwt(DateTime.Now.ToString() + login.Username + Guid.NewGuid()),
                        UserId = User.Identity.GetUserId()
                    };                       
                    return Ok(loginAprovado);
                }                  
            default:
                {
                    return Unauthorized();
                }
        }
    }

As you can see, I am returning the object LoginAprovado.

I do not know how to fix this problem, it seems a cors issue.

This is my web config

  <appSettings>

<add key="JWT_AUDIENCE_TOKEN" value="http://mysite.azurewebsites.net/" />
<add key="JWT_ISSUER_TOKEN" value="http://mysite.azurewebsites.net/" />
...more here
  <system.webServer>
<httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
        </customHeaders>
    </httpProtocol>

Note that in my customeheaders section, the access-controol-allow-origin is set to * so I can debug my front end in local.

What can I do to fix the issue? thanks

根据我的经验,对我Configuration(IAppBuilder app)Startup类的第一行Configuration(IAppBuilder app)方法中添加以下行(如果您使用的是OWIN ):

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM