Execute RestAPI Azure DevOps Services - Authentication with username & Password no PAT - authentication

Can i Use User/Password combination to run RestAPI to Azure DevOps Services?
Short answer NO. - see explanation at marked answer
I tried to find a way to get RestAPI working without PAT or Create a Token from Current Login Info and failed
The following Code Return 401:
using System.Net;
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("user:password");
string patEncoded = Convert.ToBase64String(bytes);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://dev.azure.com/<ORG>/_apis/wit/workitems/22289?api-version=6.0");
httpWebRequest.Headers.Add("Authorization", "Basic " + patEncoded);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Any Advice is much appreciated
I do not want to create an app and register it on the tenant .

Authenticate your web app users for REST API access, so your app doesn't continue to ask for usernames and passwords. Azure DevOps Services uses the OAuth 2.0 protocol to authorize your app for a user and generate an access token. Use this token when you call the REST APIs from your application.
For the Authentication mechanism, REST API is using the mention-aboved authentication mechanism to be authentication.
userName & password: Azure DevOps no longer supports Alternate Credentials authentication since the beginning of March 2, 2020. Here is the document.

Related

Authenticate an EWS WCF service by using OAuth and refresh access token

I am trying to call Exchange web services (EWS) end points from my WCF service using OAuth authentication.
I have registered the app on Azure portal and able to generate and authenticate it using access token.
My question is about how I can refresh the token in WCF service. It seems access token has an hour validity.
// Using Microsoft.Identity.Client 4.22.0
var cca = ConfidentialClientApplicationBuilder
.Create(ConfigurationManager.AppSettings["appId"])
.WithClientSecret(ConfigurationManager.AppSettings["clientSecret"])
.WithTenantId(ConfigurationManager.AppSettings["tenantId"])
.Build();
// The permission scope required for EWS access
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
//Make the token request
var authResult = await cca.AcquireTokenForClient(ewsScopes).ExecuteAsync();
Followed below link for this.
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth
Thanks
In your WCF client you want to do something like How to add a custom HTTP header to every WCF call? so you have a piece of code that runs before any request is made that calls AcquireTokenForClient which should use the Token Application Cache (so it will either give you the current token if valid or acquire a new token if expired).

Get user info and other claims in Azure Function with Identity server

I am having an application where Authentication is done using IdentityServer4 with Azure AD as an OpenID provider. IdentityServer4 is hosted in Azure App service. After successful authentication, I am able to get access token in Angular application. Access token is passed to .Net Core based RESTful API which is hosted in Azure Function 3.x.
In my Azure function I would like to get user info and other claims without hitting the end point "/connect/userinfo" of IdentityServer4.
Something similar to following for getting Claims would be helpful
[FunctionName("MyFunctionName")]
public static HttpResponseMessage Run(
[HttpTrigger(
AuthorizationLevel.Anonymous,
"get", "post",
Route = "MyFunctionName")]HttpRequestMessage req,
ILogger log,
ClaimsPrincipal claimsPrincipal)
{
// My function code here...
}
How do I get I user info and other claims in Azure function where Authentication is done by IdentityServer4 with Azure AD as OpenID provider
If you have a valid access token, then you can make a request on your own to the UserInfo endpoint to retrieve the remaining user details.
Read more about it here
The only option if you don't want to access the userinfo endpoint is to include the required data in the tokens directly. Here you need to do a trade-of between token size vs convenience. Then you get a really stateless system.
If you don't want to hit user info end point of Identity Server to get the user info and other claims, here is what needs to be done.
Add the claim info to the authorization token
Parse the authorization token and extract the user info and other claim information.
The downside of this approach is that the token size is increased but advantage is that you don't need hit userinfo end point which saves your http request(s). So there are trade offs between each approach.
Here is how you can add claims info while configuring your api in Identity Server. Typically this information resides in Config.cs if you have used Identity Server template
public static IEnumerable<ApiResource> GetApis()
{
var apiResourceList = new List<ApiResource>
{
new ApiResource(IdentityServerConstants.LocalApi.ScopeName)
{
UserClaims =
{
JwtClaimTypes.Email,
JwtClaimTypes.PhoneNumber,
JwtClaimTypes.GivenName,
JwtClaimTypes.FamilyName,
JwtClaimTypes.PreferredUserName
},
}
};
return apiResourceList;
}
For parsing and validating the token please follow the blog Manual token validation in Azure Function
This StackOverflow thread is also very useful.

Reuse Access Token Throughout ASP.NET Core App (via DI)

I have a ASP.NET Core app that I'm using OIDC (Microsoft Azure AD) to authenticate users to my app. I have added a ton of APIs to the Registered Application in Azure AD including Dynamics. How can I access the access token in my middleware? I created a class for the sole purpose of communicating with Dynamics and would like to reuse the access token generated during authentication to my app. How and where do I get it from? I have tried all the usual suspects such as the following:
var accessToken = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Authorization].ToString(); // null
and
var accessToken = _httpContextAccessor.HttpContext.GetTokenAsync("access_token").Result; // null
Any suggestions?
To get access token for calling Dynamics API with the authenticated user context, application should get access token using OBO flow. MSAL.NET has method to do so.
string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
You can refer this ASP.NET Core Sample and has the similar scenario that you are trying to achive.

Auth0 and ADAL.NET

I am trying to get an access token from my Auth0 setup, I am using ADAL. I don't understand why it's trying to connect to the following site when I look at fiddler:
https://login.windows.net/common/discovery/instance?api-version=1.0&authorization_endpoint=https://myusername.auth0.com/oauth/oauth2/authorize
Here is my code:
var AuthCtx = new AuthenticationContext("https://MYUSERNAME.auth0.com/oauth/token");
var token = AuthCtx.AcquireTokenAsync("https://api.MYSITE.COM", new ClientCredential("clientid here", "secret here"));
Console.WriteLine(token.Result.AccessToken);
Thank you!
ADAL is a Microsoft library that is developed to connect native devices (non-browser) e.g. desktop & mobile to either Azure AD or ADFS.
You can use it for other Identity providers but it is not supported as a generic OAuth stack.
All the samples either use Azure AD or ADFS.
The endpoint above is the common endpoint for Azure AD.

How to authenticate from automated tests against WebAPI with Owin security?

I have a .net web api app with owin security. The security middleware is configured with Google authentication (no local username/password authentication) and Oauth bearer token.
In startup:
public void ConfigureAuth(IAppBuilder app)
{
...
app.UseOAuthBearerTokens(new OAuthAuthnorizationServerOptions {
TokenEndpointPath = new PathString("/token"),
AuthorizeEndpointPath = new PathString("/account/authorize"),
Provider = new ApplicationOAuthProvider("web"),
...
});
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions {
ClientID = "...",
ClientSecret = "..."
});
}
From my client applications I go to
http://myapp.com/account/authorize?client_id=web&response_type=token&redirect_uri=...
This redirects to a google login that the user fills in, then back to my app with a bearer token that I peel off and add to request headers for my api.
I would like to write some integration tests where my tests call the API. The tests have the google credentials of a test user, but I am not sure how to have the test authenticate without bringing up a browser and a google login screen. I could drive that with Selenium but that seems heavy-handed.
How do I programmatically get a bearer token to use with my API such that I can impersonate my test user?
Normally you would use the OAuth2 resource owner password credentials grant in this case, but Google does not seem to support that.
So your best option seems to be to use the authorization code grant to authenticate the test user, extract the refresh token from the token endpoint response. Then use the refresh token and client ID and secret to get an access token from your integration test.
See this for more information:
https://developers.google.com/identity/protocols/OAuth2InstalledApp