49 lines
1.4 KiB
C#
49 lines
1.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net.Http;
|
|
using System.Threading.Tasks;
|
|
using System.Web;
|
|
|
|
namespace VECV_WebApi.App_Start
|
|
{
|
|
public class TokenService
|
|
{
|
|
public async Task<string> GetAccessTokenAsync()
|
|
{
|
|
var tokenEndpoint = "https://your-auth-server.com/oauth/token";
|
|
var clientId = "your_client_id";
|
|
var clientSecret = "your_client_secret";
|
|
var username = "user@example.com";
|
|
var password = "user_password";
|
|
|
|
using (var client = new HttpClient())
|
|
{
|
|
var formData = new Dictionary<string, string>
|
|
{
|
|
{"grant_type", "password"},
|
|
{"client_id", clientId},
|
|
{"client_secret", clientSecret},
|
|
{"username", username},
|
|
{"password", password}
|
|
};
|
|
|
|
var content = new FormUrlEncodedContent(formData);
|
|
|
|
var response = await client.PostAsync(tokenEndpoint, content);
|
|
var responseContent = await response.Content.ReadAsStringAsync();
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
// Parse and return access_token (you can use JSON.NET)
|
|
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(responseContent);
|
|
return result.access_token;
|
|
}
|
|
else
|
|
{
|
|
throw new Exception("Failed to get token: " + responseContent);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |