HttpContext.Current is null in OpenId Connect OWIN middleware on SecurityTokenValidated - webforms

I'm working on a bug related to an OpenId Connect middleware (OWIN) in an ASP.NET Web Forms application which authenticates to Azure AD. I'm completely new to OWIN and OpenID, and did not write this code so bear with me.
The solution was tested and seemingly worked just fine, but once it hit production we saw multiple null reference exceptions, due to HttpContex.Current being null when the SecurityTokenValidated notification middleware was called.
The issue appear to happen roughly 30%-40% of the time the user tried to log in to production. We were initially not able to reproduce the issue locally, but we eventually found out we could reproduce 100% of the time by setting network speed in Chrome to Fast/Slow 3G speed (interestingly enough).
This is our code in the Startup.cs class to configure the Middleware:
[assembly: OwinStartup(typeof(Namespace.Startup))]
namespace Namespace
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var openIdConnectProvider = OpenIdConnectProviderDAO.GetOpenIdConnectProviders().Single(x => x.ClientId == "ClientIdHere");
app.Use((context, next) =>
{
var httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
httpContext.SetSessionStateBehavior(SessionStateBehavior.Required);
return next();
});
app.UseStageMarker(PipelineStage.MapHandler);
app.SetDefaultSignInAsAuthenticationType(OpenIdConnectAuthenticationDefaults.AuthenticationType);
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = openIdConnectProvider.ClientId,
Authority = openIdConnectProvider.Authority,
RedirectUri = ConfigurationHelper.GetAppSetting("applicationRoot").ToLower(),
AuthenticationType = openIdConnectProvider.Key,
AuthenticationMode = AuthenticationMode.Passive,
ResponseType = OpenIdConnectResponseType.IdToken,
Scope = OpenIdConnectScope.Email,
TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = openIdConnectProvider.ValidIssuer,
ValidateIssuer = true,
ValidAudience = openIdConnectProvider.ClientId,
ValidateAudience = true
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = OnSecurityTokenValidated,
AuthenticationFailed = OnAuthenticationFailed
}
});
}
private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> arg)
{
// This is null when connection speed is set to Slow/Fast 3G
var context = HttpContext.Current;
return Task.FromResult(0);
}
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
context.HandleResponse();
context.Response.Redirect("Login.aspx");
return Task.FromResult(0);
}
}
}
We need to access the HttpContext.Current in order to access the Session in the SecurityTokenValidated middleware. So we added the middleware as suggested in these posts:
Can OWIN middleware use the http session?
HttpContext.Current.Session is null + OWIN
This seemingly worked great, until the issues started popping up in production.
I've tried to use various combinations of UseStageMarker in various PipelinesStages (Authenticate, PostAcquireState etc), but none of them has worked.
Any help will be greatly appreciated!

Having the same issue, ran into this link. I found a solution to my problem on github.
Basically, add an empty Session_OnStart() method on Global.asax
Hope it helps others running into this problem.

Related

_userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email)) returns null

I am having an issue with Claims not populating with ClaimsPrinciple after creating a JWT. I am using ASP.NET Core 6 on VS 2022. The issue raised after configuring identity to include Roles and RolesUsers. I had no issues prior to including these 2 identity tables from the automated generated ones from IdentityModel.
now on creation, I show no errors and receive the JWT token without any issues, but afterwards when I try to authorize the user that log in the ClaimIdentity does not propagate and errors on _userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email)) showing null.
Here is some code to show the current state of the project.
First is the Method that handles the validation for login users.
[Authorize]
[HttpGet]
public async Task<ActionResult<UserDto>> GetCurrentUser()
{
// Null Exception Error
var user = await _userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email));
return CreateUserObject(user);
}
UserDto CreateUserObject( AppUser user )
{
return new UserDto
{
DisplayName = user.DisplayName,
Image = null,
Token = _tokenService.CreateToken(user),
Username = user.UserName
};
}
This is my Token Service that handles creating the JWT token from users that Register or Login.
public class TokenService
{
private readonly IConfiguration _config;
public TokenService(IConfiguration config)
{
_config = config;
}
public string CreateToken(AppUser user)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Email, user.Email)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["TokenKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(7.0),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
This is what I changed prior to having this issue in my IdentityServiceExtension Class.
public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
{
services.AddIdentity<AppUser, AppRole>(opt => //Changed AddIdentityCore to AddIdentity to apply AppUser & AppRole
{
opt.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<DataContext>()
.AddSignInManager<SignInManager<AppUser>>()
.AddRoleManager<RoleManager<AppRole>>(); //Added Role Manager for Roles to loaded.
var Key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"]));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = Key,
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddScoped<TokenService>();
// Added Roles to Policy
services.AddAuthorization(opt =>
{
opt.AddPolicy("Verified", pol =>
pol.RequireRole("User", "Staff", "Admin", "Guest"));
opt.AddPolicy("Restricted", pol =>
pol.RequireRole("User", "Staff", "Admin"));
opt.AddPolicy("EmployeeAccess", pol =>
pol.RequireRole("Staff", "Admin"));
opt.AddPolicy("ManagerAccess", pol =>
pol.RequireRole("Admin"));
});
//////////////////////
return services;
}
Hopefully this is enough information to help me with this issue. I have searched all over online and the resolutions I have seen does not match to my particular issue to solve the problem.
I surprisingly found the issue, so the reason I was having errors was due to not configuring Identity to handle all Identity Models. Prior to my change, I only handled users, but by adding roles and roleusers I had to handle all of Identity Model to prevent losing the claims. Due to this fact, I had to install another Microsoft Package,Microsoft.AspNetCore.Identity.UI, to gain access to the Identity Helper Method (.AddDefaultIdentity()) to configure the generated identity tables. Once added, Identity was fully configured and the issue was resolved. I hope anyone else that need help can use this as a possible solution.

Azure B2C Keep signed in MVC 6 .Net Core 2

I have an issue in my WebApp with Azure B2C.
Every time when the browser get closed I have to Sign In again.
This is not very convenient.
Is there any solution ?
I have tested a few (microsoft) examples, same effect.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(auth =>
{
auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
auth.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddAzureAdB2C(opts =>
{
Configuration.GetSection("Authentication:AzureAdB2C").Bind(opts);
})
.AddCookie(opts =>
{
opts.ExpireTimeSpan = TimeSpan.FromDays(14);
}
);
"IsPersistent=true" was an possible solution, but it has no effect.
SessionController.cs
[HttpGet]
public IActionResult SignIn()
{
return Challenge(
new AuthenticationProperties { IsPersistent = true, RedirectUri = Url.Action("SignedIn") },
OpenIdConnectDefaults.AuthenticationScheme);
}
I found a solution for my problem.
Microsoft.Owin.Security.OpenIdConnect with Azure Active Directory authentication ticket lifetime
OpenIdConnectionOption -> UseLifeTime = false; (default value)
Alternatively, if you don't want to save the application cookie across sessions and you are using Azure AD B2C custom policies, then you can enable the "Keep me signed in" (KMSI) functionality as follows:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-kmsi-custom

Web app and web api authentication in same application

I have a web app MVC,using auth0 owin regular web app cookie based authentication.
This web app also has webapis which is used internally in the application. However i have a requirement to call this webapis from outside the application. So i created a restclient and tried to implement jwtbearerauthentication in application (but cookie based on authentication still in place).
Now when i call the webapi from other application it validates the bearer token gives no error however it redirects to login page due to cookie based authentication.
startup file:
public partial class Startup
{
private IPlatform platform;
public void ConfigureAuth(IAppBuilder app, IPlatform p, IContainer container)
{
platform = p;
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = System.TimeSpan.FromDays(2),
SlidingExpiration = true
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
var provider = new Auth0.Owin.Auth0AuthenticationProvider
{
OnReturnEndpoint = (context) =>
{
// xsrf validation
if (context.Request.Query["state"] != null && context.Request.Query["state"].Contains("xsrf="))
{
var state = HttpUtility.ParseQueryString(context.Request.Query["state"]);
AntiForgery.Validate(context.Request.Cookies["__RequestVerificationToken"], state["xsrf"]);
}
return System.Threading.Tasks.Task.FromResult(0);
},
OnAuthenticated = (context) =>
{
var identity = context.Identity;
//Add claims
var authenticationManager = container.Resolve<IAuthenticationManager>();
authenticationManager.AddClaims(identity);
if (context.Request.Query["state"] != null)
{
authenticationManager.AddReturnUrlInClaims(identity, context.Request.Query["state"]);
}
return System.Threading.Tasks.Task.FromResult(0);
}
};
var issuer = "https://" + ConfigurationManager.AppSettings["auth0:Domain"] + "/";
var audience = ConfigurationManager.AppSettings["auth0:ClientId"];
var secret = TextEncodings.Base64.Encode(TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["auth0:ClientSecret"]));
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
}
});
app.UseAuth0Authentication(
clientId: platform.ServerRole.GetConfigurationSettingValue("auth0:ClientId"),
clientSecret: platform.ServerRole.GetConfigurationSettingValue("auth0:ClientSecret"),
domain: platform.ServerRole.GetConfigurationSettingValue("auth0:Domain"),
provider: provider);
}
}
webapiconfig file:
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});
config.Filters.Add(new AuthorizeAttribute());
ODataConfig.Setup(config);
var clientID = WebConfigurationManager.AppSettings["auth0:ClientId"];
var clientSecret = WebConfigurationManager.AppSettings["auth0:ClientSecret"];
config.MessageHandlers.Add(new JsonWebTokenValidationHandler()
{
Audience = clientID,
SymmetricKey = clientSecret
});
}
Currently creating the jwt token from below code and posting using postman in header just to check if it works.. but redirects to login page.
string token = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256);
I suspect what's happening is that your call to the API has a bearer token which fails validation (or there is no Authorize token at all), your API controller has an Authorize attribute, which, since there is no valid ClaimsPrincipal on the call throws 401. Auth0AuthenticationProvider picks that and assumes the call was to UI so redirects for user authentication. You may want to add an override in the Oauth0Provider to trap OnRedirectToIdP (or something like that), inspect the request and if it is to API, abot further handling and return Unauthorized.
Remove any [Authorize] from your API and see whether it works then. Also make sure your startup does not require Authorize for all controllers.
You may want to remove the authn part of your code (cookie and Oauth2Provider) and see whether you are getting to the API then.
A few years late i know, but i recently came across the same requirement in a project, and found this sample put together by a dev at Auth0.
https://github.com/auth0-samples/aspnet-core-mvc-plus-webapi
The example in the link allows for cookie authentication OR token authentication for the API endpoints.
The key takeaway for me was using attributes on your routes to tell the pipline what authentication mechanism to use. In my case i wanted cookie authentication for the UI and token authentication for the endpoints. i had no requirement to use both for any single area of the project.
controller:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[HttpGet]
[Route("api")]
public string TestAuth()
{
return "All good " + this.User.FindFirst(ClaimTypes.NameIdentifier).Value + ". You only get this message if you are authenticated.";
}

Enable CORS for Web Api 2 and OWIN token authentication

I have an ASP.NET MVC 5 webproject (localhost:81) that calls functions from my WebApi 2 project (localhost:82) using Knockoutjs, to make the communication between the two projects I enable CORS. Everything works so far until I tried to implement OWIN token authentication to the WebApi.
To use the /token endpoint on the WebApi, I also need to enable CORS on the endpoint but after hours of trying and searching for solutions it is still now working and the api/token still results in:
XMLHttpRequest cannot load http://localhost:82/token. No 'Access-Control-Allow-Origin' header is present on the requested resource.
public void Configuration(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
TokenConfig.ConfigureOAuth(app);
...
}
TokenConfig
public static void ConfigureOAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
AuthorizationProvider
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var appUserManager = context.OwinContext.GetUserManager<AppUserManager>();
IdentityUser user = await appUserManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
... claims
}
IdentityConfig
public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
{
// Tried to enable it again without success.
//context.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
var manager = new AppUserManager(new UserStore<AppUser>(context.Get<ApplicationDbContect>()));
...
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<AppUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
EDIT:
1. Important note is that opening the endpoint directly (localhost:82/token) works.
2. Calling the Api (localhost:82/api/..) from the webproject also works, so the CORS is enabled for WebApi.
I know your issue was solved inside comments, but I believe is important to understand what was causing it and how to resolve this entire class of problems.
Looking at your code I can see you are setting the Access-Control-Allow-Origin header more than once for the Token endpoint:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
And inside GrantResourceOwnerCredentials method:
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
This, looking at the CORS specifications, is itself an issue because:
If the response includes zero or more than one Access-Control-Allow-Origin header values, return fail and terminate this algorithm.
In your scenario, the framework is setting this header two times, and understanding how CORS must be implemented, this will result in the header removed in certain circumstances (possibly client-related).
This is also confirmed by the following question answer: Duplicate Access-Control-Allow-Origin: * causing COR error?
For this reason moving the call to app.UseCors after the call to ConfigureOAuth allows your CORS header to be set only once (because the owin pipeline is interrupted at the OAuth middleware, and never reaches the Microsoft CORS middleware for the Token endpoint) and makes your Ajax call working.
For a better and global solution you may try to put again app.UseCors before the OAuth middleware call, and remove the second Access-Control-Allow-Origin insertion inside GrantResourceOwnerCredentials.
Follow below steps and you will have your API working:
Remove any code like config.EnableCors(), [EnableCors(header:"*"....)] from your API.
Go to startup.cs and add below line
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
before
ConfigureAuth(app);
Uou will also need to install Microsoft.owin.cors package to use this functionality
Solving the problem without using app.UseCors()
I had the same problem. I used a Vue.Js client with axois to access my REST-API with cross-corps. On my Owin-Api-Server I was not able to add Microsoft.Owin.Cors nuget due to version conflicts with other 3rd party components. So I couldn't use app.UseCors() method but I solved it by using the middleware pipeline.
private IDisposable _webServer = null;
public void Start(ClientCredentials credentials)
{
...
_webServer = WebApp.Start(BaseAddress, (x) => Configuration(x));
...
}
public void Configuration(IAppBuilder app)
{
...
// added middleware insted of app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.Use<MyOwinMiddleware>();
app.UseWebApi(config);
...
}
public class MyOwinMiddleware : OwinMiddleware
{
public MyOwinMiddleware(OwinMiddleware next) :
base(next)
{ }
public override async Task Invoke(IOwinContext context)
{
var request = context.Request;
var response = context.Response;
response.OnSendingHeaders(state =>
{
var resp = (IOwinResponse)state;
// without this headers -> client apps will be blocked to consume data from this api
if (!resp.Headers.ContainsKey("Access-Control-Allow-Origin"))
resp.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
if (!resp.Headers.ContainsKey("Access-Control-Allow-Headers"))
resp.Headers.Add("Access-Control-Allow-Headers", new[] { "*" });
if (!resp.Headers.ContainsKey("Access-Control-Allow-Methods"))
resp.Headers.Add("Access-Control-Allow-Methods", new[] { "*" });
// by default owin is blocking options not from same origin with MethodNotAllowed
if (resp.StatusCode == (int)HttpStatusCode.MethodNotAllowed &&
HttpMethod.Options == new HttpMethod(request.Method))
{
resp.StatusCode = (int)HttpStatusCode.OK;
resp.ReasonPhrase = HttpStatusCode.OK.ToString();
}
}, response);
await Next.Invoke(context);
}
}
So I created my own middleware and manipulated the response. GET calls only needed the Access-Control-Allow headers whereas for OPTIONS calls I also needed to manipulate the StatusCode because axois.post() is calling first with OPTIONS-method before sending the POST. If OPTIONS return StatusCode 405, the POST will never be sent.
This solved my problem. Maybe this can help somebody too.

IdentityServer3 and Web API in same process

I have Asp.net MVC web application and webapi in same project.I am using Resource owner Credential flow to have identity management.Is it possible to configure webapi, client and identity server in same startup.cs(startup.cs of webapplication).While trying to configure webapi and identity server in same startup.cs i ended up with the following error "An exception of type 'System.InvalidOperationException' occurred in IdentityServer3.AccessTokenValidation.dll but was not handled in user code
Additional information: IDX10803: Unable to create to obtain configuration from: 'https://localhost:44303/.well-known/openid-configuration'."
Here is the code of my startup.cs:
using IdentityServer3.AccessTokenValidation;
using IdentityServer3.Core.Configuration;
using IdentityServer3.Core.Services;
using IdentityServer3.Core.Services.Default;
using MarilynIdentityServer.IdentityServer;
using Microsoft.Owin;
using Owin;
using System;
//using System.IdentityModel.Claims;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Web.Http;
using System.Linq;
[assembly: OwinStartupAttribute(typeof(MarilynIdentityServer.Startup))]
namespace MarilynIdentityServer
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var factory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get());
var userService = new UserLoginService();
factory.UserService = new Registration<IUserService>(resolver => userService);
factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService { AllowAll = true });
var option = new IdentityServerOptions
{
SiteName = "Embedded IdentityServer",
SigningCertificate = LoadCertificate(),
Factory = factory,
//AuthenticationOptions = new AuthenticationOptions
//{
// //EnableLocalLogin = false,
// IdentityProviders = ConfigureIdentityProviders
//},
};
app.UseIdentityServer(option);
app.Map("/api", idsrvApi =>
{
// token validation
idsrvApi.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44303/",
RequiredScopes = new[] { "sampleApi" }
});
// add app local claims per request
idsrvApi.UseClaimsTransformation(incoming =>
{
// either add claims to incoming, or create new principal
var appPrincipal = new ClaimsPrincipal(incoming);
incoming.Identities.First().AddClaim(new Claim("appSpecific", "some_value"));
return Task.FromResult(appPrincipal);
});
// web api configuration
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
idsrvApi.UseWebApi(config);
});
}
X509Certificate2 LoadCertificate()
{
return new X509Certificate2(
string.Format(#"{0}bin\identityServer\idsrv3test.pfx", AppDomain.CurrentDomain.BaseDirectory), "idsrv3test");
}
}
}
To conclude Is it possible to configure WebApi, Webapplication and Identity Server in same application?
Any help would be appreciated.
Regards
Amit
It definitely is possible, however I have experienced similar issues to yourself in not being able to find the local Identity Server.
What usually solves it is modifying your pipeline to have Identity Server in it's own app.Map block instead of the root. This seems to make it discoverable by the authentication middleware.
If you try this, don't forget to update the authority in you authentication middleware.
I achieved the goal stated by this question using a combination of Scott Brady's post and Andras Nemes's post, both excellent. Here's the Startup.cs that worked for me:
using IdentityServer3.Core.Configuration;
using Owin;
using System.Web.Http;
namespace idsvr3owin
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// kick the Web API piece of this app
app.Map(
"/api",
apiApp => {
HttpConfiguration httpConfiguration = new HttpConfiguration();
// api.App_Start is a namespace in my app
api.App_Start.WebApiConfig.Register(httpConfiguration);
apiApp.UseWebApi(httpConfiguration);
}
);
// kick the IdentityServer3 piece of this app
app.Map(
"/identity",
identityApp =>
{
identityApp.UseIdentityServer(new IdentityServerOptions
{
SiteName = "Standalone Identity Server",
// idsvr3 is a namespace in my app
SigningCertificate = idsvr3.Cert.LoadCertificate(),
Factory = new IdentityServerServiceFactory()
.UseInMemoryClients(idsvr3.Clients.Get())
.UseInMemoryScopes(idsvr3.Scopes.Get())
.UseInMemoryUsers(idsvr3.Users.Get()),
RequireSsl = true
});
}
);
}
}
}

Resources