Identity Server: Redirect When Route Requires Logged in User

This post is going to continue where the series on IdentityServer4 left off, but I am not officially making it part of the series. There may be a few posts like this where I improve on the example applications from the series. The starting code for this post can be found here.

All the changes in the post are in the Client Application from the sample linked above. I did some cleanup on a couple of files so if you are looking for the differences keep in mind most of the changes are a result of the cleanup.

Unauthorized Component

The first step is to add a new component that will be shown to the user when they navigate to a page that requires them to be logged in but they are not. Add a  unauthorized.component.html file to the  ClientApp/app/components/unauthorized/ directory with the following contents.

This will tell the user they need to log in and provide a login button and a button to go back to the previous page. Next, add a  unauthorized.component.ts file to the same directory. This class will handle the clicks from the view.

This class is using the  AuthService for login and Angular’s  Location class to move back to the previous page.

New Component Usage

Now that this new component exists it needs to set up in  app.module.shared.ts. First, add an import.

Next, add to the  declarations array.

Finally, add unauthorized to the routes array.

Now that this new component is in place how does it get used? Well, any route that has  canActivate:[AuthGuardService] will require the user to be logged in to activate. For example, the  fetch-data route above won’t activate unless the user is logged in.

Auth Guard Service

AuthGuardService is an existing class in the project. The following is the full file.

As you can see in the  canActivate function if the user is logged in then the function returns true otherwise, the user is routed to the unauthorized component. Before the changes in this post, this dropped the user back on the home page since the unauthorized component didn’t exist.

Wrapping up

With the changes above the user gets a slightly better experience. Just being dropped on the home page wasn’t very helpful as to why that was happening. This at least lets the user know they need to log in. Another option could be to hide the navigation for the routes they don’t have access to until they log it.

The finished version of the code can be found here.

Identity Server: Calling Secured API from Angular

This post is a continuation of a series of posts that follow my initial looking into using IdentityServer4 in ASP.NET Core with an API and an Angular front end. The following are the related posts.

Identity Server: Introduction
Identity Server: Sample Exploration and Initial Project Setup
Identity Server: Interactive Login using MVC
Identity Server: From Implicit to Hybrid Flow
Identity Server: Using ASP.NET Core Identity
Identity Server: Using Entity Framework Core for Configuration Data
Identity Server: Usage from Angular

This post is going to take the solution from last week, the code can be found here, and add an example of the Client Application (Angular) calling an endpoint on the API Application that requires a user with permissions.

API Application

To provide an endpoint to call with minimal changes this example just moves the SampleDataController from the Client Application to the API Application. The following is the full class.

Make special note that this class now has the  Authorize attribute applied which is the only change that was made when moving the file from the Client Application. This attribute is what will require an authorized user for all the routes this controller services.

Client Application

In the Client Application, the first step is to remove the  SampleDataController since it is now in the API Application.

Next, in the  app.module.client.ts file, add a new provider which can be used to supply the URL of the API to the rest of the Client Application. Don’t take this as best practices for injecting configuration data it is just an easy way to handle it in this application. The following is the full class without the imports (which haven’t changed) the new item is the  API_URL.

Now for the changes that need to be made to the  FetchDataComponent which is the class that will call the new API endpoint. First, add an import for the  AuthService.

Next, there are a couple of changes to the signature of the constructor. The first is to use  'API_URL' instead of  'ORIGIN_URL'. The second is to provide for injection of the  AuthService. The following is a comparison between the version of the constructor signature.

The final change is to use  authService.AuthGet with the new URL instead of  http.get.

With the above changes, the user has to be logged in or the API will respond with not authorized for the weather forecasts end point. The Client Application doesn’t have anything to provide the user with the fact they aren’t authorized at the moment, but that is outside the scope of this entry.

So far we haven’t look at the code in the  AuthService class, but I do want to explain what the  AuthGet function is doing and the related functions for put, delete, and post. These calls are wrappers around the standard Angular HTTP library calls that add authorization headers based on the logged in user. The following is the code of the  AuthGet as well as two helper functions the class uses to add the headers.

Wrapping up

It feels like this application is finally getting to the point where other development could happen if it were more than a demo, which is exciting. My thought on how this could be used for real applications is the Identity Application would stand on its own and be used by many clients. The Client Application with a few more tweaks could be used as a template for Angular applications. The completed code can be found here.

This post finishes up the core of what I set out to learn about IdentityServer, but there could be more related posts as I continue to add some polish to the current implementation of the sample solution.

Identity Server: Usage from Angular

This post is a continuation of a series of posts that follow my initial looking into using IdentityServer4 in ASP.NET Core with an API and an Angular front end. The following are the related posts.

Identity Server: Introduction
Identity Server: Sample Exploration and Initial Project Setup
Identity Server: Interactive Login using MVC
Identity Server: From Implicit to Hybrid Flow
Identity Server: Using ASP.NET Core Identity
Identity Server: Using Entity Framework Core for Configuration Data
Identity Server: Usage from Angular (this post)

This post is finally going to add login from Angular in the Client Application. It has been a long time coming and will be a starting point, based on a few examples I found which I will list at the end. The starting point of the code can be found here.

API Application

In order for the Client Application to be able to call the API Application, there are some changes needed to allow cross-origin resource sharing. For more details check out this post only the basics will be covered here. First, add the following NuGet package.

  • Microsoft.AspNetCore.Cors

Next, in the  ConfigureServices function of the  Startup class add AddCors before AddMvc. The following is the full function. This allows calls to the API Application from the Client Application which is running on localhost on port 5002.

Then, in the  Configure function add  app.UseCors("default"); to make sure the default policy defined above is enforced. The following is the full function.

Identity Application

The Identity Application doesn’t have a lot of changes, but some of the configuration between it and the Client Application is what took me the bulk of time getting the code for this post setup and going.

If you are keeping up with the series then last you will know last week all the configuration data was moved to a database using Entity Framework Core. This is a bit of a problem now that I need to add a new client and the configuration data doesn’t any associated UI. To work around this I just added the new client to the  Config class in the  GetClients function and then deleted the existing database and let Entity Framework recreate it based on the new seed data. Not optimal, but I didn’t want to complicate things by adding a UI for the client setup. The following is the new client.

There are a few things in this configuration that took me some time to get right. First of all best, I have been able to tell with this style of application implicit flow is the way to go which is handled by using a  GrantTypes.Implicit for the  AllowedGrantTypes.

The next issues I ran was a cross-origin resource sharing issue. Thankfully IdentityServer makes it easy to specify what origins should be allowed using the  AllowedCorsOrigins property. In this example, we want to allow requests from the URL of our Client Application which is http://localhost:5002.

The last issue I had on was with the URIs I had set. The configuration in IdentityServer needs to exactly match the setup in the Client Application or you will have issues. I also had trouble trying to use the raw base address (http://localhost:5002) as the  PostLogoutRedirectUris so look out for that as well.

Client Application

In the client application open the  package.json file and add the following the  dependencies section.

I also updated the typescript version to 2.3.4. Be cautious when changing the version of typescript as there is an issue with Angular and typescript 2.4.x at the moment.

At this point in the process, I had to find some resources on how to continue. The following are the ones I leaned on most.

ANGULAR OPENID CONNECT IMPLICIT FLOW WITH IDENTITYSERVER4
ASP.NET Core & Angular2 + OpenID Connect using Visual Studio Code
Repo for the previous link
Repo for with example Angular OidcClient

Getting this part of the application working involved a lot of changes and instead of going in depth on everything I am going to recommend just copying in the following files for the finished example code and dig more into them after you get an example working. Here is the list of files.

  • ClientApp/ClientApp/app/components/callback/callback.component.ts
  • ClientApp/ClientApp/app/components/services/ – whole directory
  • ClientApp/ClientApp/boot-server.ts – related to a typescript error only if needed

With the above files in place, we will now focus on using the functionality they provide to log in and protect routes. To begin   app.module.client.tsapp.module.server.ts and  app.module.shared.ts all need the next set of changes. I haven’t tried it yet, but I bet this change could just be made in the shared file and used in the other two. Add the following imports.

Next, add the same three items to the array of providers (or add one if it doesn’t exist). The following is an example from the shared file.

Finally, in the shared file change any routes that you would like to require the user to be logged in to be like the following which utilizes the  canActivate of the route.

In the  navmenu.component.html which is the UI for the navigation menu add the following two options to the unordered list.

The user will only ever see one of the above options based on being logged in or not which is what the  *ngIf is doing.

The navigation view model ( navmenu.component.ts) changed a bit more. The following is the complete file.

New imports were added for the  AuthService and  GlobalEventsManager which get injected into the constructor of the class. The class also contains a _loggedIn property to track if the user is logged in or not. Finally, functions were added for  login and  logout to go with the two new links shown in the navigation.

Wrapping up

With the above, the Client Application can now log a user in and out utilizing IdentityServer from Angular. There are a lot of details in the files we just copied, but with a working sample, it is much easier to examine/customize how the process is being handled. Check back next week to see how to call the API Application from the Angular part of the Client Application.

The completed code can be found here.

Identity Server: Using Entity Framework Core for Configuration Data

This post is a continuation of a series of posts that follow my initial looking into using IdentityServer4 in ASP.NET Core with an API and an Angular front end. The following are the related posts.

Identity Server: Introduction
Identity Server: Sample Exploration and Initial Project Setup
Identity Server: Interactive Login using MVC
Identity Server: From Implicit to Hybrid Flow
Identity Server: Using ASP.NET Core Identity
Identity Server: Using Entity Framework Core for Configuration Data (this post)
Identity Server: Usage from Angular

This post is going to take the existing solution this series has been using and switch from using hard coded configuration data, found in the  Config class of the Identity Application and moving it to a database using Entity Framework Core. As with prior entries, this will be following the intent of one of the official quick starts for Using Entity Framework Core for configuration data. This post is fairly different just because our example project already uses entity framework so a lot of steps can be skipped. The starting point of the code can be found here. All the changes in this post will be taking place in the Identity Application.

Identity Application

Thankfully the creators of IdentityServer provide a NuGet package that includes all the bits needed to move configuration data and operational data to Entity Framework Core. Start by added the following NuGet package.

  • IdentityServer4.EntityFramework
Startup

With the above NuGet package installed the  ConfigureServices function of the  Startup class needs to be changed to tell IdentityServer the new place to pull data from. The following is the new version of the  AddIdentityServer call updated to use Entity Framework Core.

Notice that the following have all been replaced by  AddConfigurationStore and  AddOperationalStore.

  • AddInMemoryPersistedGrants
  • AddInMemoryIdentityResources
  • AddInMemoryApiResources
  • AddInMemoryClients

The other thing of note is the  migrationsAssembly and its usage via  options.MigrationsAssembly. This is moving the management of the migrations from the assembly that the contexts are defined to the Identity Application. This is needed in this case since the two contexts in question are defined in a NuGet package.

Migrations

Now that the configuration is done for the new contexts migrations need to be added to them. As always there are two ways to handle this either via the Package Manager Console or from a command prompt. I am going to use the command prompt this round to match the IdentityServer docs. Run the following two commands from the same path as the Identity Application’s csproj file.

This is the first time I have used the  -o argument which controls where the migration is output and following the docs example I am putting the migrations that are for entities outside of the control of the application into a subdirectory. Speaking of the entities being outside of the control of the main application, this means anytime the NuGet package that contains the entity is updated a check will need to be made to see if new migrations are needed.

Database Migrations and Seed Data

Since the  DbContext classes that need migrations run are outside of the control our application if automatic migrations must be handled in a different way than with the identity-related context used previously in this series. Following the official docs, I am going to create an  InitializeDatabase function that will apply any needed migrations as well as add seed data. To do this I am adding a new IdentityServerDatabaseInitialization class in the Data/IdentityServer directory. The following is the full class.

The  InitializeDatabase takes an  IApplicationBuilder in order to be able to control the lifetime of the two  DbContext classes needed. Normally this wouldn’t be needed and the lifetime would be controlled automatically, but since this code is being called from the  Startup class instead of during a request (which is how the DI system does auto scoping) the scope is being created by the  app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope() call.

The  PerformMigrations function pulls the two  DbContext objects from the container and applies migrations. Finally in  SeedData if the  DbSets don’t already contain data then the seed data is pulled from the  Config class and saved to the database.

Back to Startup

In the  Configure function of the  Startup class add the following call to make sure migrations and seed data are run when the application starts.

Wrapping up

With the above changes, the Identity Application is now using the database for all its persistence. The missing bits are of course UI to manage the related data, but those can be built out as needed. The code in its completed state can be found here.

The next steps for this project will be utilizing IdentityServer from Angular in the Client Application instead of the temporary  IdentityController that has had to be used in all the examples so far.

Identity Server: Using ASP.NET Core Identity

This post is a continuation of a series of posts that follow my initial looking into using IdentityServer4 in ASP.NET Core with an API and an Angular front end. The following are the related posts.

Identity Server: Introduction
Identity Server: Sample Exploration and Initial Project Setup
Identity Server: Interactive Login using MVC
Identity Server: From Implicit to Hybrid Flow
Identity Server: Using ASP.NET Core Identity (this post)
Identity Server: Using Entity Framework Core for Configuration Data
Identity Server: Usage from Angular

This post is going to cover using ASP.NET Core Identity instead of an in-memory user store like the previous examples. As I write this I am working through the Using ASP.NET Core Identity quick start from the docs. This isn’t going to differ a whole lot from the official docs, but I still want to document it to help solidify everything in my head. The starting point of the code for this post can be found here.

Identity Application

The Identity Application will be where the bulk of the changes happen. Since it is much easier to add IdentityServer to a project than it is to add ASP.NET Core Identity we are going to delete the existing Identity Application project and re-create it with Identity from the start. Right click on the IdentityApp project and click remove.

This removes the project from the solution, but the files also need to be deleted off of disk or use a different name. I chose to rename the old project folder on disk so I could still grab any files I might need.

Create a new Identity Application

Right-click on the solution and select Add > New Project.

On the Add New Project dialog under Visual C# > .NET Core select ASP.NET Core Web Application and enter the name of the project (IdentityApp in this example) and click OK.

On the next dialog select the Web Application template.

Next, click the Change Authentication button and select the Individual User Accounts option.

Click OK on the Change Authentication dialog and then click OK on the template dialog. After a few seconds, the solution will contain a new IdentityApp that is using ASP.NET Core Identity with Entity Framework Core.

Adding Identity Server to the Identity App Project

Using NuGet install the IdentityServer4.AspNetIdentity package which will also install  IdentityServer4 which the old project was using. Next, copy the  Config class from the old IdentityApp project and delete the  GetUsers function.

Startup Changes

In the  Startup class at the end of  ConfigureServices function add the following.

The only difference between this and the one used with the previous posts is instead of  AddTestUsers being used to pull a hard coded list of uses our of the  Config class users are pulled from the database using ASP.NET Core Identity using this  AddAspNetIdentity<ApplicationUser>() call. Identity Server is very flexible and this is only of the option for an identity store.

Next, in the  Configure function add  app.UseIdentityServer() after  app.UseIdentity().

Database

There are a couple of ways to make sure the database is created and migrated when changes happen. One is via the command line in the project directory using the following command.

The way I normally us when at this stage in development is to add code to the DB context to automatically apply migrations. The following is the full  ApplicationDbContext class modified to automatically run migrations when the context is constructed.

Now throw that all away

The above is good to go through to know how things work, but I got to this point and wanted the functionality to be on par with the previous entries. The docs made this sound simple, but it was not simple at all I had a list of at least 30 points of files to be moved and changes made to existing files. I am going to spare you all those details and recommend that you just pull the Identity Application from my GitHub repo for this project instead. I did basically the same thing out of the official samples repo to get things working as they should with contents, errors, and log out.

If you want the auto migrations then make sure and keep the version of the  ApplicationDbContext from above.

Client Application

No changes are actually required to the client application, but as in the official docs, I made changes to show hitting the API Application using both a user access token and client credentials. The following is the index action on the  IdentityController which has been changed to call two functions one for each type of API access.

The following is the function to access the API Application using a user access token.

Now the function to access the API Application using client credentials.

Finally,  Index.cshtml found in the Views/Identity directory has the following change.

Wrapping up

Now the Identity Application is using ASP.NET Core Identity with Entity Framework Core to store users in the database. The next post will cover moving the items now in the  Config class into the database. The completed version of the code can be found here.

Identity Server: From Implicit to Hybrid Flow

This post is a continuation of a series of posts that follow my initial looking into using IdentityServer4 in ASP.NET Core with an API and an Angular front end. The following are the related posts.

Identity Server: Introduction
Identity Server: Sample Exploration and Initial Project Setup
Identity Server: Interactive Login using MVC
Identity Server: From Implicit to Hybrid Flow (this post)
Identity Server: Using ASP.NET Core Identity
Identity Server: Using Entity Framework Core for Configuration Data
Identity Server: Usage from Angularsing MVC

This post is going to cover adding back in the API access that was lost in the last post by changing the MVC client to use a hybrid grant instead of an implicit grant. This post was written while working through Switching to Hybrid Flow and adding API Access back in the official docs.

Identity Application

The changes to the Identity Application are pretty simple and only involve tweaking the settings on the MVC client found in the  GetClients function of the  Config class. First, change the  AllowedGrantTypes from  Implicit to  HybridAndClientCredentials. Next, a client secret should be added.

This is, of course, a bad secret, but this is only an example. Next, add  "apiApp" to the  AllowedScopes and finally add  AllowOfflineAccess = true. The following is the full client code.

Most of the above are straight forward.  AllowedGrantTypes is what is moving to the hybrid flow which then needs a client secret to ensure everything is on the up and up. This client should be able to hit the API application so it is added to the allowed scopes.  AllowOfflineAccess is less clear to me. According to the docs, it allows the requesting refresh tokens for long-lived API access. This would take some more digging before production to ensure authorization isn’t too long lived.

Client Application

Changes to the client application were pretty minimal as well. First, in the  Configure function of the  Startup class, the  UseOpenIdConnectAuthentication call must pass a few more items. The following is the full set up.

ClientSecret should match what was set up for the client in the Identity Application. According to the docs setting  ResponseType to  code id_token means use a hybrid flow. This is another point that I would want to dig more on.  Scope is requesting access to the API Application and offline access which is the matching part to the offline access set up in the Identity Application.  GetClaimsFromUserInfoEndpoint tells the middleware to go to the user info endpoint to retrieve additional claims after getting an identity token.

Identity Controller

The  Index action in the  IdentityController ends up being much simpler than it was in the previous posts. The following is the full function.

In the new version, the token can be retrieved from the HTTP context instead of using the  DiscoveryClient and  TokenClient like the previous version of this code did. The general idea is the same in both which is to get a token, use the token as part of a request to the API application, and finally display the response in a view.

Identity View

The last set of changes is to the  Index.cshtml file in the View/Identity directory which is the view that goes with the Index action of the  IdentityController. The view displays the access token, refresh token, results of the API call, and the logged in user’s claims.

Wrapping up

Adding back API access was pretty easy and the new setup will make managing other resources pretty simple. The identity space is still pretty new to me but working through the IdentityServer quickstarts are helping get me up to a basic level of knowledge. The finished code for this post can be found here. Come back next week to convert this example to use ASP.NET Core Identity.

Identity Server: Interactive Login using MVC

This post is a continuation of a series of posts that follow my initial looking into using IdentityServer4 in ASP.NET Core with an API and an Angular front end. The following are the related posts.

Identity Server: Introduction
Identity Server: Sample Exploration and Initial Project Setup
Identity Server: Interactive Login using MVC (this post)
Identity Server: From Implicit to Hybrid Flow
Identity Server: Using ASP.NET Core Identity
Identity Server: Using Entity Framework Core for Configuration Data
Identity Server: Usage from Angular

As before the end goal will be having authorization happen from Angular, but in the short term, the Client Application is using MVC/Razor for testing and verifications. The code as it stood before this post can be found here. If you are following along with the official docs I wrote this post while working through the Adding User Authentication with OpenID Connect quickstart.

The main point of this post is to add a way for a user to enter their username and password and get access to a page that requires authorization using the OpenID Connect protocol.

Identity Application

To enable this scenario the Identity Application will need MVC added along with some UI that will be used to handle login, permissions, and log off. First, using NuGet install the following two packages.

  • Microsoft.AspNetCore.Mvc
  • Microsoft.AspNetCore.StaticFiles

Next, in the ConfigureServices of the Startup class MVC needs to be added as a service.

Then in the Configure function use static files and use MVC should be added after the use statement for IdentityServer.

UI Changes

For the type of flow being used in this sample, the Identity Application will be in control of the login, grant, log out, and related UI. This is not a small amount of thing to get set up properly. Thankfully the IdentityServer team provides a Quickstart UI for use with the in-memory items we are currently using. The files can be downloaded from the repo linked in the previous line or an easier way is to open a Powershell prompt in the same directory of the Identity application as the Startup.cs file and run the following command.

After the download the project will contain a Quickstart folder with the needed controllers, a Views with of course the needed views, and wwwroot will have all the related files that need to be served with the views.

Config Changes

The Config class needs to be changed to return some more in-memory information to make this new process work. The first is to add a new client for MVC to the GetClients function. The following is the full function, but it is the second Client is the new one.

Notice that for the OpenID Connect implicit flow there are URLs that are needed that so this flow knows how to call back into the client application. At this point, I haven’t dug into everything that is going on in the client. The ClientId, ClientName, and URLs related properties are pretty clear. I am not 100% on the AllowedGrantTypes and AllowedScopes, but at this point, I am not going to dive into on these two options.

Next, add a  GetIdentityResources function matching the following. This fall in the same category as the two properties above, we are using them without fully digging into them.

The last change to the Config class is to add a function to return the in-memory users.

Startup Changes

The last change in the Identity Application is to add the new in-memory items to the IdentityServer service in the ConfigureServices function. The following is the full function.

Client Application

In order to get the client application to play well with the changes in the Identity Application, a few changes need to be made. First, the following NuGet packages need to be installed.

  • Microsoft.AspNetCore.Authentication.Cookies
  • Microsoft.AspNetCore.Authentication.OpenIdConnect

Next, in the  Configure function of the  Startup class, the application’s middleware pipeline needs some changes. Add the following line to turn off the JWT claim type mapping. This must be done before calling  UseOpenIdConnectAuthentication.

Now add in the cookie authentication middleware.

The last change is to add OpenID Connect authentication to the pipeline placed after the cookies middleware.

Notice that the URL of the authority is the URL the Identity Application runs on as well as the client ID match the one we set up in the  GetClients function of the  Config class in the Identity Application.

Identity Controller

Now that the above is set up we can switch over to the  IdentityController and add the  Authorize attribute to the  Index function.

This means if a user hits the index action of this controller and isn’t logged in they will be presented with the login page and after login, they will be redirected back to the above index action. That whole process is handled by the OpenId Connect Authentication middleware. The first time I tested the flow and it just worked was magical.

 

The final set of changes for this post is going to be added a way to log out. In the  IdentityController add a  Logout function.

Identity View Changes

The last change is to add a logout button to the  Index.cshtml found in the Views/Identity directory. At the bottom of the page, the following was added to call the  Logout action.

Wrapping Up

I already liked the idea of IdentityServer before this post, but after playing with it with the changes above it is emphasized how nice it is. I am very happy I am going down this path instead of trying to work this all out on my own. Stay tuned as this exploration will continue in future posts.

The code in the finished state can be found here.

Update

Turns out there is a bug in the code that goes with this example. In the client application’s  IdentityConroller the call to get a token is using  clientApp instead of  mvc for the client ID when requesting a token. With that change, the call to the API Application will fail since the MVC client doesn’t have access to the API scope. Look for next weeks post where API access will be added to the MVC client.

Identity Server: Introduction

In the SPA based sample applications, this blog has used so far user authentication has either been completely ignored in order to keep the examples simpler or the sites have used ASP.NET Core’s built in identity to encapsulate the whole SPA. In this post (or series of posts) I am going to share what I learn along the way of creating an Angular (2+) application that utilizes ASP.NET Core as its host/API/backend.

This post isn’t going to cover any code it is just going to be a lot of the information I gathered in the process of learning more about Identity Server.

Following are all the post in this series.

Identity Server: Introduction (this post)
Identity Server: Sample Exploration and Initial Project Setup
Identity Server: Interactive Login using MVC
Identity Server: From Implicit to Hybrid Flow
Identity Server: Using ASP.NET Core Identity
Identity Server: Using Entity Framework Core for Configuration Data
Identity Server: Usage from Angular

Identity Server

According to their docs IdentityServer4 is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core which enables Authentication as a Service, Single Sign-on, API Access Control and a Federation Gateway.

Obviously, that covers a lot of scenarios. The two that I am interested in are Authentication as a Service and the API Access Control which has driven my research which means that the other aspects of IdentityServer4 will not be included.

Official Samples

The IdentityServer GitHub account has a samples repo that contains a ton of examples. I have found the quickstart area of the repo to be the most helpful when starting out.

Based on all the quickstarts samples it looks like a typical setup involves a minimum of three projects. One for the API, one for the client and one for Identity Server. As you go through the samples the number of projects increase, but that is because of a wider range of scenarios that the sample is trying to cover.

References for learning

Damienbod has a whole series of blog posts related to IdentityServer4 and code to go along with it which can be found here. As a side note if you are interested in ASP.NET Core and you aren’t following damienbo you should be he has a ton of great content.

Blog posts
Videos

Identity Server Alternatives

Identity Server isn’t the only way to go there is a number of Software as a Service options that cover a lot of same scenarios. The following are some examples.

Auth0 – Check out the .NET Core related blogs by Jerrie Pelser
Stormpath
Amazon Cognito

Wrapping up

Obviously, I didn’t get a lot covered on how to actually do something with IdentityServer, but I wanted to share my starting point. This is an area I am going to continue digging it to and sharing information about as I learn more.

If you have any resources in this area please leave a comment below.

ASP.NET 5 IIS Express Configuration and OAuth 2

I am still in the process of getting all the features from my ASP.NET 4 contacts application moved into ASP.NET 5. Today I was working on getting OAuth 2 working with Google. All the code changes are in the Startup.cs in the root of the project.

In the Configuration function the options need to be set for Google authentication. This is where you set your client ID and secret. I covered the steps of getting this information from Google in this post if you need a reference.

In the Configure function add the following.

The above is changing the Configuration and Configure functions which are pretty similar names that could be clearer. Configuration is where services are registered withASP.NET 5’s built in dependency injection container. Examples of potential services include Entity Framework, MVC, Web API, Application Settings and in my case Google Authentication.

The Configure function is where the HTTP request pipeline is set up. This can include things like serving static files, error handlers, MVC routes and Web API routes.

At this point I tried to run and use Google to login. I was greeted with at 400 – redirect_uri_mismatch. The URL my new project was using did not match the one I used when I setup OAuth with Google. I would like to say this was not a big deal, but it took me way longer to solve than I would like to admit. The settings for which port to use when debugging is in a bit of a different place than before. It can now be found on the debug tab of the project properties.

ProjectDebugProps

Under Other IIS Express setting there is also a check box for Enable SSL which I had to check as well since the URL I used with Google was HTTPS. In addition to the settings in the project properties I also had to edit the applicationhost file which is used by IIS Express. You can find this file in a hidden folder in the same directory as the solution file. The path is .vs\config. To find the relevant section search for your project name or for “site name=” and that should get you to the right area. I tweaked the setting I found there to match the changes I had made in my project properties. I don’t think this is something everyone will have to do and more than likely was a result of a misstep on my part.

I ended up having to manually edit my Contacts.xproj file to get the port settings I needed. The project properties UI will let you set a port, but not edit the HTTPS URL which meant I could not get the URL I need to make Google happy without manual changes. Following is the relevant portion of my Contacts.xproj file and it is the SSLPort I had to edit.

At this point I can now start the application, but I have to manually use the HTTPS URL to get auth with Google to work since I have not found away to get Visual Studio to launch the using the HTTPS URL.

The good news is Google auth does work now!

More OAuth

Last week I covered using OAuth with Google for authentication. I thought I would try GitHub next only to find out Microsoft does not have a built in provider. After a little searching I came across OWIN OAuth Providers on GitHub. This project has a ton for providers ranging from BattleNet to Yammer.

To install run the following from the package manager console.

The rest of the process is very similar to last weeks post. I am going to walk through GitHub for this example but the others are very similar. The big difference for each provider is getting API access.

At the top of Statup.Auth.cs in the App_Start folder add the following.

And at the bottom of the ConfigureAuth function.

The next setup is to set up API access with GitHub. Login to GitHub and go to Developer applications.

oauthgithub

Click the Register new application button in the upper right of the page. On the registration page enter an application name, homepage URL and authorization callback URL. As last week the URL options will be need to be based on your project settings. After entering all your information click Register application.

oauthgithubRegisterApplication

Then next page will show your client ID and client secret which just need to be entered in Statup.Auth.cs. That is all there is to adding an additional OAuth provider and give your users even more authentication options.

oauthgithubLogin

Using OWIN OAuth Providers makes adding access other OAuth providers just as simple as the providers from Microsoft.