I want my application to accept OAuth tokens when hosted using Azure Websites. I have the following:
web.config of web app
<appSettings>
<add key="ida:Realm" value="https://example.com/development" />
<add key="ida:AudienceUri" value="https://example.com/development" />
<add key="ida:Tenant" value="example.com" />
</appSettings>
Startup.cs of web app
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security.ActiveDirectory;
using System.Configuration;
[assembly: OwinStartup(typeof(MyApplication.Web.Startup))]
namespace MyApplication.Web
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
{
ValidAudience = ConfigurationManager.AppSettings["ida:AudienceUri"]
},
Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
});
}
}
}
Main.cs
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
void Main()
{
var clientId = #"GUIDGUIDGUID";
var key = #"KEYKEYKEYKEYKEY";
var aadInstance = "https://login.windows.net/{0}";
var tenant = "example.com";
var authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, aadInstance, tenant), true);
var credential = new ClientCredential(clientId, key);
authContext.TokenCache.Clear();
var token = authContext.AcquireToken(#"https://example.com/development", credential);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
var response = client.GetAsync(#"https://app.example.com/").Result;
var responseText = response.Content.ReadAsStreamAsync().Result;
Console.Write(new StreamReader(responseText).ReadToEnd());
}
}
Can anyone provide some guidance?
So it turns out that I was using the Uri class to validate the App ID URI. Problem is, it adds a trailing slash onto to the end, which causes problems. As soon as I started using the string class to store the App ID URI, it was fine.
So make sure you are using exactly the values seen in Azure AD!
Related
I've tried to follow this sample on link to implement MSAL authentication (authorization code flow) to our app running in .NET 4.8 platform:
https://github.com/Azure-Samples/ms-identity-aspnet-webapp-openidconnect/blob/master/WebApp
I implement the MSAL code in the following file of our app
Startup.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using CompanyApp.Infrastructure;
using CompanyApp.App_Start;
using Owin;
using Microsoft.Owin;
using System.Web.Http;
using System.Net.Http.Formatting;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Notifications;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using System.Web;
using Microsoft.Identity.Web;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Owin.Host.SystemWeb;
using CompanyApp.Utils;
namespace CompanyApp
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = AuthenticationConfig.ClientId,
Authority = AuthenticationConfig.Authority,
RedirectUri = AuthenticationConfig.RedirectUri,
PostLogoutRedirectUri = AuthenticationConfig.RedirectUri,
Scope = AuthenticationConfig.BasicSignInScopes + $" User.Read",
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
AuthenticationFailed = OnAuthenticationFailed
}
}
);
RegisterConstants(app);
RegisterAppFilters(AppFilters.Filters);
HttpConfiguration config = new HttpConfiguration() {
};
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
// config.EnsureInitialized();
app.UseWebApi(config);
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
{
// Upon successful sign in, get the access token & cache it using MSAL
IConfidentialClientApplication clientApp = MsalAppBuilder.BuildConfidentialClientApplication();
AuthenticationResult result = await clientApp.AcquireTokenByAuthorizationCode(new[] { "api://<Application ID in azure>/.default" }, context.Code).ExecuteAsync();
}
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
notification.HandleResponse();
notification.Response.Redirect("/Error?message=" + notification.Exception.Message);
return Task.FromResult(0);
}
}
}
HomeController.cs
using Microsoft.Identity.Client;
using Microsoft.Identity.Web;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OpenIdConnect;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using CompanyApp.Utils;
namespace CompanyApp.Controllers
{
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();
var msalAccountId = ClaimsPrincipal.Current.GetMsalAccountId(); // getting null from this line
var account = await app.GetAccountAsync(msalAccountId);
string[] scopes = { "api://<Application ID in azure>/.default" };
try
{
// try to get an already cached token
await app.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false);
}
catch (MsalUiRequiredException ex)
{
throw ex;
}
return View();
}
}
}
I tried to run this in my local
after it successfully authenticated and goes to the controller
I am getting null result from the line where ClaimsPrincipal.Current.GetMsalAccountId() is invoked
Is there something that is missing for ClaimsPrincipal.Current.GetMsalAccountId() to give out null?
In ASP.NET 4.x projects, it was common to use ClaimsPrincipal.Current to retrieve the current authenticated user's identity and claims. In ASP.NET Core, this property is no longer set. Code that was depending on it needs to be updated to get the current authenticated user's identity through a different means.
There are several options for retrieving the current authenticated user's ClaimsPrincipal in ASP.NET Core in place of ClaimsPrincipal.Current:
1)ControllerBase.User. MVC controllers can access the current authenticated user with their User property.
2)HttpContext.User. Components with access to the current HttpContext (middleware, for example) can get the current user's ClaimsPrincipal from HttpContext.User.
3)Passed in from caller. Libraries without access to the current HttpContext are often called from controllers or middleware components and can have the current user's identity passed as an argument.
4)HttpContextAccessor. The project being migrated to ASP.NET Core may be too large to easily pass the current user's identity to all necessary locations. In such cases, IHttpContextAccessor can be used as a workaround. IHttpContextAccessor is able to access the current HttpContext (if one exists). If DI is being used, see Access HttpContext in ASP.NET Core. A short-term solution to getting the current user's identity in code that hasn't yet been updated to work with ASP.NET Core's DI-driven architecture would be:
For more details refer this document
I have a service that has been successfully performing inferences for 2 years, but API stopped working in December. I have created a simple App based on documentation from Microsoft to reproduce the problem. Please see code below.
Is anybody else experience this problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction;
using static System.Net.Mime.MediaTypeNames;
namespace TestCustomVision
{
class Program
{
public static void Main()
{
string imageFilePath = <My Image>;
MakePredictionRequest(imageFilePath).Wait();
Console.WriteLine("\n\nHit ENTER to exit...");
Console.ReadLine();
}
public static async Task MakePredictionRequest(string imageFilePath)
{
var client = new HttpClient();
// Request headers - replace this example key with your valid Prediction-Key.
client.DefaultRequestHeaders.Add("Prediction-Key", <My key>);
// Prediction URL - replace this example URL with your valid Prediction URL.
string url = <Prediction URL>;
HttpResponseMessage response;
// Request body. Try this sample with a locally stored image.
byte[] byteData = GetImageAsByteArray(imageFilePath);
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(url, content);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
private static byte[] GetImageAsByteArray(string imageFilePath)
{
FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}
}
}
I'm trying to create and read (validate) a JSON Web Token (JWT) in an Azure Function using C#. I came across this post:
https://www.codeproject.com/Tips/1208535/Create-And-Consume-JWT-Tokens-in-csharp
which outlines the process very nicely. Being relatively new to Azure Functions, I put the reference to "System.IdentityModel.Tokens.Jwt" in my project.json file like this:
{
"frameworks": {
"net46":{
"dependencies": {
"System.IdentityModel.Tokens.Jwt" : "5.0"
}
}
}
}
The version I used came from this post: Namespaces for .NET JWT token validation: System vs. Microsoft, which talks about versioning issues back in 2016.
Unfortunately, this didn't work. References to SecurityAlgorithms, JwtHeader, JwtPayload, JwtSecurityToken, and JwtSecurityTokenHandler all report, "[run.csx] The type or namespace name 'class name' could not be found (are you missing a using directive or an assembly reference?)".
Researching further, I discovered this page: https://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/, which displays Nuget version information for System.IdentityModel.Tokens.Jwt. After trying several versions (by changing the version in my project.json file), I've still had no luck in getting the Function App to recognize the classes I need.
I assume that this is a versioning issue. If so, where can I go to determine which version of "System.IdentityModel.Tokens.Jwt" is compatible with "net46"? I haven't written C# code in years (I'm a Java developer), so I may be wrong about the versioning assumption.
BTW, here's what the code in my function looks like, it's appears exactly like the code sample in: https://www.codeproject.com/Tips/1208535/Create-And-Consume-JWT-Tokens-in-csharp. The only difference is I've wrapped it in a Function App.
using System.Net;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System.IdentityModel;
using System.Security;
using System.Text;
using System.IdentityModel.Tokens;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
// Define const Key this should be private secret key stored in some safe place
string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
// Create Security key using private key above:
// not that latest version of JWT using Microsoft namespace instead of System
var securityKey = new Microsoft
.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
// Also note that securityKey length should be >256b
// so you have to make sure that your private key has a proper length
//
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
(securityKey, SecurityAlgorithms.HmacSha256Signature);
// Finally create a Token
var header = new JwtHeader(credentials);
//Some PayLoad that contain information about the customer
var payload = new JwtPayload
{
{ "some ", "hello "},
{ "scope", "http://dummy.com/"},
};
//
var secToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
// Token to String so you can use it in your client
var tokenString = handler.WriteToken(secToken);
// And finally when you received token from client
// you can either validate it or try to read
var token = handler.ReadJwtToken(tokenString);
return req.CreateResponse(HttpStatusCode.Created, "test");
}
So, my questions are:
Which version of System.IdentityModel.Tokens should I use with "net46" in my project file?
The next time this happens, how do I determine myself which versions work together?
I just tried this and saw the same thing. You're missing a reference to System.IdentityModel and a using System.IdentityModel.Tokens.Jwt;
Changing to this got things building:
#r "System.IdentityModel"
using System.Net;
using System.IdentityModel;
using System.Security;
using System.Text;
using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
I'd also recommend you move your JWT package reference up to 5.2.4, which is the latest version of that package.
I figured it out. From various sites and hundreds of combinations of versions, it works.
I wish I could explain why, but instead I'll post the working code here with the appropriate libraries listed. If anyone else runs into this problem, I hope it helps. Thanks for looking into this brettsam!
The Function App looks like this:
using System;
using System.Net;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Configuration;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
string token = JwtManager.GenerateToken("rbivens#mydomain.com", 60);
ClaimsPrincipal simplePrinciple = JwtManager.GetPrincipal(token);
var identity = simplePrinciple.Identity as ClaimsIdentity;
log.Info(identity.IsAuthenticated.ToString());
var usernameClaim = identity.FindFirst(ClaimTypes.Name);
var username = usernameClaim ? .Value;
log.Info(username);
return req.CreateResponse(HttpStatusCode.Created, token);
}
public static class JwtManager
{
private static string secret = ConfigurationManager.AppSettings["FunctionsJwtSecret"];
public static string GenerateToken(string username, int expireMinutes = 60)
{
var symmetricKey = Convert.FromBase64String(secret);
var tokenHandler = new JwtSecurityTokenHandler();
var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, username)
}),
Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
};
var stoken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(stoken);
return token;
}
public static ClaimsPrincipal GetPrincipal(string token)
{
try
{
var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;
if (jwtToken == null)
return null;
var symmetricKey = Convert.FromBase64String(secret);
var validationParameters = new TokenValidationParameters()
{
RequireExpirationTime = true,
ValidateIssuer = false,
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
};
SecurityToken securityToken;
var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
// log.Info(securityToken.ToString());
return principal;
}
catch (Exception)
{
return null;
}
}
}
And the project.json looks like this:
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.IdentityModel.Logging" : "1.0.0.127",
"Microsoft.IdentityModel.Tokens" : "5.0.0.127",
"Newtonsoft.Json" : "9.0.0.0",
"System.IdentityModel.Tokens.Jwt" : "5.0.0.127"
}
}
}
}
Again, I don't know why this combination of versions work together, but I hope this saves someone else 20 hours of tedious trial and error.
I followed the article : https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect-aspnetcore-b2c
In this sample app there is a Sign-in button. I am able to Sign-in successfully by clicking Sign-In button by providing my Azure B2C Tenant and registering the application in the tenant.
In another app, I want to authenticate without the Sign-In button being clicked i.e. right when I open the URL, I get redirected first to the Azure B2C AD login page, and after successful validation of credentials, I should be able to see the home screen.
So, what I did was from the URL mentioned from the article, I copied the SiginIn() method as:
public async Task<IActionResult> Index()
{
await SignIn();
await GetDataAsync();
}
I get an error message on running the application as : InvalidOperationException: No authentication handler is configured to handle the scheme: b2c_1_org_b2c_global_signin
Please advise how can I authenticate directly without the signin button. Previously with MVC5, I have successfully done this where I used [Authorize] attribute on the Controller class.
Controller Code with Index method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Hosting;
using WebViewerCore.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Authorization;
namespace WebViewerCore.Controllers
{
[Authorize]
public class DocumentController : Controller
{
#region GlobalVariables
private static readonly string serviceUrl = "";
private string doctype = string.Empty;
private string dmsno = string.Empty;
public string documentName = string.Empty;
private string errMsg = string.Empty;
StringBuilder msg;
Document doc;
private IHostingEnvironment _env;
private IConfiguration _config;
#endregion
#region C'tor
public DocumentController(IHostingEnvironment env, IConfiguration config)
{
_env = env;
_config = config;
}
#endregion
#region ControllerAction
public async Task<IActionResult> Index()
{
//return View();
try
{
//await SignIn();
string storageAccount = _config.GetSection("BlobStorage").GetSection("StorageAccount").Value;
string storageContainer = _config.GetSection("BlobStorage").GetSection("StorageContainer").Value;
ViewBag.StorageAccount = storageAccount;
ViewBag.StorageContainer = storageContainer;
await GetDataAsync();
//HttpContext.Response.ContentType = "application/vnd.ms-xpsdocument";
if (TempData["QueryStringMissing"] != null && (bool)TempData["QueryStringMissing"] || doc == null)
{
return View("View");
}
else
{
return View("Index", doc);
}
}
catch (Exception ex)
{
//logger.LogErrorWithMessage(ex, ex.StackTrace);
//return View("Error", new HandleErrorInfo(ex, "Document", "Index"));
throw ex;
}
}
#endregion
Startup.cs code
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Microsoft.AspNetCore.Http;
using System.IO;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authentication.Cookies;
namespace WebViewerCore
{
public class Startup
{
#region Global Variables
public static string SignUpPolicyId;
public static string SignInPolicyId;
public static string ProfilePolicyId;
public static string ClientId;
public static string RedirectUri;
public static string AadInstance;
public static string Tenant;
#endregion
public Startup(IHostingEnvironment env)
{
//var builder = new ConfigurationBuilder()
// .SetBasePath(env.ContentRootPath)
// .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
// .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
// .AddEnvironmentVariables();
//Configuration = builder.Build();
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.CookieHttpOnly = true;
});
services.AddSingleton<IConfiguration>(Configuration);
// Add Authentication services.
services.AddAuthentication(sharedOptions => sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Document}/{action=Index}/{id?}");
});
// App config settings
ClientId = Configuration["AzureAD:ClientId"];
AadInstance = Configuration["AzureAD:AadInstance"];
Tenant = Configuration["AzureAD:Tenant"];
RedirectUri = Configuration["AzureAD:RedirectUri"];
// B2C policy identifiers
SignUpPolicyId = Configuration["AzureAD:SignUpPolicyId"];
SignInPolicyId = Configuration["AzureAD:SignInPolicyId"];
// Configure the OWIN pipeline to use OpenID Connect auth.
//app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpPolicyId));
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
}
private OpenIdConnectOptions CreateOptionsFromPolicy(string policy)
{
policy = policy.ToLower();
return new OpenIdConnectOptions
{
// For each policy, give OWIN the policy-specific metadata address, and
// set the authentication type to the id of the policy
MetadataAddress = string.Format(AadInstance, Tenant, policy),
AuthenticationScheme = policy,
CallbackPath = new PathString(string.Format("/{0}", policy)),
// These are standard OpenID Connect parameters, with values pulled from config.json
ClientId = ClientId,
PostLogoutRedirectUri = RedirectUri,
Events = new OpenIdConnectEvents
{
OnRemoteFailure = RemoteFailure,
},
ResponseType = OpenIdConnectResponseType.IdToken,
// This piece is optional - it is used for displaying the user's name in the navigation bar.
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
}
};
}
// Used for avoiding yellow-screen-of-death
private Task RemoteFailure(FailureContext context)
{
context.HandleResponse();
if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("access_denied"))
{
context.Response.Redirect("/");
}
else
{
context.Response.Redirect("/Home/Error?message=" + context.Failure.Message);
}
return Task.FromResult(0);
}
}
}
To automatically redirect users navigating to a specific controller or endpoint in MVC, all you need to do is add the [Authorize] attribute, provided you've configured your middleware correctly.
In the case of Azure AD B2C, you need to make sure you add the OpenID Middleware like so:
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
// For each policy, give OWIN the policy-specific metadata address, and
// set the authentication type to the id of the policy
MetadataAddress = string.Format(AadInstance, Tenant, policy),
AuthenticationScheme = policy,
CallbackPath = new PathString(string.Format("/{0}", policy)),
// These are standard OpenID Connect parameters, with values pulled from config.json
ClientId = ClientId,
PostLogoutRedirectUri = RedirectUri,
Events = new OpenIdConnectEvents
{
OnRemoteFailure = RemoteFailure,
},
ResponseType = OpenIdConnectResponseType.IdToken,
// This piece is optional - it is used for displaying the user's name in the navigation bar.
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
},
};);
The sample you referenced already does what you want, to a point.
In that sample, if you haven't signed in and navigate to /about, you'll get automatically redirected to Azure AD B2C to sign in.
As it stands, the sample has the [Authorize] attribute only on a controller action in the Home controller, you'll want to move that up to the controller level and add it to every controller. Then you can just remove the the sign-in/sign-up/sign-out buttons and controller action.
I want to get all uploaded certificate on storage in azure to use these certificate associate with VM when I creating VM's using rest-api to.
Is it necessary, the certificate should available on local machine?
If yes, is there any way to install certificate locally, when the web site/ portal in open on any machine.
You need to install the certificate on each machine that uses REST api to be able to function.
The point of the private and public keys are to maintain security. I dont think this would be something you would want to put on a website for anyone to be able to install.
That being said, if you are making the REST call via a website, then only the server hosting the application needs to have the certificate installed.
I build a webrequest that has the REST URL in it, like this one, then build the response.
private HttpWebResponse CallAzure(HttpWebRequest request, string postData)
{
var certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certificateStore.Open(OpenFlags.ReadOnly);
var certs = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false);
if (request.Method.ToUpper() == "POST")
{
var xDoc = new XmlDocument();
xDoc.LoadXml(postData);
var requestStream = request.GetRequestStream();
var streamWriter = new StreamWriter(requestStream, Encoding.UTF8);
xDoc.Save(streamWriter);
streamWriter.Close();
requestStream.Close();
}
request.ClientCertificates.Add(certs[0]);
request.ContentType = "application/xml";
request.Headers.Add("x-ms-version", "2012-03-01");
ServicePointManager.Expect100Continue = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
request.ServicePoint.Expect100Continue = false;
var response = request.GetResponse();
return (HttpWebResponse)response;
}
I have found it easiest to install the certificate via PowerShell.
If you want to generate your own publishsettingfile here is a very easy app to do it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Security.Cryptography.X509Certificates;
using System.IO;
namespace CreatePublishSettingsFile
{
class Program
{
private static string subscriptionId = "[your subscription id]";
private static string subscriptionName = "My Awesome Subscription";
private static string certificateThumbprint = "[certificate thumbprint. the certificate must have private key]";
private static StoreLocation certificateStoreLocation = StoreLocation.CurrentUser;
private static StoreName certificateStoreName = StoreName.My;
private static string publishFileFormat = #"<?xml version=""1.0"" encoding=""utf-8""?>
<PublishData>
<PublishProfile
PublishMethod=""AzureServiceManagementAPI""
Url=""https://management.core.windows.net/""
ManagementCertificate=""{0}"">
<Subscription
Id=""{1}""
Name=""{2}"" />
</PublishProfile>
</PublishData>";
static void Main(string[] args)
{
X509Store certificateStore = new X509Store(certificateStoreName, certificateStoreLocation);
certificateStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificates = certificateStore.Certificates;
var matchingCertificates = certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
if (matchingCertificates.Count == 0)
{
Console.WriteLine("No matching certificate found. Please ensure that proper values are specified for Certificate Store Name, Location and Thumbprint");
}
else
{
var certificate = matchingCertificates[0];
certificateData = Convert.ToBase64String(certificate.Export(X509ContentType.Pkcs12, string.Empty));
if (string.IsNullOrWhiteSpace(subscriptionName))
{
subscriptionName = subscriptionId;
}
string publishSettingsFileData = string.Format(publishFileFormat, certificateData, subscriptionId, subscriptionName);
string fileName = Path.GetTempPath() + subscriptionId + ".publishsettings";
File.WriteAllBytes(fileName, Encoding.UTF8.GetBytes(publishSettingsFileData));
Console.WriteLine("Publish settings file written successfully at: " + fileName);
}
Console.WriteLine("Press any key to terminate the program.");
Console.ReadLine();
}
}
}