setting an asp variable via java script

i have an aspx.cs page:

i have an aspx.cs page:

public partial class multiIndex : System.Web.UI.Page
{
public string Link = "";
public string board = "";
public string against = "";

protected void Page_Load(object sender, EventArgs e)
{
}

}

and an aspx page and in it a script and this code:

<script>
var newBoard = "<%=board%>";
<%UpdateDataBase(board)%>
</script>

now this is working but i can't use it in reverse:

var board = "something";
<%board=%>= board;
<%UpdateDataBase(board)%>

so how do i do such a thing without php or any other libarary like node.js, i want to keep it simple

Goodbye Javascript! Build an Authenticated Web App in C# with Blazor + ASP.NET Core 3.0

Goodbye Javascript! Build an Authenticated Web App in C# with Blazor + ASP.NET Core 3.0

In this post, you'll see why we say goodbye JavaScript and how to build an Authenticated Web App in C# with Blazor and ASP.NET Core 3.0

Curious what the experience would be like to trade in Javascript for C# on the front end? You are about to find out!

Table of Contents

  • Build a Basic Website with ASP.NET Core 3.0 + Blazor
  • Add User Authentication your Blazor Web App
  • Set Up Your Okta Account to handle the ASP.NET Core 3.0 Blazor App
  • Configure Your Blazor App to use Okta as the External Auth Provider
  • Add User Login to your Blazor Web App UI
  • Test Okta Registration and Login for Your Blazor App

For many years, Javascript (and it’s child frameworks) have had their run of the DOM (Document Object Model) in a browser, and it took having that scripting knowledge to really manipulate client-side UI. About 2 years ago, all of that changed with the introduction of Web Assembly - which allows compiled languages to be interpreted client-side and is fully supported across all browsers now. Microsoft’s answer to this was the creation of Blazor. Allowing C# developers to build their entire stack in .NET, including UI, was an exciting proposition. For some time Blazor has been in preview but is now included as a general release on September 23rd, 2019 along with the next iteration of .NET Core - version 3.0.

In order to build with Blazor and ASP.NET Core 3.0, you need the following prerequisites installed and ready to go:

Build a Basic Website with ASP.NET Core 3.0 + Blazor

Now that you have your dev environment handy, let’s get familiar with what a basic website walkthrough would be like. There are two ways you can utilize this technology: client-side or server-side Blazor. For this example, the server-side option is the best choice for stability, as client-side Blazor is still new and working on the final release. Stay tuned for that implementation!

First, you’ll need to create a Blazor project. To get the latest Blazor project templates to work with Visual Studio or VS Code, simply install them from the command line/terminal from your base repo directory:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview9.19424.4

Visual Studio (16.3 or later) will detect that the templates have been installed and surface them to you without the need for any additional extensions. Now it’s time to scaffold your new project. From your parent directory of code repositories, execute the following command:

dotnet new blazorserver -o OktaBlazorAspNetCoreServerSide

Once it’s been run, open up the OktaBlazorAspNetCoreServerSide folder in Visual Studio Code. Once loaded, if you look in the bottom right-hand corner of the IDE you will see a permission request to add assets to the build. Select Yes.

Now that everything has been loaded up, return to your command line/terminal and run the project.

dotnet run

Launch your browser of choice and navigate to https://localhost:5001. You should see a templated website.

Add User Authentication your Blazor Web App

ASP.NET Core 3.0 has brought along with it some hefty changes to the libraries and dependencies from previous versions of .NET Core. To get started with using an external OAuth provider, like Okta, there is a NuGet package you need to add to the project. Fire up your command line/terminal window in VS Code and add the Okta .NET SDK:

dotnet add package Okta.Sdk --version 1.4.0

In 3.0, ASP.NET Core ships as part of the .NET Core shared framework. The metapackage that was used for 2.x apps is no longer used. The first line of your project file that references the Web SDK is what pulls in the shared assemblies for ASP.NET Core.

For user authentication with OAuth, there is an additional layer of information you will use, called Open ID Connect (OIDC). While much of handling authentication is baked into the new 3.0 framework, OIDC is not included, so you’ll need to add a quick reference to that.

dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect --version 3.0.0-preview9.19424.4

Authentication works by redirecting users to the Okta website, where they will log in with their credentials, and then be returned to your site via the URL you will configure in the next section. Add the following code to the very top of your appsettings.json file, inside of the first brackets, and separate it from the rest of the settings by adding a comma after it.

"Okta": {
   "Issuer": "https://okta.okta.com/oauth2/default",
   "ClientId": "{yourClientId}",
   "ClientSecret": "{yourClientSecret}"
 }

Your file should look like this:

Just to make sure everything still can run, go ahead and execute dotnet run again.

Set Up Your Okta Account to handle the ASP.NET Core 3.0 Blazor App

Execute the following steps to configure Okta so that users can register themselves for an account.

  1. From the Administrative Dashboard, hover over Users and click Registration
  2. Click Enable Registration
  3. Save the changes

Once you have access to your account you can proceed to the Dashboard using a link like the one below: https://okta.okta.com/admin/dashboard

On the Dashboard, click Applications in the main menu and on the Application screen, click Add Application. Then select Web and click Next.

On the Create New Application screen, set the following values:

Click Done, then click Edit next to General Settings on your newly created Okta app. Edit the following values: Logout redirect URIs: https://localhost:5001/signout-callback-oidc Initiate login URI: https://localhost:5001/authorization-code/callback

Once you’ve saved those values, scroll down and take note of the ClientID and ClientSecret.

ClientId refers to the client ID of the Okta application ClientSecret refers to the client secret of the Okta application Issuer will need the text {yourOktaDomain} replaced with your Okta domain, found at the top-right of the Dashboard page.

You will use your Okta account settings to update those values in the appsettings.json file in your project. For an even more secure way to store those values

Configure Your Blazor App to use Okta as the External Auth Provider

Great! Now that Okta has been configured and is ready to go, there are a few changes that need to be made to the application startup.

Add these using statements to your Startup.cs file:

using Microsoft.AspNetCore.Authentication.OpenIdConnect; 
using Microsoft.AspNetCore.Authentication.Cookies; 
using Microsoft.IdentityModel.Tokens;

Replace all the code in the ConfigureServices method with the code below.

public void ConfigureServices(IServiceCollection services)
{
   services.AddRazorPages();
   services.AddServerSideBlazor();
   services.AddSingleton<WeatherForecastService>();
   services.AddAuthorizationCore();
   services.AddAuthentication(sharedOptions =>
   {
       sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
       sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
       sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
   })
   .AddCookie()
   .AddOpenIdConnect(options =>
   {
       options.ClientId = Configuration["okta:ClientId"];
       options.ClientSecret = Configuration["okta:ClientSecret"];
       options.Authority = Configuration["okta:Issuer"];
       options.CallbackPath = "/authorization-code/callback";
       options.ResponseType = "code";
       options.SaveTokens = true;
       options.UseTokenLifetime = false;
       options.GetClaimsFromUserInfoEndpoint = true;
       options.Scope.Add("openid");
       options.Scope.Add("profile");
       options.TokenValidationParameters = new TokenValidationParameters
       {
           NameClaimType = "name"
       };
   });
}

ASP.NET Core 3.0 has new options to configure the services in this file. UseAuthorization has been newly added to 3.0 project templates.

In the Configure() method of your Startup.cs file add this line just before the app.UseEndpoints() method:

app.UseAuthentication();
app.UseAuthorization();

In this example, you'll see there's a new UseEndpoints method in Startup.cs. This is what enables the new endpoint routing system in ASP.NET Core. All 3.0 project templates use that now. Think of this as a more performant routing system.

Add User Login to your Blazor Web App UI

Time to add some user personalization to this app! Open Shared/MainLayout.razor and add the following HTML right before the About link.

<AuthorizeView>
<Authorized>
           <a href="Identity/Account/Manage">Hello, @context.User.Identity.Name!</a>
           <a href="Identity/Account/LogOut">Log out</a>
   </Authorized>
   <NotAuthorized>
           <a href="Identity/Account/Register">Register</a>
           <a href="Identity/Account/Login">Log in</a>
   </NotAuthorized>
</AuthorizeView>

Using <AuthorizeView> is the easiest way to access authentication data, and is useful when you need to display a user’s name. The <AuthorizeView> component exposes a context variable of type AuthenticationState. In order to add this state to our app, open App.razor and wrap the HTML you see with <CascadingAuthenticationState> tags at the parent level. It should look like this:

<CascadingAuthenticationState>
   <Router AppAssembly="@typeof(Program).Assembly">
       ...
   </Router>
</CascadingAuthenticationState>

Test Okta Registration and Login for Your Blazor App

That’s it! To test it out, go back to the command line/terminal and execute dotnet run.

Then navigate to http://localhost:5001 in your browser. Click Login and you should be redirected to the Okta Sign-In Page.

Because you configured your Okta org for self-registration, there should be an option at the bottom of the widget to allow users to register for a new account.

Now you have a website with a working login and user registration form. Your website also allows users to recover lost passwords. By repeating these steps you can create a network of tools that your users can access all with the same login.

All of that and not one line of Javascript. The future is looking bright for C#, give it a go with Blazor!

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

Blazor CRUD Using Google Cloud Firestore

Build amazing web apps with ASP.NET Core 3.0

Create a desktop app with Electron, React and C#

Originally published at https://developer.okta.com



Using Parcel.js in an ASP.NET Core Application

Using Parcel.js in an ASP.NET Core Application

In this post, we’re going to take an ASP.NET website template that uses Bootstrap 4 and set it up to use Parcel-generated bundles instead.

In this post, we’re going to take an ASP.NET website template that uses Bootstrap 4 and set it up to use Parcel-generated bundles instead.

Parcel.js is a “Blazing fast, zero configuration web application bundler.” In this post, we’re going to take an ASP.NET Core website template that uses Bootstrap 4 and set it up to use Parcel-generated bundles instead.

ASP.NET Core supports bundling and minifying static assets at design-time using the community supported BuildBundlerMinifier package that can be configured in a bundleconfig.json file. However it’s not well suited for scenarios that would benefit from a deploy-time bundling strategy, i.e. assets are built during deployment and output files are not checked in.

This is where Parcel.js comes in. Parcel is a “Blazing fast, zero configuration web application bundler.” The zero-configuration bit is its major selling point because it allows you to get started with minimal effort.

In this post, we’re going to take an ASP.NET website template that uses Bootstrap 4 and set it up to use Parcel-generated bundles instead.

Create & Set Up a New ASP.NET Project

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	{
  "name": "aspnet-parcel-exp",
  "private": true,
  "version": "0.1.0"
}


  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
javascriptnpm install --save-dev [email protected]

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
npm install [email protected]
npm install [email protected]
npm install [email protected]
npm install [email protected]
npm install [email protected]

If everything went right, your package.json should look something like this:

{
  "name": "aspnet-parcel-exp",
  "private": true,
  "version": "0.1.0",
  "devDependencies": {
    "parcel-bundler": "^1.11.0"
  },
  "dependencies": {
    "bootstrap": "^4.2.1",
    "jquery": "^3.3.1",
    "jquery-validation": "^1.19.0",
    "jquery-validation-unobtrusive": "^3.2.11",
    "popper.js": "^1.14.7"
  }
}


Set Up an Asset Bundle Using Parcel.js

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	/AspNetParcelExp/ # project root
  - .sassrc       # sass configuration
  - assets/       # front end assets root
    - scss/       # Place for all styles
      - site.scss
    - js/         # Place for all scripts
      - site.js
    - bundle.js   # Entry point for our output bundle


  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
// Import styles  
import './scss/site.scss'  

// Setup jquery
import $ from 'jquery'
window.$ = window.jQuery = $

// Import other scripts
import 'bootstrap'  
import 'jquery-validation'  
import 'jquery-validation-unobtrusive'  

import './js/site'


We import everything we depend on. ‘bootstrap’ for example refers to the …/node_modules/bootstrap/ folder. If you want to import a specific file from a package only, you may do that too. The above code should be straightforward, except for maybe jQuery, which I’ll explain in a bit.

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	{
  "includePaths": [
    "./node_modules/"
  ]
}


This will allow referencing package folders without a full path to it. See parcel-bundler/parcel#39 for more information.

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	@import "~bootstrap/scss/bootstrap";


You may also just include the bootstrap SCSS files that you actually need to keep the output size down. Since we’re trying to replicate the template, we could also paste the code in the original template’s site.css here after the line.

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	"scripts": {
  "build": "parcel build assets/bundle.js --out-dir wwwroot/dist/",
  "watch": "parcel watch assets/bundle.js --out-dir wwwroot/dist/"
},

This adds scripts that can be invoked as npm run build to build, for example. It passes the bundle.js entry point to Parcel, and instructs it to generate output files in the wwwroot/dist/ using the --out-dir option.

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
npm run build

You should now see a bundle.css, bundle.js and a bundle.map file in the wwwroot/dist directory (the directory we specified for the build script above). It’s a good idea to ignore the wwwroot/dist from version control.

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	<script src="~/dist/bundle.js" 
        asp-append-version="true"></script>
 	And replace the stylesheet <link> tags with:
 	<link rel="stylesheet" 
      href="~/dist/bundle.css" 
      asp-append-version="true" />


That’s it. If you did everything right, running the program should display the same output as with the old files.

If it feels like a lot of work, it’s probably because you aren’t familiar with the npm, SCSS, etc., so take your time.

Watching Changes

Rather than running npm run build each time you make changes, you can use HMR (Hot Module Replacement), which will detect pages and reload for you, so that you don’t have to do it.

Open a new terminal instance and run npm run watch. Keep this running while performing any dev changes — it’ll speed you up.

Add a Pre-Publish Task

Add the following to the AspNetParcelExp.csproj file right before the closing

</Project> tag:
<Target Name="ParcelBeforePublish" 
        BeforeTargets="PrepareForPublish">
  <Exec Command="npm run build" />
</Target>


Now, every time you create a publish package, it will run the npm build script. This is particularly important in Continuous Delivery scenarios, because the wwwroot/dist is (usually) not under version control, and the build environment needs to build the files before deploying. You may test this step using dotnet publish: you’ll see output from parcel-bundler.

If you want the task to be run every time is the project is built, change PrepareForPublish to BeforeBuild.

A Note on CommonJS Modules

The parcel-bundler generates a CommonJS module, which means it doesn’t pollute the global window object. Now this can be a problem sometimes, because some libraries — particularly the old ones — have always been polluting window.

Take jQuery for instance. Libraries that require jQuery perform a test on the window object to check if it’s got a jQuery or a $ property. Since CommonJS libraries don’t pollute window, these checks will fail. So we’ll need to manually pollute the window object ourselves. We did that for jquery in bundle.js using:

import $ from 'jquery'
window.$ = window.jQuery = $

This is one thing you need to remember when using Parcel.js or other similar bundlers.

A few pointers and ideas

  • You do not have to use SCSS. LESS or even plain CSS is completely fine.
  • Parcel.js doesn’t have a config file of its own, unlike Grunt or webpack. You may, however, have config files for each tool, and parcel-bundler will honor them. E.g. tsconfig.json for typescript, .sassrc for SCSS, etc.
  • Parce.js has built-in support for PostCSS. For example, to automatically add CSS prefixes to the generated output using the autoprefixer-postcss plugin, add the following to .postcssrc at the project root:
 	{ 
  "plugins": { 
    "autoprefixer": true 
  } 
}


  • You do not have to use SCSS. LESS or even plain CSS is completely fine.
  • Parcel.js doesn’t have a config file of its own, unlike Grunt or webpack. You may, however, have config files for each tool, and parcel-bundler will honor them. E.g. tsconfig.json for typescript, .sassrc for SCSS, etc.
  • Parce.js has built-in support for PostCSS. For example, to automatically add CSS prefixes to the generated output using the autoprefixer-postcss plugin, add the following to .postcssrc at the project root:

Create Login and Registration in Your ASP.NET Core MVC App

Create Login and Registration in Your ASP.NET Core MVC App

This tutorial walks you through setting up login and registration with ASP.NET Core MVC. In this tutorial, you learned how to add authentication to your ASP.NET Core MVC app and allow users to register for a new account.

This tutorial walks you through setting up login and registration with ASP.NET Core MVC. In this tutorial, you learned how to add authentication to your ASP.NET Core MVC app and allow users to register for a new account.

User authentication and authorization are common features in web applications, but building these mechanics has the potential to take a lot of time. Doing so requires setting up persistent storage for user information (in some type of database) and paying keen attention to potential security issues around sensitive operations like hashing passwords, password reset workflows, etc. - weeks of development time begin to add up before we ever get to the functionality that delivers value to your users.

In this post, we’ll walk through how Okta simplifies this process for us and set up a simple integration for an ASP.NET Core MVC app using the Okta NuGet package. We’ll build functionality for users to register for new accounts and login with their Okta credentials.

Scaffold Your ASP.NET Project

To follow along with this tutorial start by creating a new app in the console:

mkdir MyOktaProject
cd MyOktaProject
dotnet new mvc


Configure User Registration

If you don’t already have one, you’ll need to create an Okta developer account. Doing so will give you a URL for your organization called an “Okta domain”. It will also allow you to create your login credentials for accessing the Okta dashboard.

Upon submission of this form, you will receive an email Okta with instructions to obtain your credentials and complete your registration.

Execute the following steps to configure Okta so that users can register themselves for an account.

  1. From the Administrative Dashboard, hover over Users and click Registration
  2. Click Enable Registration
  3. Save the changes

Configure Basic User Authentication

Once you have access to your account you can proceed to the Dashboard using a link like the one below:

<span

class="okta-preview-domain">https://{yourOktaDomain}/admin/dashboard

On the Dashboard, click Applications in the main menu and on the Application screen, click Add Application.

Select Web then click Next.

On the Create New Application screen, set the following values:

Click Done, then click Edit next to General Settings on your newly created Okta app. Edit the following values:

Logout redirect URIs: https://localhost:5001/signout-callback-oidc

Initiate login URI: https://localhost:5001/authorization-code/callback

Add .NET Authentication Dependencies

Once your account is set up you need to add the Okta.Sdk library to your project. This post will take the approach of using the NuGet package, but the Github repository for Okta.AspNetCore can be found here.

To proceed simply search for the latest version of the Okta.Sdk NuGet package in your IDE of choice (version 1.2.0 at the time of this publication) and install it. If you’re using Visual Studio you can do this by right-clicking on the project in the solution explorer and selecting Manage NuGet Packages. For those of you not using Visual Studio, add the package via console window using the following command:

dotnet add package Okta.Sdk --version 1.2.0


Configure Your ASP.NET App for Login

Authentication works by redirecting users to the Okta website, where they will log in with their credentials, and then be returned to your site via the URL you configured above.

Add the following code to your appsettings.json file:

  "Okta": {
    "Issuer": "https://{yourOktaDomain}/oauth2/default",
    "ClientId": "{yourClientId}",
    "ClientSecret": "{yourClientSecret}"
  }


You can find each of the actual values needed to replace the settings in the config above in the following places:

ClientId refers to the client ID of the Okta application ClientSecret refers to the client secret of the Okta application Issuer will need the text {yourOktaDomain} replaced with your Okta domain, found at the top-right of the Dashboard page

Add some using statements to your Startup.cs file:

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;


Add the following code to the top of the ConfigureServices method in your Startup.cs file:

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.ClientId = Configuration["okta:ClientId"];
        options.ClientSecret = Configuration["okta:ClientSecret"];
        options.Authority = Configuration["okta:Issuer"];
        options.CallbackPath = "/authorization-code/callback";
        options.ResponseType = "code";
        options.SaveTokens = true;
        options.UseTokenLifetime = false;
        options.GetClaimsFromUserInfoEndpoint = true;
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name"
        };
    });


In the Configure() method of your Startup.cs file add this line just before the app.UseMvc() method:

app.UseAuthentication();


Add the following MeViewModel to the Models directory:

using System.Collections.Generic;

namespace OktaAspNetCoreMvc.Models
{
    public class MeViewModel
    {
        public string Username { get; set; }

        public bool SdkAvailable { get; set; }

        public dynamic UserInfo { get; set; }

        public IEnumerable<string> Groups { get; set; }
    }
}


Add Login to Your ASP.NET App

Now that all the configuration and plumbing is done, you’re ready to add the code that will actually log users into your application.

Add the following AccountController to the Controller directory.

The controller exposes the Login() action. If the user has already been authenticated, the Login() action will redirect them to the home page. Otherwise, it will redirect them to the Okta login screen.

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc;
using Okta.Sdk;

namespace OktaAspNetCoreMvc.Controllers
{
    public class AccountController : Controller
    {
        private readonly IOktaClient _oktaClient;

        public AccountController(IOktaClient oktaClient = null)
        {
            _oktaClient = oktaClient;
        }

        public IActionResult Login()
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return Challenge(OpenIdConnectDefaults.AuthenticationScheme);
            }

            return RedirectToAction("Index", "Home");
        }
    }
}


Add the following code to your _Layout.cshtml file, just below the main menu to add the login button, or a welcome message, based on the current user’s status.:

   @if (User.Identity.IsAuthenticated)
    {
        <ul class="nav navbar-nav navbar-right">
            <li><p class="navbar-text">Hello, @User.Identity.Name</p></li>
        </ul>
    }
    else
    {
        <ul class="nav navbar-nav navbar-right">
            <li><a asp-controller="Account" asp-action="Login">Log in</a></li>
        </ul>
    }


For information on user authorization using Okta groups check out Lee Brandt’s article on user authorization in ASP.NET Core with Okta.

Register Users

If you following the instructions above to enable self-service registration the “Don’t have an account? Sign Up” message will appear at the bottom of the login form. In the next step, you’ll run the application.

Log In Using ASP.NET

That’s it! To run your solution open up a terminal and enter the following command:

dotnet run


Then navigate to http://localhost:5001 in your browser and enjoy!

The source code for this tutorial is available on GitHub.

Now you have a website with a working login and user registration form. Your website also allows users to recover lost passwords. By repeating these steps you can create a network of tools that your users can access all with the same login.

Learn More

The Complete ASP.NET MVC 5 Course

Build a Real-world App with ASP.NET Core and Angular 2 (4+)

ASP NET Core (ASP.NET 5),MVC 6,C#,Angular2 & EF Crash Course

Rest Api’s in Asp.Net and C#

Hands on ASP .Net Core 2