Skip to content

ASP.NET MVC Tutorial

Dylan Plecki edited this page Jan 15, 2016 · 4 revisions
  1. Create a new project/solution of the ASP.NET Web Application project type. When the ASP.NET wizard comes up, select the MVC website template for ASP.NET 4.5, and change the authentication type to No Authentication.
  2. Go to the project's NuGet Package Manager and update all required packages, and then install the following packages:
    • Owin.Security.Keycloak
    • Microsoft.Owin.Host.SystemWeb
    • Microsoft.Owin.Security.Cookies
  3. Create a new C# class in the root of the project called Startup.cs, and paste the following code into it, taking note to change the namespace to your project's default namespace, change the authentication type names to match your project, and to enter your own KeycloakUrl, Realm, ClientId, and ClientSecret:
    using Microsoft.Owin;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Cookies;
    using Owin;
    using Owin.Security.Keycloak;
    
    [assembly: OwinStartup(typeof(KeycloakOwinAuthenticationSample.Startup))]
    
    namespace KeycloakOwinAuthenticationSample
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                // Name of the persistent authentication middleware for lookup
                const string persistentAuthType = "KeycloakOwinAuthenticationSample_cookie_auth";
        
                // --- Cookie Authentication Middleware - Persists user sessions between requests
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = persistentAuthType
                });
                app.SetDefaultSignInAsAuthenticationType(persistentAuthType); // Cookie is primary session store
        
                // --- Keycloak Authentication Middleware - Connects to central Keycloak database
                app.UseKeycloakAuthentication(new KeycloakAuthenticationOptions
                {
                    // App-Specific Settings
                    ClientId = "KeycloakOwinAuthenticationSample", // *Required*
                    ClientSecret = "98dc575e-2892-46f7-ae53-78018e4352de", // If using public authentication, delete this line
                    VirtualDirectory = "", // Set this if you use a virtual directory when deploying to IIS
        
                    // Instance-Specific Settings
                    Realm = "master", // Don't change this unless told to do so
                    KeycloakUrl = "https://33.0.0.101/auth", // Enter your Keycloak URL here
        
                    // Template-Specific Settings
                    SignInAsAuthenticationType = persistentAuthType, // Sets the above cookie with the Keycloak data
                    AuthenticationType = "KeycloakOwinAuthenticationSample_keycloak_auth", // Unique identifier for the auth middleware
                });
            }
        }
    }
  4. Go to your Keycloak server in your browser and login as realm admin. Create a new client for your sample MVC application, and set the Valid Redirect URIs portion to either your web application's URL followed by a backslash and star (i.e. http://localhost:5000/*) or just enter the wildcard character (*). Make sure the client uses the Confidential authentication type.
  5. Open the Controllers/HomeController.cs file in Visual Studio, and edit the About() method to the following (you'll have to include the System.Security.Claims namespace at the top):
    [Authorize]
    public ActionResult About()
    {
        	ViewBag.Message = "Your application description page.";
    
        	var userPrinciple = User as ClaimsPrincipal;
    
        return View(userPrinciple);
    }
  6. To enable viewing of all claims from Keycloak, edit the Views/Home/About.cshtml file and paste the following code (as to overwrite the entire file):
    @{
        ViewBag.Title = "About";
    }
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
    
    @model System.Security.Claims.ClaimsPrincipal
    
    <dl>
        @foreach (var claim in Model.Claims)
        {
            <dt>@claim.Type</dt>
            <dd>@claim.Value</dd>
        }
    </dl>
  7. Run the application! If you click on the About tab on the navigation bar, you should be redirected to your Keycloak server for authentication, and then returned to the About page which will then display all of the claims that Keycloak sent to your application.
You can’t perform that action at this time.