Created
February 14, 2017 18:06
-
-
Save juunas11/ec35b9953c8ee85fc02e9296641e60f6 to your computer and use it in GitHub Desktop.
Calling ASP.NET Web API protected by Azure AD from a console app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Threading.Tasks; | |
using Microsoft.IdentityModel.Clients.ActiveDirectory; | |
namespace ConsoleApplication2 | |
{ | |
class Program | |
{ | |
private const string Authority = "https://login.microsoftonline.com/testazuread.onmicrosoft.com"; | |
private const string Resource = "https://testazuread.onmicrosoft.com/WebApplication3"; | |
private const string ClientId = "11111111-a00b-4131-8233-292e0403c7ba"; | |
private static readonly Uri RedirectUri = new Uri("https://localhost"); | |
//private const string ApiUri = "https://localhost:44303/api/values"; | |
private const string ApiUri = "https://testapiapp.azurewebsites.net/api/values"; | |
static void Main(string[] args) | |
{ | |
RunTestAsync().Wait(); | |
} | |
private static async Task RunTestAsync() | |
{ | |
string accessToken = await GetAccessTokenAsync(); | |
using (var client = new HttpClient()) | |
{ | |
var req = new HttpRequestMessage(HttpMethod.Get, ApiUri); | |
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); | |
req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | |
HttpResponseMessage res = await client.SendAsync(req); | |
string json = await res.Content.ReadAsStringAsync(); | |
Console.WriteLine(json); | |
} | |
} | |
private static async Task<string> GetAccessTokenAsync() | |
{ | |
var authenticationContext = new AuthenticationContext(Authority); | |
var result = | |
await authenticationContext.AcquireTokenAsync(Resource, ClientId, RedirectUri, new PlatformParameters(PromptBehavior.RefreshSession)); | |
string accessToken = result.AccessToken; | |
return accessToken; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Configuration; | |
using System.IdentityModel.Tokens; | |
using Microsoft.Owin.Security.ActiveDirectory; | |
using Owin; | |
namespace WebApplication3 | |
{ | |
public partial class Startup | |
{ | |
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 | |
public void ConfigureAuth(IAppBuilder app) | |
{ | |
app.UseWindowsAzureActiveDirectoryBearerAuthentication( | |
new WindowsAzureActiveDirectoryBearerAuthenticationOptions | |
{ | |
Tenant = ConfigurationManager.AppSettings["ida:Tenant"], | |
TokenValidationParameters = new TokenValidationParameters { | |
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"] | |
}, | |
}); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Owin; | |
namespace WebApplication3 | |
{ | |
public partial class Startup | |
{ | |
public void Configuration(IAppBuilder app) | |
{ | |
ConfigureAuth(app); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Web.Http; | |
namespace WebApplication3.Controllers | |
{ | |
[Authorize] | |
public class ValuesController : ApiController | |
{ | |
// GET api/values | |
public IEnumerable<string> Get() | |
{ | |
return new [] { User.Identity.Name }; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<!-- | |
For more information on how to configure your ASP.NET application, please visit | |
http://go.microsoft.com/fwlink/?LinkId=301879 | |
--> | |
<configuration> | |
<appSettings> | |
<add key="webpages:Version" value="3.0.0.0" /> | |
<add key="webpages:Enabled" value="false" /> | |
<add key="ClientValidationEnabled" value="true" /> | |
<add key="UnobtrusiveJavaScriptEnabled" value="true" /> | |
<add key="ida:Tenant" value="testazuread.onmicrosoft.com" /> | |
<add key="ida:Audience" value="https://testazuread.onmicrosoft.com/WebApplication3" /> | |
<add key="ida:ClientID" value="1111111-2a48-4ed3-a5e8-9fa9f72daa79" /> | |
</appSettings> | |
<system.web> | |
<compilation debug="true" targetFramework="4.5.2" /> | |
<httpRuntime targetFramework="4.5.2" /> | |
</system.web> | |
<system.webServer> | |
<handlers> | |
<remove name="ExtensionlessUrlHandler-Integrated-4.0" /> | |
<remove name="OPTIONSVerbHandler" /> | |
<remove name="TRACEVerbHandler" /> | |
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> | |
</handlers> | |
</system.webServer> | |
<runtime> | |
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> | |
<dependentAssembly> | |
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /> | |
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> | |
</dependentAssembly> | |
<dependentAssembly> | |
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /> | |
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /> | |
</dependentAssembly> | |
<dependentAssembly> | |
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> | |
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> | |
</dependentAssembly> | |
<dependentAssembly> | |
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> | |
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> | |
</dependentAssembly> | |
<dependentAssembly> | |
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> | |
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> | |
</dependentAssembly> | |
<dependentAssembly> | |
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> | |
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> | |
</dependentAssembly> | |
</assemblyBinding> | |
</runtime> | |
<system.codedom> | |
<compilers> | |
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" /> | |
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" /> | |
</compilers> | |
</system.codedom> | |
</configuration> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment