0% found this document useful (0 votes)
2 views

Task-13

The document outlines the steps to create an ASP.NET Core MVC project, including setting up session management and authentication. It provides code snippets for configuring the application, creating a login view, and implementing an account controller for handling user login and logout. Additionally, it demonstrates how to display the username on a dashboard and secure the dashboard with authorization attributes.

Uploaded by

vishalsandhan178
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Task-13

The document outlines the steps to create an ASP.NET Core MVC project, including setting up session management and authentication. It provides code snippets for configuring the application, creating a login view, and implementing an account controller for handling user login and logout. Additionally, it demonstrates how to display the username on a dashboard and secure the dashboard with authorization attributes.

Uploaded by

vishalsandhan178
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Task -13

Name: Siddhant Kiran Shahane


Reg. No.: wlgetl3dot001
University Name: D Y Patil College of Engineering
Email: [email protected]
Contact: 8446539240
Level: 3
Subject Name: Dot-net
1: Create an ASP.NET Core MVC Project

2: Configure Session in Program.cs


using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});

// Register authentication with the correct scheme name "Cookies"


builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationSch
eme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/Account/Login"; // Redirect to login page if not
authenticated
options.AccessDeniedPath = "/Account/AccessDenied";
});

builder.Services.AddAuthorization(); // Add authorization services

var app = builder.Build();

app.UseSession();
app.UseRouting();

app.UseAuthentication(); // Must come before UseAuthorization


app.UseAuthorization(); // Must come after UseAuthentication
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});

app.Run();

3: Create Login View (Views/Account/Login.cshtml)

This form allows users to log in.

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Login</h2>

<form method="post" asp-controller="Account" asp-action="Login">


<div>
<label>Username</label>
<input type="text" name="Username" required />
</div>
<div>
<label>Password</label>
<input type="password" name="Password" required />
</div>
<button type="submit">Login</button>
</form>
4: Create Account Controller (Controllers/AccountController.cs)

This controller will handle login logic and store the session.

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Threading.Tasks;

public class AccountController : Controller


{
public IActionResult Login()
{
return View();
}

[HttpPost]
public async Task<IActionResult> Login(string Username, string Password)
{
// Dummy authentication logic (replace with actual database validation)
if (Username == "admin" && Password == "password")
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, Username)
};

var claimsIdentity = new ClaimsIdentity(claims,


CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
IsPersistent = true // Remember the user
};

// Ensure the scheme is "Cookies"


await
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return RedirectToAction("Dashboard", "Home");
}

ViewBag.Message = "Invalid credentials!";


return View();
}

public async Task<IActionResult> Logout()


{
await
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login");
}

public IActionResult AccessDenied()


{
return View();
}
}
5: Display Username in Dashboard (Views/Home/Dashboard.cshtml)
@using System.Security.Claims
@{
Layout = "~/Views/Shared/_Layout.cshtml";
var username = User.Identity.Name;
}

<h2>Dashboard</h2>

@if (!string.IsNullOrEmpty(username))
{
<p>Welcome, @username!</p>
<a asp-controller="Account" asp-action="Logout">Logout</a>
}
else
{
<p>Please <a asp-controller="Account" asp-action="Login">login</a>.</p>
}
6: Apply [Authorize] to Secure the Dashboard

Modify HomeController.cs to prevent unauthenticated access.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller


{
[Authorize]
public IActionResult Dashboard()
{
return View();
}
}

Final Output:

You might also like