Unable to find DiscoveryClient for IdentityServer4 - asp.net-mvc

Trying to access discovery client for acceising other endpoints anf following with,
http://docs.identityserver.io/en/aspnetcore1/endpoints/discovery.html
Installed IdentityModel nuget package in .Net 7.5 MVC application. But unable to find the DiscoveryClient.
var discoveryClient = new DiscoveryClient("https://demo.identityserver.io");
var doc = await discoveryClient.GetAsync();
Is there something change in Identitymodel for IdentityServer4
Also, unable to find parameter for "Tokenclient".

Able to figure out, change in IdentityModel, its all extension of HttpClient.
https://identitymodel.readthedocs.io/en/latest/client/discovery.html
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://demo.identityserver.io");

Yes, you are correct. There are lot of changes in the IdentityModel NuGet package.
Below code will help you:
HttpClient httpClient = new HttpClient();
//Below code will give you discovery document response previously we were creating using DiscoveryClient()
// They have created `.GetDiscoveryDocumentAsync()` extension method to get discovery document.
DiscoveryDocumentResponse discoveryDocument = await httpClient.GetDiscoveryDocumentAsync();
// To create a token you can use one of the following methods, which totally depends upon which grant type you are using for token generation.
Task<TokenResponse> RequestAuthorizationCodeTokenAsync(AuthorizationCodeTokenRequest)
Task<TokenResponse> RequestClientCredentialsTokenAsync(ClientCredentialsTokenRequest)
Task<TokenResponse> RequestDeviceTokenAsync(DeviceTokenRequest)
Task<TokenResponse> RequestPasswordTokenAsync(PasswordTokenRequest)
Task<TokenResponse> RequestRefreshTokenAsync(RefreshTokenRequest)
Task<TokenResponse> RequestTokenAsync(TokenRequest)
For example if you want to create a token for password grant type then use below code:
PasswordTokenRequest passwordTokenRequest = new PasswordTokenRequest()
{
Address = discoveryDocument.TokenEndpoint,
ClientId = ClientName,
ClientSecret = ClientSecret,
GrantType = GrantTypes.ResourceOwnerPassword,
Scope = scope,
UserName = userName,
Password = password
};
httpClient.RequestPasswordTokenAsync(passwordTokenRequest);
I hope this will help you!

If you used some sample code and the other answers aren't working, because HttpClient doesn't have GetDiscoveryDocumentAsync
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001");
Update your IdentityModel package, in Visual Studio:
Right click Dependencies -> Manage Nuget Packages -> Updates (select "All" in top right corner)

Related

Can not login Jira with Api

I have this code below, i need to login but Jira documantation so bad that i cant figured out, how can i login to jira ? They say basic auth is depreced but all examples are like this. How can i login ?
var apiUrl = #"https://MYDOMAIN.atlassian.net/rest/api/3/issue/MYPROJECTNAME";
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), apiUrl))
{
request.Headers.TryAddWithoutValidation("Accept", "application/json");
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("xxxxx#gmail.com:1xxxxxk2qdnqHJxxxx155"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
var response = await httpClient.SendAsync(request);
}
}
You are right, documentation too weak.
In my use cases, I preferred using "username" only. Not email. Can you try this?
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("<YOUR_USERNAME>:1xzyNAGgksdfgP3155"));
This is Jira documentation:
The username and password of a user who has permission to create issues on your Jira Server site
Build a string of the form username:password.
If this recommendation fails can you share your rest logs?

How I can call an api from MVC .net 4.7.2 using Microsoft Identity Planform (Azure AD

I am following a tutorial from microsoft docs and I have created an api with Microsoft Identity Platform using Azure AD in asp.net core 5.
The tutorialI followed shows how to call an api from asp.net core 5, and I have done that part but now I want to call the api from asp.net 4.7.2. Since I am new to apis and example I am finding are not using Microsoft Identity platform to call an api secured by microsoft identity
Can someone point me to document, tutorial, or code which shows me how I can call the api. Code should be written in asp.net not core.
I have done some part but stuck on calling the api.
See the below code
Api methods:
I have already setup the api and web app in Azure portal and configured permission to 2 of the scope.
Method in api.
GetCategory()
GetCatalog()
private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification
notification)
{
notification.HandleCodeRedemption();
var idClient = ConfidentialClientApplicationBuilder.Create(clientId)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret)
.WithAuthority(authority)
.Build();
var signedInUser = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
try
{
var apiScope = "catalog.Read, Category.Read";
string[] scopes = apiScope.Split(' ');
var result = await idClient.AcquireTokenByAuthorizationCode(
scopes, notification.Code).ExecuteAsync();
//rest of the code to call the api for both scope
// and if i have to do add some code to controller
Not sure if you are still looking for an answer but here it goes.
Once you get the accessToken with required scope, you just need to add it as Authorization Header when you make a call to the API:
const string Scheme = "Bearer";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);
httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue(Scheme, result.AccessToken);
var result = await httpClient.SendAsync(httpRequestMessage)

Is it possible to run Twilio Video only on IIS and written on C#?

In the all samples I see usage of Twilio VIdeo only on node.js as a web server.
Is it possible to run it on IIS and the both, server and client part written on C#?
Twilio evangelist here.
This page has code for generating Access Tokens in C#:
using System;
using Twilio.Jwt.AccessToken;
class Example
{
static void Main(string[] args)
{
// Substitute your Twilio AccountSid and ApiKey details
var AccountSid = "accountSid";
var ApiKeySid = "apiKeySid;
var ApiKeySecret = "apiKeySecret";
var identity = "example-user";
// Create a video grant for the token
var grant = new VideoGrant();
grant.Room = "cool room";
var grants = new HashSet { grant };
// Create an Access Token generator
var token = new Token(accountSid, apiKey, apiSecret, identity: identity, grants: grants);
// Serialize the token as a JWT
Console.WriteLine(token.ToJwt());
}
}
There is also a Github repo with a full token server sample in C#.
Hope that helps.

MVC5 app using Azure Active Directory + REST API -- to auth for PowerBI / O365

I'm trying to adapt the WebAPI example shown here, to use in MVC5:
https://msdn.microsoft.com/en-US/library/dn931282.aspx#Configure
I have a regular AccountController based login system, but I also need the user to login via OAuth into PowerBI, so I can pull datasets via the PowerBI REST API. However, I'm gettting the ClaimsPrincipal.Current.FindFirst(..) to be null.
private static async Task<string> getAccessToken()
{
// Create auth context (note: token is not cached)
AuthenticationContext authContext = new AuthenticationContext(Settings.AzureADAuthority);
// Create client credential
var clientCredential = new ClientCredential(Settings.ClientId, Settings.Key);
// Get user object id
var userObjectId = ClaimsPrincipal.Current.FindFirst(Settings.ClaimTypeObjectIdentifier).Value;
// Get access token for Power BI
// Call Power BI APIs from Web API on behalf of a user
return authContext.AcquireToken(Settings.PowerBIResourceId, clientCredential, new UserAssertion(userObjectId, UserIdentifierType.UniqueId.ToString())).AccessToken;
}
It all works fine in the sample app (a WebAPI project). I've also configured the OWIN app.UseOpenIdConnectAuthentication stuff in Startup.Auth.cs.
It seems the issue is the only type of Claim I have in 'ClaimsPrincipal.Current' is a 'CookieAuthentication' - it is missing the http://schemas.microsoft.com/identity/claims/objectidentifier Claim.
Also...the Microsoft OAuth window never opens in the browser...however, the error is within the ActiveDirectory related code...that code shouldn't need an OAuth token in the first place, right?
The recommended way to do this is to use the code that the Open ID Connect middleware will automatically retrieve for you. There is relevant sample here:
https://github.com/AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet
This sample uses OAuth to get a token for the AAD Graph API. I don't know PowerBI but I believe that this is exactly analogous to getting a token for PowerBI.
Pay attention in particular to this file:
https://github.com/AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet/blob/master/TodoListWebApp/App_Start/Startup.Auth.cs
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
return Task.FromResult(0);
},
The code above is called on every successful authentication, and ADAL is used to retrieve a token to the Graph API. At this point the only reason to get a token for the Graph API is to exchange the short lived auth code for a longer lived refresh token and get that stored in the cache. That is why the 'result' is never used.
Later, in the following file, the cache is employed to retrieve the token and use it to access the graph:
https://github.com/AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet/blob/master/TodoListWebApp/Controllers/UserProfileController.cs
string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
ClientCredential credential = new ClientCredential(clientId, appKey);
result = authContext.AcquireTokenSilent(graphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
This time the token is actually used.
Substitute PowerBI for Graph API in the sample and I think you should be good to go.
Note that one other thing to pay attention to is the cache implementation. This file contains an appropriately name NaiveSessionCache.
https://github.com/AzureADSamples/WebApp-WebAPI-OpenIDConnect-DotNet/blob/master/TodoListWebApp/Utils/NaiveSessionCache.cs
If you have multiple front ends you will need to implement your own, less naive, session cache so that all the front ends can share the same cache.
A potential workaround, at least for me, is to use the "native app" setup on Azure AD and follow this workflow, instead of the web app + oauth workflow:
https://msdn.microsoft.com/en-US/library/dn877545.aspx

How do I work with Google Analytics oAuth in a WebAPI?

I am building an extension for open source ASP.NET CMS Umbraco where I want to fetch the analytic's from the user's account once they have authorised via oAuth.
The example MVC 4 snippet over on the Google API .NET wikiw page for oAuth seems to only work with a controller and not a WebAPI controller as far as I can tell, is this right?
AuthorizationCodeMvcApp(this, new AppFlowMetaData()).AuthorizeAsync(cancellationToken);
The first parameter in the example expects it to be a regular MVC Controller
https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis.Auth.Mvc4/OAuth2/Mvc/AuthorizationCodeMvcApp.cs
So my question is really, how do I work with oAuth with a WebAPI in mind, as I want to return stats back from the API as JSON from the WebAPI so I can use a client side library such as AngularJS to bind the JSON returned to the HTML view?
I would love for any ideas, feedback or suggestions on how I could solve this please.
Thanks,
Warren :)
I have looked into your problem and the i have tested the service account solution. It's tricky to setup but when it runs it works.
This is the code I used in a webapi controller :
String serviceAccountEmail = "805395301940-cu3nhkuqi4ipa3453o276bar5u2e70lq#developer.gserviceaccount.com";
var cert = HttpContext.Current.Server.MapPath("/key.p12");
var certificate = new X509Certificate2(cert, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
//var ga = service.Data.Ga.Get("ga:31335471", "2013-01-01", "2013-01-31", "ga:visits");
// Not Working Currently in Beta
//var ga = service.Data.Realtime.Get("ga:31335471", "ga:activeVisitors");
var ga = service.Management.Profiles.List("~all", "~all");
return ga.Execute();

Resources