Identity Server 4 store access token for subsequent requests - c#

I am logging in against identity server and getting a token back to a web application. Then i am getting the token and sending to an api. All works well. But i want to capture this token to use it for subsequent requests without having to call this line in controller actions. How do i do this?
var accessToken = await HttpContext.GetTokenAsync("access_token");

See this question for details now how to achieve that.
Also do check out this article

Related

how to generate bridgedataoutput api access token

i register on https://bridgedataoutput.com/ for using bridge data api. as per documents
https://bridgedataoutput.com/docs/platform/API/zg-data#Zestimates
require access token. how I get access token ?
after login , I get detail of Client id, Client Secret and Server Token. i try server token but give me authorization error.
I try to do get request on this below API link
https://api.bridgedataoutput.com/api/v2/zestimates_v2/zestimates?access_token=P7cbhWXt2PLOGOHbctzuOJ1qF2mJYSSF7cI1IrUabGdt3u2IGMiFzu5XLCNk&address=%22123%20Main%20Street%22
Response
{"success":false,"status":403,"bundle":{"name":"AuthenticationError","message":"Invalid access_token format"}}
I had the same issue, and Bridge support said to use the Server Token as the access token. It needs to go in the URL, not as a header when I tried it. Here's an example.
https://api.bridgedataoutput.com/api/v2/OData/[DATASET_ID]/[RESOURCE]?access_token=[SERVER_TOKEN]
Zillow Public Records, Zestimates and Econimic Data does need additional approval. Please confirm in https://bridgedataoutput.com/data/feeds.

Microsoft Graph authentication fails on web API

We currently have a client(MVC .Net Core Web Application) and web API which is used to access Microsoft Graph calls, the authentication process uses Azure AD v2.0 endpoint. we can get this working if we do all of this in the client, however, as soon as we pass the token to the Web API this fails and doesn't even return a response to help us diagnose. below are loads of things we have tried, we have come to the conclusion our azure hasn't been set up correctly but unsure.
Process 1 Works
We forget the web API and do all actions inside the client, this method works but not what we are after so we know the code is not broken.
Process 2 Fails
Client Authenticates to Microsoft graph
redirects with code to the client
send the code to Web API to authenticate, get access token and refresh token
Fails returns nothing
Process 3 Fails
Client Authenticates to Microsoft graph
redirects with code to the client
send the code in the client to authenticate, get access token and refresh token
send access token and refresh token to Web API
use token to perform Microsoft graph action
Fails returns nothing
Azure Settings
Within Microsoft Azure, we have tried configuring the Microsoft Active Directory to follow this example. However, this uses WPF and can't get this to work. We follow it step by step and even the user is prompted with the API permissions be still doesn't work. I am happy to provide any further information to help diagnose this issue.
Our architecture we are trying to achieve.
Update
This is where we exchange the authorization code for an access token however, this gives no return response and times out after about 100 seconds, doesn't even continue.
HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{"code", code},
{"client_id", _clientId},
{"client_secret", _clientSecret},
{"redirect_uri", _redirectUri},
{"grant_type", _codeGrantType}
});
using (HttpClient client = new HttpClient())
{
var response = await client.PostAsync(_tokenServerUrl, content);
if (response.IsSuccessStatusCode)
{
//get token from body and update expiry time...
var token = await response.Content.ReadAsJsonAsync<OAuthToken>();
token.ExpiresOn = DateTime.Now.AddSeconds(token.ExpiresIn - 100);
return token;
}

Passing authorization token to Odata client

I've been trying to consume an authorized ASP.NET Odata Web API by using an Odata client. I do know how to set the header with the token for the client, but where should the token be kept for re-use?. Because the Authorization header has to be set with each request, not just once. To be more precise, this is what I am down to:
Get user's credentials, pass them back to the API.
Get token.
Set the header for the Odata client with the token value.
I am struggling with the actions to be taken between 2nd and 3rd step: Where should the token be kept, so you could keep setting the Odata client Header with it?
This is how I set the authorization header value.
EDIT: In regards to the comment, I might've not clearly specified the issue. The problem arises, because controllers will be created for every request and will be garbage collected "sometime after" the request has completed. So, the token value will be gone.
have a look here, they are storing it in a cookie. If you do not want to expose the actual token on the client side, store it somewhere near your e.g. user profile / session, or store the token with a generated id in a lookup-table and save the id to a cookie.
this is another approach using ASP.NET Identity and ApplicationCookies

OneDrive for business Oauth2 authentication

I am trying to get access to OneDrive for Business using OAuth2.0 authentication protocol. I have followed this example:
http://msdn.microsoft.com/EN-US/library/dn605894(v=office.15).aspx
an this is my code so far:
// Create an authentication context
AuthenticationContext ac = new AuthenticationContext(string.Format("https://login.windows.net/{0}",
ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value));
String id = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value;
// Create a client credential based on the application id and secret.
ClientCredential clcred = new ClientCredential(AppPrincipalId, AppKey);
// Using the authorization code acquire an access token.
var arAD = ac.AcquireTokenByAuthorizationCode(code, new Uri(appRedirect), clcred);
I am getting a Authorization code is malformed error. I don't understand why I am getting this message.
Any help would be appreciated!
Had the same issue when I was trying to get authorization code manually and then use it from console application. Not sure why it doesn't work for me.
But when I use it from Web App, the same app which performed authorization and received code in return (because I specified it as returnURL) - everything works.
I suggest you to have a look on this example
https://github.com/AzureADSamples/WebApp-WebAPI-OAuth2-UserIdentity-DotNet
And also this article to understand what's happening under the good:
http://blogs.msdn.com/b/exchangedev/archive/2014/03/25/using-oauth2-to-access-calendar-contact-and-mail-api-in-exchange-online-in-office-365.aspx
P.S.
It's not a OneDrive, but I had exactly the same problem, so if you can make it working with Exchange or GraphApi, then it should work for OneDrive as well.
Authorization code is malformed error is occured if you send the auth code in incorrect format. May be the authorization code which you are sending is encoded value of authcode and session state. you need to seperate both values and send the auth code only. or decode the '&' symbol(seperator) between auth code and session state and send them as two parameters.
The method AcquireTokenByAuthorizationCode(...) from ADAL4j takes only authcode.

When I add google+ button to my website, how can I be aware that `access_token` expired?

Access tokens periodically expire and, when that happens, need to be refreshed. When an access token expires or at any other time, your application may be able to use a refresh token to obtain a new, valid access token. Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process.
I take this information from https://developers.google.com/youtube/v3/guides/authentication
How can I be aware that access_token expired ?
One very common approach is to catch HTTP Errors for all API requests you make. If you run into a 401 error it means the access token is not valid any more and you can try to refresh it and repeat the original request. If the token refresh fails it most likely means that the user has revoked access for your app.
In pseudo code:
result = makeApiRequest();
if (result.status == 401) {
refreshToken();
result = makeApiRequest();
}
Some of the Google APIs client libraries (for example the one for Python) will take care of that for you automatically, but unfortunately not all of them.

Categories