如何通过访问邮递员中的[AllowAnonymous]创建发帖请求以访问[授权]

时间:2018-08-30 19:32:53

标签: api asp.net-core postman

i created .NETCore APT according to this by using jwt

这是我的TokenController的一部分

 [Route("api/[controller]")]
[ApiController]
public class TokenController : ControllerBase
{
    [AllowAnonymous]
    [HttpPost]
    public IActionResult CreateToken([FromBody]LoginModel login)
    {}

在令牌控制器中

      private UserModel Authenticate(LoginModel login)
    {
        UserModel user = null;

        if (login.Username == "mario" && login.Password == "secret")
        {
            user = new UserModel { Name = "Mario Rossi", Email = "mario.rossi@domain.com" };
        }
        return user;
    }

这是我的BooksController的一部分

[HttpGet, Authorize]
    public IEnumerable<Book> Get()
    {
        var currentUser = HttpContext.User;
        int userAge = 0;
        var resultBookList = new Book[] {
            new Book { Author = "Ray Bradbury", Title = "Fahrenheit 451" },
            new Book { Author = "Gabriel García Márquez", Title = "One"},
        };

        return resultBookList;
    }
}

当我通过邮递员向api /令牌发送{“ username”:“ mario”,“ password”:“ secret”}时,我将令牌返回给我 但是当我将其发送到api / books时,它没有返回如何通过邮递员创建帖子要求以获取书籍的详细信息

1 个答案:

答案 0 :(得分:1)

我想您是在问令牌如何用于将来的Web请求。如果是这样,则必须将标头添加到Web请求。示例:

Authorization: Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9DQp7InVuaXF1ZV9uYW1lIjoic3RldmUiLCJodHRwOi8vSnVuay93cy8yMDE4LzA1L2lkZW50aXR5L2NsYWltcy91c2VydHlwZSI6Ik4iLCJodHRwOi8vSnVuay93cy8yMDE4LzA1L2lkZW50aXR5L2NsYWltcy91c2Vyc3RhdHVzIjoiQSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL3NpZCI6IkJhcnJ5IiwiZW1haWwiOiIiLCJodHRwOi8vSnVuay93cy8yMDE4LzA1L2lkZW50aXR5L2NsYWltcy9yZXNldHBhc3N3b3JkIjoiRmFsc2UiLCJodHRwOi8vSnVuay93cy8yMDE4LzA1L2lkZW50aXR5L2NsYWltcy9jbGllbnRpZCI6IkFJMjE0MjYwIiwiaHR0cDovL0p1bmsvd3MvMjAxOC8wNS9pZGVudGl0eS9jbGFpbXMvc2Vzc2lvbnN0YXJ0IjoiNjM2NjY5MTk0NjEwNDUwNDkyIiwibmJmIjoxNTMxMzE3ODYxLCJleHAiOjE1MzEzNzc4NjEsImlhdCI6MTUzMTM0Nzg2MSwiaXNzIjoiSnVuayJ9DQo5VX/vv73QhF0M77+9PsWhWwjvv73vv70k77+9b++/vSrvv73vv73vv73vv71Z77+9Le+/ve+/vT3vv73vv73vv73vv71gWVRrdc6a77+9TnQCaCnvv70NCu+/vWRo77+977+977+9cWIy77+9HO+/vRF5DQo=

Postman允许添加自定义标头,但是对于此标头,我们可以使用Postman请求选项卡“授权”定义承载令牌标头。有关如何添加承载令牌标头的详细信息,请参见https://www.getpostman.com/docs/v6/postman/sending_api_requests/authorization