.NET Bearer Token无法[授权]总是401 Unauthorized

时间:2018-05-15 14:30:07

标签: unauthorized authorize

我是.NET的新手并试图在某些WebAPI中实现Bearer Token:

我的控制器:

public class ClientController : Controller
{
    [Route("/api")]
    [AllowAnonymous]
    [HttpGet("{clientKey}")]
    public async Task<IActionResult> UserLogin(string clientKey)
    {
        SQLDataResult response = null;

        List<SqlParameter> parameters = new List<SqlParameter>();
        parameters.Add(new SqlParameter("@clientKey", clientKey));

        response = await new SQLDataContext().StoredProcedureExecuteReaderAsync<SQLDataResult>("ClientCheck", parameters);

        if (response == null)
        {
            response = new SQLDataResult();
            return Ok(response);
        }
        else
        {
            var token = new JwtTokenBuilder()
                .AddSecurityKey(JwtSecurityKey.Create("imarh-secret-key"))
                .AddSubject("imarh")
                .AddIssuer("imarh.Security.Bearer")
                .AddAudience("imarh.Security.Bearer")
                .AddClaim("MembershipId", "111")
                .AddExpiry(1)
                .Build();
            return Ok(token.Value);
        }
    }

    [Authorize]
    [HttpPost] 
    [Route("/api/get/{clientID}")]
    public async Task<IActionResult> ClientAssign(string clientID)
    {
        SQLDataResult response = null;

        List<SqlParameter> parameters = new List<SqlParameter>();
        parameters.Add(new SqlParameter("@clientID", clientID));
        response = await new SQLDataContext().StoredProcedureExecuteReaderAsync<SQLDataResult>("ClientAssign", parameters);

        if (response == null)
            response = new SQLDataResult();

        return Ok(response);
    }
}

令牌正确。当我从第二个API中删除[Authorize]属性时,我将从数据库中获得正确的结果。但是当在Authorization标头中返回并传递生成的令牌时,我总是获得401 Unauthorized而没有任何结果。

1 个答案:

答案 0 :(得分:0)

假设在不同的情况下会发生这种情况,但在我的情况下,解决问题的唯一方法是:

// app.UseMvc();
Startup.cs