Build an ASP.NET Core Application With User Authentication
In this tutorial, Nate Barbettini shows us how to scaffold a basic ASP.NET Core MVC application and plug in Stormpath user authentication with two lines of code.
Join the DZone community and get the full member experience.
Join For FreeWe’re thrilled to announce our open-source ASP.NET Core authentication library is now available! What’s the deal with ASP.NET Core, you ask?
ASP.NET Core 1.0 (formerly ASP.NET 5 or “vNext”) is the latest version of ASP.NET. Instead of building incrementally on ASP.NET 4, Microsoft opted to do a full rewrite of the ASP.NET stack. The end result is a leaner and more modular framework than ever before.
What’s changed? For starters, MVC and Web API have been unified into a single pipeline. Dependency injection is provided out of the box. And, most exciting of all, ASP.NET is now cross-platform!
Not only does this mean native hosting on Linux (woot!), but the modular design of the framework gives you more flexibility to use exactly the components that you want. Like Entity Framework but don’t want to use SQL Server? Not a problem! Not a fan of IIS? Kestrel is blazingly fast and works great with nginx.
How about an application with full-fledged user authentication, no database required? In this tutorial, you’ll learn how to scaffold a basic ASP.NET Core MVC application and plug in Stormpath user authentication with two lines of code.
Let’s get started.
What is Stormpath?
Stormpath is an API service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications.
Our API enables you to:
- Authenticate and authorize your users
- Store data about your users
- Perform password and social-based login
- Send password reset messages
- Issue API keys for API-based web apps
- And much more! (Check out our Product Documentation.)
In short: we make user account management a lot easier, more secure, and more scalable than what you’re probably used to.
Ready to get started? Register for a free developer account here.
Creating a New ASP.NET Core Project
First, create a new project using the ASP.NET Core template in Visual Studio.
- Click on File – New Project.
- Under Visual C# – Web, pick the ASP.NET Web Application template.
- On the New ASP.NET Project dialog, pick the Web Application template under ASP.NET 5 Templates.
- Click Change Authentication and pick No Authentication. You’ll be adding it yourself!
Creating a New Project Without Visual Studio
There isn’t currently a way to scaffold a new web project from the command line, so I set up an empty seed project you can copy or clone:
git clone https://github.com/nbarbettini/dotnet-new-web.git
cd dotnet-new-web/src/WebApplication
dotnet restore
Get Your API Credentials
Your ASP.NET application will need a few pieces of information in order to communicate with Stormpath:
- Stormpath API Key ID and Secret
- Stormpath Application URL (href)
The best way to provide these is through environment variables. You can also hardcode the values into your application code, but we recommend environment variables as a best practice for security.
To save the Stormpath credentials (and Application URL) as environment variables, follow these steps:
- If you haven’t registered for Stormpath, create a free developer account.
- Log in to the Admin Console and use the Developer Tools section on the right side of the page to create and download an API key file.
- Open the
apiKey.properties
file up in Notepad (or your favorite editor). Using the command line (or PowerShell), execute these commands:
setx STORMPATH_CLIENT_APIKEY_ID "value_from_properties_file"
setx STORMPATH_CLIENT_APIKEY_SECRET "value_from_properties_file"
If you're on a non-Windows platform, the bash commands are:
export STORMPATH_CLIENT_APIKEY_ID=value from properties file
export STORMPATH_CLIENT_APIKEY_SECRET=value_from_properties_file
Install the Stormpath ASP.NET Core Middleware
This part’s easy! The Stormpath.AspNetCore NuGet package contains everything you need to use Stormpath from your application. Install it using the NuGet Package Manager, or from the Package Manager Console:
PM> install-package Stormpath.AspNetCore
If you’re not using Visual Studio, simply edit the project.json
file and add this line to the dependencies
group:
"Stormpath.AspNetCore": "*"
Then, run dotnet restore
on the command line to download the package.
Add Stormpath to Startup.cs
At the top of your Startup.cs
file, add this line:
using Stormpath.AspNetCore;
Next, add Stormpath to your services collection in ConfigureServices()
:
public void ConfigureServices(IServiceCollection services)
{
services.AddStormpath();
// Other service code here
}
Finally, inject Stormpath into your middleware pipeline in Configure()
:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Logging and static file middleware here (if applicable)
app.UseStormpath();
// MVC or other framework middleware here
}
Note: Make sure you add Stormpath before other middleware you want to protect, such as MVC.
With only two lines of code, the Stormpath middleware will automatically handle registration, login, logout, password reset, and email verification. Pretty cool! By default, this functionality is exposed on the /register
, /login
routes (and so on).
Customizing the Default View
When a user logs in, the Stormpath middleware will set Context.User
automatically. You can use the IsAuthenticated
property in your views to show different content depending on whether the user is logged in.
In your Views/Shared/_Layout.cshtml
file, replace the existing navbar with one that will update when a user logs in:
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a>Home</a></li>
<li><a>About</a></li>
<li><a>Contact</a></li>
</ul>
@if (Context.User.Identity.IsAuthenticated)
{
<form id="logout_form" action="/logout" method="post">
<ul class="nav navbar-nav navbar-right">
<li>
<p class="navbar-text">Hello, <b>@Context.User.Identity.Name</b></p>
</li>
<li><a style="cursor: pointer;">Log Out</a></li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a href="/login">Log In or Register</a></li>
</ul>
}
</div>
Bask in the Glory of Easy ASP.NET Core Authentication
Time to try it out!
- Fire up your application and open it in a browser.
- Click the Log In or Register link in the navbar. You’ll be redirected to the default Stormpath login view.
- Click Create an Account and fill out the form. Enter the same credentials in the login form to log in with the new account.
- You’ll be redirected back to your application. Check the navbar. You’re logged in!
- Log out again. Easy as pie.
Updating the navbar is cool, but what about protecting access to controllers that only your logged-in users should use? You’re in luck…
Add an MVC Controller Secured by Stormpath
The Stormpath middleware plugs right into the ASP.NET authentication system, which means you can use the [Authorize]
attribute to protect your routes and actions with ease. To demonstrate, add a new MVC controller to allow logged-in users to view their profile:
Create a new file in the Controllers folder called ProfileController.cs
. Paste this code into the new file (you may need to tweak the namespace to match the rest of your code):
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
[Authorize]
public class ProfileController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
}
}
Next, create a new folder under Views called Profile. Create a new file called Index.cshtml
and use the @inject
directive to get the Stormpath IAccount
object for the logged-in user:
@* The logged in Stormpath user can be injected into the view *@
@inject Stormpath.SDK.Account.IAccount Account
<h2>Manage Profile</h2>
<p>This route is <b>protected</b> and cannot be accessed unless you are logged in.</p>
<h3>Account Details</h3>
<p><b>Username:</b> @Account.Username</p>
<p><b>Email:</b> @Account.Email</p>
<p><b>Full Name:</b> @Account.FullName</p>
<p><b>First:</b> @Account.GivenName</p>
<p><b>Last:</b> @Account.Surname</p>
<p><b>ID:</b> @Account.Href</p>
Run your application again, and ensure that you are logged out.
Try accessing /profile
. You’ll be redirected to the login page. When you log in, you’ll automatically be redirected to the Profile view. Awesome!
Go Forth and Code
As you’ve seen, Stormpath makes it super simple to add authentication to an ASP.NET Core application with only a few lines of code. The middleware and dependency injection patterns used in ASP.NET Core are powerful and can be used to build complex applications very efficiently. And, everything is portable across Windows, Linux, and Mac!
If you want to learn more, check out these resources:
- Example ASP.NET Core application
- Stormpath ASP.NET Core documentation
- Stormpath REST API documentation
Of course, feel free to grab the full code for this project and play around with it. If you have any questions, leave me a comment!
Published at DZone with permission of Nate Barbettini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments