I used Youtube Data Api(v3) to get data from a Youtube Account.
I used this link https://console.developers.google.com/ to create ClientId and ClientSecret for a web application.
Everything works fine when I run my project in local. When I tried to host the project in server it gives a exception which says
Access to the path ASP.****.aspx page is denied
When I debugged the solution, I noticed that this part of code causes the exception:
UserCredential credential;
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync (
new ClientSecrets
{
ClientId = ClientId,
ClientSecret = ClientSecret
},
new[] { YouTubeService.Scope.YoutubeReadonly },
"user",
CancellationToken.None,
new FileDataStore(GetType().ToString())
);
Some methods inside google youtube api require OAUTH2 authentication (get refresh token from client secret ->get access token from refresh token...),upload videos for example, but some like getvideos do not require. You can provided API key to your youtubeService conctructor instead of UserCredential
Related
I previously worked on an OAuth2 application where the logic was to generate a new access token via refresh token once the old one expired.
Now working with Google APIs, I'm not experiencing the same thing. I have received both an access token and refresh token, and after allowing the access token to expire, I attempt to use the refresh token
var myToken = new TokenResponse
{
RefreshToken = sRefreshToken
};
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
}
}), "user", myToken);
service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "XYZ",
});
It seems after doing so I can make API calls. But I have tried to retrieve the access/refresh tokens after doing this with:
ACCESS_TOKEN = credentials.Token.AccessToken;
REFRESH_TOKEN = credentials.Token.RefreshToken;
And both the access and refresh tokens are the same as the old ones. I had thought refreshing would generate a new token altogether? Is this not the case?
If the access token expires after 30 minutes and you then just need to pass in the refresh token (but nothing re-generates), what is the point of the refresh token?
I previously worked on an OAuth2 application where the logic was to generate a new access token via refresh token once the old one expired.
This idea also applies to Google access/refresh tokens. But if you're using the .NET client library (as your code snippet suggests), you don't have to perform the refreshes yourself. You can just continue using the UserCredential object and it'll automatically fetch a new access token every ~1h.
I have a .NET Web API and a small vanilla-JS app using ADAL.js, and I've managed to make them talk nicely to each-other and authenticate correctly.
If I console.log the token returned from adalAuthContext.acquireToken() and manually enter it as Authorization: Bearer {{token}} in Postman, I can also get a valid, authenticated, response from my backend.
However, I can't figure out how to configure Postman's built-in OAuth2.0 authentication UI to get me tokens automatically. I have managed to get tokens in several ways, but none of them are accepted by the backend.
How do I configure Postman to get a token the same way the ADAL.js library does?
For completeness, here's some code:
Backend configuration:
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters { ValidAudience = "<app-id>" },
Tenant = "<tenant>",
AuthenticationType = "WebAPI"
});
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
}
ADAL.js configuration:
const backendUrl = 'http://localhost:55476';
const backendAppId = '<app-id>';
const authContext = new AuthenticationContext({
clientId: backendAppId,
tenant: '<tenant>',
endpoints: [{ [backendAppId]: backendAppId }],
cacheLocation: 'localStorage'
});
Actually making a request:
authContext.acquireToken(backendAppId, (error, token) => {
// error handling etc omitted
fetch(backendUrl, { headers: { Authorization: `Bearer ${token}` } })
.then(response => response.json())
.then(console.log)
})
So since the Azure AD v1 endpoint is not fully standards-compliant, we have to do things in a slightly weird way.
In Postman:
Select OAuth 2.0 under Authorization
Click Get new access token
Select Implicit for Grant Type
Enter your app's reply URL as the Callback URL
Enter an authorization URL similar to this: https://login.microsoftonline.com/yourtenant.onmicrosoft.com/oauth2/authorize?resource=https%3A%2F%2Fgraph.microsoft.com
Enter your app's application id/client id as the Client Id
Leave the Scope and State empty
Click Request token
If you configured it correctly, you'll get a token and Postman will configure the authorization header for you.
Now about that authorization URL.
Make sure you specify either your AAD tenant id or a verified domain name instead of yourtenant.onmicrosoft.com.
Or you can use common if your app is multi-tenant.
The resource is the most important parameter (and non-standards-compliant).
It tells AAD what API you want an access token for.
In this case I requested a token for MS Graph API, which has a resource URI of https://graph.microsoft.com.
For your own APIs, you can use either their client id or App ID URI.
Here is a screenshot of my settings:
SUMMARY UPDATE:
I got a sample working today thanks to the many good replies. Thanks all. My primary goal was to get current user information (ME) without using secret key. First I just used the secret key from the App Reg and this will authenticate the App and not the user. This does of course not work when calling ME. My next finding was if you want the users token, you still need the App Reg token, and then you request the users token. This requires less permissions on the App Reg, but requires to request two tokens. I ended up skipping ME and just requesting information for a specified user (through the APp Reg permissions):
$"https://graph.microsoft.com/v1.0/users/{email}/$select=companyName"
Both both approaches should be viable. I updated code below with working sample.
I am trying to do a very simple call to graph API to get companyName from current user. Found some samples but they seemed to be very complicated. The MVC app is authenticated trough an Application Registration in AAD.
I guess the application registration needs to be authorized to access Graph API. Or is more needed here? Getting company name should be fairly simple:
https://graph.microsoft.com/v1.0/me?$select=companyName
Does anyone have a snippet for calling the graph API, my best bet would be you need to extract a bearer token from the controller? ALl help is appreciated.
Working snippet:
public async Task<ActionResult> Index()
{
string clientId = "xxx";
string clientSecret = "xxx";
var email = User.Identity.Name;
AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/xxx.onmicrosoft.com/oauth2/token");
ClientCredential creds = new ClientCredential(clientId, clientSecret);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);
HttpClient http = new HttpClient();
string url = $"https://graph.microsoft.com/v1.0/users/{email}/$select=companyName";
//url = "https://graph.windows.net/xxx.onmicrosoft.com/users?api-version=1.6";
// Append the access token for the Graph API to the Authorization header of the request by using the Bearer scheme.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
HttpResponseMessage response = await http.SendAsync(request);
var json = response.Content.ReadAsStringAsync();
return View();
}
To add one last item, here is a link to an MVC sample on Git that uses an MVC application to send email. It illustrates how to call the MS Graph API to get various pieces of information. Keep in mind, if you are using an application only scenario, ME will not work, the sample illustrates how to obtain a delegated token for a user and use that toke to do work:
https://github.com/microsoftgraph/aspnet-connect-rest-sample
If I am reading this code snippet correctly, You are requesting a application only token for the Graph.Microsoft.Com resource, then attempting to use that toke with this URI:
url = "https://graph.windows.net/thomaseg.onmicrosoft.com/users?api-version=1.6"
This will not work because you are mixing resources, AAD Graph and MS Graph. The ME endpoint does not make since in this scenario because you are using the application only flow. This flow does not support the ME endpoint. ME is designed for use with a delegated token. the ME endpoint represents the signed in user, since and application is not a user, ME is meaningless.
You will need to target the user specifically:
https://graph.microsoft.com/v1.0/Users/[UPN or ID of user]?$select=companyName
Should work if your application has been granted the appropriate permission scopes.
I have a Angular 4 site that I’m trying to use Microsoft Graph implicit flow to authenticate users then use token to call our APIs at another endpoint, so I use msal.js to get the access token.
After I bring the access token to my API endpoint and try to valid it, the token cannot be valid. I got a SignatureVerificationFailedException.
My understanding is that the access token is for Microsoft Graph API, not for my APIs, so I cannot valid it. (I can use it to call Graph API without problem)
How can I get a access token(not id token) using msal.js that can be used for my APIs but not Microsoft Graph? Thanks!
The reason I'm sending access token instead of id token to the API endpoint is that I want to get the puid claim from the token, which is not available for id token.
Here is what I was trying to valid the access token I got from client which is using msal.js
const string authority = "https://login.microsoftonline.com/common";
const string audience = "https://graph.microsoft.com";
string issuer = null;
string stsDiscoveryEndpoint = $"{authority}/v2.0/.well-known/openid-configuration";
List<SecurityToken> signingTokens = null;
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint);
var config = await configManager.GetConfigurationAsync();
issuer = config.Issuer;
signingTokens = config.SigningTokens.ToList();
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
ValidAudience = audience,
ValidIssuer = issuer,
ValidateIssuer = false,
IssuerSigningTokens = signingTokens,
CertificateValidator = X509CertificateValidator.None
};
try
{
// Validate token.
SecurityToken validatedToken = new JwtSecurityToken();
var claimsPrincipal = tokenHandler.ValidateToken(jwtToken, validationParameters, out validatedToken);
var claimsIdentity = claimsPrincipal.Identity as ClaimsIdentity;
return ExtractAuthenticatedUserFromClaimsIdentity(claimsIdentity);
}
catch (SignatureVerificationFailedException)
{
throw;
}
Thanks,
If you want to get an access token for your API rather than the Microsoft Graph API, you must specify your API as the resource in the token request.
Make sure that:
Your Web API has configured OAuth2Permission Scopes. See here. Configuring a resource application to expose web APIs
Your Client Application has selected permissions to those exposed APIs. Configuring a client application to access web APIs
Finally, make sure you use your Web API's App ID URI or App ID GUID as the resource value in your token request.
Let me know if this helps!
I am trying to access GoogleDrive API (my own a/c) using the refresh token --issued from OAuth Playground -- like below. I am using my refresh token and access token for offline access but I am getting a 401 unauthorized. My code is based on reference belwoand google-api javadocs recommendation for building an offline request
I do not wish to use a browser, i wish to run this from a server side app to upload to my own a/c.
ref: http://stackoverflow.com/questions/10533203/fetching-access-token-from-refresh-token-using-java
Code:
public static void main(String[] args) throws IOException {
HttpTransport TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();
String refreshTokenString="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; //from console
String accessTokenString ="yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; //from console
GoogleCredential credential = createCredentialWithRefreshToken(
TRANSPORT, JSON_FACTORY, new TokenResponse().setRefreshToken(refreshTokenString));
credential.setAccessToken("accessTokenString");
//exeucute HTTP request for offline accessTokenString
// Execute HTTP GET request to revoke current token.
HttpResponse response = TRANSPORT.createRequestFactory()
.buildGetRequest(new GenericUrl(
String.format(
"https://www.googleapis.com/drive/v2/changes",
credential.getAccessToken()))).execute();
System.out.println("RESPONSE: " +response);
}
public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport,
JsonFactory jsonFactory, TokenResponse tokenResponse) {
HttpTransport TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();
return new GoogleCredential.Builder().setTransport(transport)
.setJsonFactory(JSON_FACTORY)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build()
.setFromTokenResponse(tokenResponse);
}
And the error:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
I am using a valid refresh token and access token (works from playground console) but i get login required 401 here when running from Java app. I requires this for daily backups from server directly to Drive.
You can't use the access or refresh token from the Playgorund in your application. These tokens where issued by google only to be used in the playground. The tokens you get are tied to a Client Id and Client Secret. Obviously your CLIENT_ID and CLIENT_SECRET are different from the ones which are used by the Google Playground application.
You really need your application to request these tokens, so for the first time you need a browser, so that the user can accept that YOUR app (not Google Playground) is getting your information stored at google. This is called "user consent", and shown in the little diagram at this page: Using OAuth 2.0 for Web Server Applications)
Then, when you have the refresh token for your application. You don't need the browser any more for your daily backups.
You can use your code with a valid refresh token for your app, as presented in your post.
Can I access using the refresh token only as this does not expire?
No. You must convert the refresh token to an access token.