In my asp.net webforms app, (.net Framework 4.8) I have a button click to call the api, i call it thusly
protected void Button1_Click( object sender, EventArgs e )
{
try
{
string buffer = string.Empty;
// Create an HttpClient instance
HttpClient client = new HttpClient();
var result = AsyncHelper.RunSync<string>( () => client.GetStringAsync( "http://localhost:44331/DoCdssLoginTests?sAdName=bob.bob" ) );
TextBox1.Text = result;
}
catch ( Exception ex )
{
TextBox1.Text = ex.Message;
throw;
}
}
if okta security is off, i can call it, but if it’s on it fails (as expected) the app the button is on is logged in oidc to okta. How do i get the token and pass it to the api call above?
You could try retrieving access token from HttpContext and add it as bearer token in your HttpClient which is making API calls to your resource server.
Here is a sample of what I used in my MVC app,
var accessToken = await HttpContext.GetTokenAsync("access_token");
using(var httpClient = new HttpClient())
{
string apiUrl = "<<Resource API URL>>";
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.GetStringAsync(apiUrl);
}
For webforms, you could do something similar to get token from HttpContext.
After running the samples, I was able to retrieve access token using the following,
var accessToken = HttpContext.Current.GetOwinContext().Authentication.User.Claims.FirstOrDefault(x => x.Type == "access_token")?.Value;
You should also see this token available in profile page of the sample which displays all user claims stored in OWIN context.
The one you were trying to use might be suitable for a Resource Server which protects API endpoints whereas this one is useful in clients which actually works with IDP to get a new access token.
how would i pass that token along to the webapi call? Like this?
string buffer = string.Empty;
// Create an HttpClient instance
HttpClient client = new HttpClient();
// uncommetn out once I cna get the token
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", accessToken );
var result = AsyncHelper.RunSync<string>( () => client.GetStringAsync( "http://localhost:44331/DoCdssLoginTests?sAdName=bob.bob" ) );
TextBox1.Text = result;