public void ConfigureAuth(IAppBuilder app) { TokenValidationParameters tvps = new TokenValidationParameters { // Accept only those tokens where the audience of the token is equal to the client ID of this app ValidAudience = ClientId, AuthenticationType = DefaultPolicy }; app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { // This SecurityTokenProvider fetches the Azure AD B2C metadata & signing keys from the OpenIDConnect metadata endpoint AccessTokenFormat = new JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider(string.Format(AadInstance, Tenant, DefaultPolicy))) }); }
public void Configure(IAppBuilder app) { var httpConfig = new HttpConfiguration(); // Build the container ContainerConfig.Register(httpConfig); // Configure API WebApiConfig.Register(httpConfig); // configure FluentValidation model validator provider FluentValidationModelValidatorProvider.Configure(httpConfig); // 1. Use the autofac scope for owin app.UseAutofacLifetimeScopeInjector(ContainerConfig.Container); // 2. Allow cors requests app.UseCors(CorsOptions.AllowAll); // 3. Use the readable response middleware app.Use <RewindResponseMiddleware>(); // 4. Register the activty auditing here so that anonymous activity is captured app.UseMiddlewareFromContainer <ActivityAuditMiddleware>(); // Allow Web API to consume bearer JWT tokens. var rsaProvider = ContainerConfig.Container.Resolve <IRsaKeyContainerService>(); var tokenParam = new System.IdentityModel.Tokens.TokenValidationParameters { ValidIssuer = ConfigurationManager.AppSettings["oAuth:Issuer"], ValidAudience = ConfigurationManager.AppSettings["oAuth:Audience"], IssuerSigningKey = new System.IdentityModel.Tokens.RsaSecurityKey(rsaProvider.GetRsaCryptoServiceProviderFromKeyContainer()) }; var jwtTokenOptions = new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, TokenValidationParameters = tokenParam, Provider = new QueryStringOAuthBearerProvider() }; app.UseJwtBearerAuthentication(jwtTokenOptions); // 6. Add SignalR support. app.MapSignalR(ContainerConfig.HubConfiguration); // 7. Add web api to pipeline app.UseWebApi(httpConfig); }
public void ConfigureAuth(IAppBuilder app) { var tvps = new System.IdentityModel.Tokens.TokenValidationParameters { // The web app and the service are sharing the same clientId ValidAudience = ConfigurationManager.AppSettings["ida:Audience"], ValidateIssuer = false, }; // NOTE: The usual WindowsAzureActiveDirectoryBearerAuthenticaitonMiddleware uses a // metadata endpoint which is not supported by the v2.0 endpoint. Instead, this // OpenIdConenctCachingSecurityTokenProvider can be used to fetch & use the OpenIdConnect // metadata document. app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { AccessTokenFormat = new Microsoft.Owin.Security.Jwt.JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")), }); }
public static void ValidateToken(string tokenString, string secret) { var securityKey = new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(Encoding.Default.GetBytes(secret)); var jwt = new System.IdentityModel.Tokens.JwtSecurityToken(tokenString); var tokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters() { ValidAudiences = new string[] { audience }, ValidIssuers = new string[] { issuer }, IssuerSigningKey = securityKey }; System.IdentityModel.Tokens.SecurityToken validatedToken; var handler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler(); handler.ValidateToken(tokenString, tokenValidationParameters, out validatedToken); }
/// <inheritdoc /> public async Task <ActionableMessageTokenValidationResult> ValidateTokenAsync( string token, string targetServiceBaseUrl) { if (string.IsNullOrEmpty(token)) { throw new ArgumentException("token is null or empty.", "token"); } if (string.IsNullOrEmpty(targetServiceBaseUrl)) { throw new ArgumentException("url is null or empty.", "targetServiceBaseUrl"); } CancellationToken cancellationToken; OpenIdConnectConfiguration o365OpenIdConfig = await OpenIdConnectConfigurationRetriever.GetAsync(O365OpenIdConfiguration.MetadataUrl, cancellationToken); ClaimsPrincipal claimsPrincipal; ActionableMessageTokenValidationResult result = new ActionableMessageTokenValidationResult(); var parameters = new System.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuer = true, ValidIssuers = new[] { O365OpenIdConfiguration.TokenIssuer }, ValidateAudience = true, ValidAudiences = new[] { targetServiceBaseUrl }, ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(TokenTimeValidationClockSkewBufferInMinutes), RequireSignedTokens = true, IssuerSigningKeys = o365OpenIdConfig.SigningTokens.SelectMany(st => st.SecurityKeys), }; System.IdentityModel.Tokens.JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler(); try { // This will validate the token's lifetime and the following claims: // // iss // aud // claimsPrincipal = tokenHandler.ValidateToken(token, parameters, out System.IdentityModel.Tokens.SecurityToken validatedToken); } catch (SecurityTokenSignatureKeyNotFoundException ex) { Trace.TraceError("Token signature key not found."); result.Exception = ex; return(result); } catch (SecurityTokenExpiredException ex) { Trace.TraceError("Token expired."); result.Exception = ex; return(result); } catch (SecurityTokenInvalidSignatureException ex) { Trace.TraceError("Invalid signature."); result.Exception = ex; return(result); } catch (Exception ex) { Trace.TraceError(ex.Message); result.Exception = ex; return(result); } if (claimsPrincipal == null) { Trace.TraceError("Identity not found in the token."); result.Exception = new InvalidOperationException("Identity not found in the token"); return(result); } ClaimsIdentity identity = claimsPrincipal.Identities.OfType <ClaimsIdentity>().FirstOrDefault(); if (identity == null) { Trace.TraceError("Claims not found in the token."); result.Exception = new InvalidOperationException("Claims not found in the token."); return(null); } if (!string.Equals(GetClaimValue(identity, "appid"), O365OpenIdConfiguration.AppId, StringComparison.OrdinalIgnoreCase)) { Trace.TraceError( "App ID does not match. Expected: {0} Actual: {1}", O365OpenIdConfiguration.AppId, GetClaimValue(identity, "appid")); return(null); } result.ValidationSucceeded = true; result.Sender = GetClaimValue(identity, "sender"); // Get the value of the "sub" claim. Passing in "sub" will not return a value because the TokenHandler // maps "sub" to ClaimTypes.NameIdentifier. More info here // https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/415. result.ActionPerformer = GetClaimValue(identity, ClaimTypes.NameIdentifier); return(result); }
public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = SettingsHelper.ClientId, Authority = SettingsHelper.Authority, ClientSecret = SettingsHelper.AppKey, ResponseType = "code id_token", Resource = "https://graph.microsoft.com", PostLogoutRedirectUri = "/", TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { // instead of using the default validation (validating against a single issuer value, as we do in line of business apps (single tenant apps)), // we turn off validation // // NOTE: // * In a multitenant scenario you can never validate against a fixed issuer string, as every tenant will send a different one. // * If you don’t care about validating tenants, as is the case for apps giving access to 1st party resources, you just turn off validation. // * If you do care about validating tenants, think of the case in which your app sells access to premium content and you want to limit access only to the tenant that paid a fee, // you still need to turn off the default validation but you do need to add logic that compares the incoming issuer to a list of tenants that paid you, // and block access if that’s not the case. // * Refer to the following sample for a custom validation logic: https://github.com/AzureADSamples/WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet ValidateIssuer = false }, Notifications = new OpenIdConnectAuthenticationNotifications() { SecurityTokenValidated = (context) => { // If your authentication logic is based on users then add your logic here return(Task.FromResult(0)); }, AuthenticationFailed = (context) => { // Pass in the context back to the app string message = Uri.EscapeDataString(context.Exception.Message); context.OwinContext.Response.Redirect("/Home/Error?msg=" + message); context.HandleResponse(); // Suppress the exception return(Task.FromResult(0)); }, AuthorizationCodeReceived = async(context) => { var code = context.Code; ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey); string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string signInUserId = context.AuthenticationTicket.Identity.FindFirst(AuthHelper.ObjectIdentifierClaim).Value; var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(SettingsHelper.Authority, new AzureTableTokenCache(signInUserId)); // Get the access token for AAD Graph. Doing this will also initialize the token cache associated with the authentication context // In theory, you could acquire token for any service your application has access to here so that you can initialize the token cache AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, SettingsHelper.AADGraphResourceId); }, RedirectToIdentityProvider = (context) => { // This ensures that the address used for sign in and sign out is picked up dynamically from the request // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand. string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase; context.ProtocolMessage.RedirectUri = appBaseUrl + "/"; context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl; if (FileHandlerController.IsFileHandlerActivationRequest(new HttpRequestWrapper(HttpContext.Current.Request), out FileHandlerActivationParameters fileHandlerActivation)) { // Add LoginHint and DomainHint if the request includes a form handler post context.ProtocolMessage.LoginHint = fileHandlerActivation.UserId; context.ProtocolMessage.DomainHint = "organizations"; // Save the form in the cookie to prevent it from getting lost in the login redirect CookieStorage.Save(HttpContext.Current.Request.Form, HttpContext.Current.Response); } // Allow us to change the prompt in consent mode if the challenge properties specify a prompt type var challengeProperties = context.OwinContext?.Authentication?.AuthenticationResponseChallenge?.Properties; if (null != challengeProperties && challengeProperties.Dictionary.ContainsKey("prompt")) { context.ProtocolMessage.Prompt = challengeProperties.Dictionary["prompt"]; } return(Task.FromResult(0)); } } });