Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
Kenneth Fung
Published

SIT331 Basic Authentication and Authorization teaching case

This it is part of assignment submitted to Deakin University, School of IT, Unit SIT331 - Full Stack Development Secure Backend Services.

BeginnerFull instructions providedOver 1 day34
SIT331 Basic Authentication and Authorization teaching case

Things used in this project

Software apps and online services

Visual Studio 2017
Microsoft Visual Studio 2017

Story

Read more

Schematics

cover_o3NPktFfp1.jpg

Code

Login.cs

C#
namespace robot_controller_api
{
    public class Login
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }
}

User.cs

C#
namespace robot_controller_api
{
    public class User
    {
        public int Id { get; set; }
        public string Email { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PasswordHash { get; set; }
        public string Description { get; set; }
        public string Role { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime ModifiedDate { get; set; }

        // Add a parameterless constructor
        public User() { }

        // Existing constructor
        public User(int id, string email, string firstName, string lastName, string passwordHash, string description, string role, DateTime createdDate, DateTime modifiedDate)
        {
            Id = id;
            Email = email;
            FirstName = firstName;
            LastName = lastName;
            PasswordHash = passwordHash;
            Description = description;
            Role = role;
            CreatedDate = createdDate;
            ModifiedDate = modifiedDate;
        }
    }
}

Program.cs

C#
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Authentication;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.Security.Claims;
using robot_controller_api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers(options =>
{
    // Define a global authorization policy that requires all users to be authenticated.
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    // Add the global authorization policy as a filter to all controllers.
    options.Filters.Add(new AuthorizeFilter(policy));
});
builder.Services.AddAuthentication("BasicAuthentication").AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy =>
        policy.RequireClaim(ClaimTypes.Role, "Admin"));
    options.AddPolicy("UserOnly", policy =>
        policy.RequireClaim(ClaimTypes.Role, "User", "Admin"));
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Robot Controller API",
        Description = "New backend service that provides resources for the Moon robot simulator.",
        Contact = new OpenApiContact
        {
            Name = "Kenneth",
            Email = "s222575621@deakin.edu.au"
        },
    });
});

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.MapControllers();
app.UseSwagger();
app.UseSwaggerUI(c => c.InjectStylesheet("/styles/theme-flattop.css"));
app.UseStaticFiles();

app.Run();

Credits

Kenneth Fung
3 projects • 0 followers
Contact

Comments

Please log in or sign up to comment.