如何通过外部API登录生成JWT?

时间:2018-01-04 09:48:02

标签: asp.net asp.net-core jwt asp.net-core-2.0 asp.net-core-middleware

我有一个外部API,包括登录服务并生成JWT我需要将我的asp.net核心应用程序与此外部登录服务连接以通过生成的令牌登录

try
{
                // validate user name and password
                loginInfo = await service.LoginAsync(loginUrl, userName, password);


                await HttpContext.SignInAsync(loginInfo.Token);
                returnTo = returnUrl;
                success = true;
            }
            catch (Exception httpEx)
            {

            }

1 个答案:

答案 0 :(得分:0)

尝试此操作以调用外部API以获得令牌并将其在您的项目中使用

public class Wrapper
{
    string baseUrl = string.Empty;
    string token = string.Empty;

    public Wrapper()
    {
        this.baseUrl = "your url";
    }

    public async Task<object> GetToken(string username, string password)
    {
        string Url = "/api/Token/Get";
        object body = null;

            body = new
            {
                Username = username,
                Password = password
            };

        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseUrl);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage Response = await client.PostAsync(Url, new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json")).ConfigureAwait(false);
                if (Response.IsSuccessStatusCode)
                {
                    var result = Response.Content.ReadAsStringAsync().Result;
                    if (string.IsNullOrEmpty(JObject.Parse(result).Property("error").Value.ToString()))
                    {
                        token = JObject.Parse(result).Property("access_token").Value.ToString();
                        return token;
                    }
                    else
                    {
                       return string.Empty;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}