Getting bearer token via Refit

-- -- 957 Reputation points
2022-02-01T15:16:18.513+00:00

Hi

I have an API that takes a username and password and then returns a bearer token. The curl code is below at the end.

How can I make the call to get the token via Refit?

Many thanks

Regards

curl -X 'POST' \
  'http://localhost:65202/api/Authentication/Authenticate' \
  -H 'accept: */*' \
  -H 'Content-Type: application/json;odata.metadata=minimal;odata.streaming=true' \
  -d '{ "userName": "Admin", "password": "" }'
Windows development Windows API - Win32
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2022-02-01T21:27:59.46+00:00

    Well if you had an API with an endpoint like this (a .NET 6.0 Microsoft.NET.Sdk.Web project):

    var builder = WebApplication.CreateBuilder(args);
    
    var app = builder.Build();
    
    app.MapPost("/api/Authentication/Authenticate", (AuthDetails details) => {
        return "token_123";
    });
    
    app.Run();
    
    class AuthDetails {
        public string Username { get; set; }
        public string Password { get; set; }
    }
    

    Then you could call it like this (a .NET 6.0 Microsoft.NET.Sdk project):

    using Refit;
    
    var authApi = RestService.For<IAuthApi>("https://localhost:7286");
    var token = await authApi.GetToken(new AuthDetails { Username = "Paul", Password = "gimme_a_token" });
    
    Console.WriteLine(token);
    Console.ReadLine();
    
    public class AuthDetails {
        public string Username { get; set; }
        public string Password { get; set; }
    }
    
    public interface IAuthApi {
        [Post("/api/Authentication/Authenticate")]
        Task<string> GetToken(AuthDetails details);
    }
    

    I suppose it makes sense if you have these AuthDetails request/response types you could put them in a separate project and share them between the projects.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.