Skip to content

Commit 349246c

Browse files
Blog-977327 - Adding sample for Role based annotation.
1 parent 32a08b5 commit 349246c

File tree

11 files changed

+243
-0
lines changed

11 files changed

+243
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net8.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
11+
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
12+
</ItemGroup>
13+
14+
</Project>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<PropertyGroup>
4+
<ActiveDebugProfile>IIS Express</ActiveDebugProfile>
5+
<Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
6+
<Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
7+
</PropertyGroup>
8+
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
9+
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
10+
</PropertyGroup>
11+
</Project>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 17
4+
VisualStudioVersion = 17.9.34723.18
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AuthenticationService", "AuthenticationService.csproj", "{7FC0F7C8-6F5B-4FDC-B22E-55CD333E0FA0}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{7FC0F7C8-6F5B-4FDC-B22E-55CD333E0FA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{7FC0F7C8-6F5B-4FDC-B22E-55CD333E0FA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{7FC0F7C8-6F5B-4FDC-B22E-55CD333E0FA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{7FC0F7C8-6F5B-4FDC-B22E-55CD333E0FA0}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {7D63024A-BC8C-4438-AC15-FBD2D739D9FC}
24+
EndGlobalSection
25+
EndGlobal
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
using AuthenticationService.Models;
2+
using Microsoft.AspNetCore.Mvc;
3+
using System.Text.Json;
4+
5+
namespace Authentication.Controllers;
6+
7+
[ApiController]
8+
[Route("api/[controller]")]
9+
public class AuthenticationController : ControllerBase
10+
{
11+
private static readonly string _userFilePath = "users.json";
12+
13+
// Register the new user with the credentials like Username, Email ID and Password
14+
[HttpPost("register")]
15+
public IActionResult Register([FromBody] User newUser)
16+
{
17+
var Users = LoadUsers();
18+
if (Users.Any(u => u.Username == newUser.Username))
19+
{
20+
return BadRequest(new { message = "Username already exists" });
21+
}
22+
if (Users.Any(u => u.Email == newUser.Email))
23+
{
24+
return BadRequest(new { message = "Email already registered" });
25+
}
26+
newUser.Password = BCrypt.Net.BCrypt.HashPassword(newUser.Password);
27+
Users.Add(newUser);
28+
var json = JsonSerializer.Serialize(Users, new JsonSerializerOptions { WriteIndented = true });
29+
System.IO.File.WriteAllText(_userFilePath, json);
30+
return Ok(new { message = "User registered successfully" });
31+
}
32+
33+
// Existing user can login using the credentials such as Email ID and password
34+
[HttpPost("login")]
35+
public IActionResult Login([FromBody] User login)
36+
{
37+
var Users = LoadUsers();
38+
var user = Users.FirstOrDefault(u => u.Email == login.Email);
39+
if (user == null || !BCrypt.Net.BCrypt.Verify(login.Password, user.Password))
40+
{
41+
return Unauthorized(new { message = "Invalid credentials" });
42+
}
43+
44+
return Ok(new { username = user.Username, email = user.Email });
45+
}
46+
47+
// 🔸 Load the user details from the local storage file
48+
private static List<User> LoadUsers()
49+
{
50+
if (!System.IO.File.Exists(_userFilePath))
51+
return new List<User>();
52+
53+
var json = System.IO.File.ReadAllText(_userFilePath);
54+
return JsonSerializer.Deserialize<List<User>>(json) ?? new List<User>();
55+
}
56+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
namespace AuthenticationService.Models
2+
{
3+
4+
/// <summary>
5+
/// Represents a user with basic authentication details.
6+
/// </summary>
7+
8+
public class User
9+
{
10+
/// <summary>
11+
/// Gets or sets the username of the user.
12+
/// </summary>
13+
public string? Username { get; set; }
14+
15+
/// <summary>
16+
/// Gets or sets the email address of the user.
17+
/// </summary>
18+
public string Email { get; set; }
19+
20+
/// <summary>
21+
/// Gets or sets the password of the user.
22+
/// </summary>
23+
public string Password { get; set; }
24+
}
25+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
var builder = WebApplication.CreateBuilder(args);
2+
3+
// Add services to the container.
4+
builder.Services.AddControllers();
5+
builder.Services.AddEndpointsApiExplorer();
6+
builder.Services.AddSwaggerGen();
7+
8+
// ✅ Add CORS configuration BEFORE building the app
9+
builder.Services.AddCors(options =>
10+
{
11+
options.AddDefaultPolicy(policy =>
12+
{
13+
policy.AllowAnyOrigin()
14+
.AllowAnyHeader()
15+
.AllowAnyMethod();
16+
});
17+
});
18+
19+
var app = builder.Build();
20+
21+
// Configure the HTTP request pipeline.
22+
if (app.Environment.IsDevelopment())
23+
{
24+
app.UseSwagger();
25+
app.UseSwaggerUI();
26+
}
27+
28+
// ✅ Use CORS middleware BEFORE authorization
29+
app.UseCors();
30+
31+
app.UseHttpsRedirection();
32+
app.UseAuthorization();
33+
34+
app.MapControllers();
35+
36+
app.Run();
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
{
2+
"$schema": "http://json.schemastore.org/launchsettings.json",
3+
"iisSettings": {
4+
"windowsAuthentication": false,
5+
"anonymousAuthentication": true,
6+
"iisExpress": {
7+
"applicationUrl": "http://localhost:19872",
8+
"sslPort": 44310
9+
}
10+
},
11+
"profiles": {
12+
"http": {
13+
"commandName": "Project",
14+
"dotnetRunMessages": true,
15+
"launchBrowser": true,
16+
"launchUrl": "swagger",
17+
"applicationUrl": "http://localhost:5063",
18+
"environmentVariables": {
19+
"ASPNETCORE_ENVIRONMENT": "Development"
20+
}
21+
},
22+
"https": {
23+
"commandName": "Project",
24+
"dotnetRunMessages": true,
25+
"launchBrowser": true,
26+
"launchUrl": "swagger",
27+
"applicationUrl": "https://localhost:7132;http://localhost:5063",
28+
"environmentVariables": {
29+
"ASPNETCORE_ENVIRONMENT": "Development"
30+
}
31+
},
32+
"IIS Express": {
33+
"commandName": "IISExpress",
34+
"launchBrowser": true,
35+
"launchUrl": "swagger",
36+
"environmentVariables": {
37+
"ASPNETCORE_ENVIRONMENT": "Development"
38+
}
39+
}
40+
}
41+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
}
8+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
},
8+
"AllowedHosts": "*"
9+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
[
2+
{
3+
"Username": "John",
4+
"Email": "[email protected]",
5+
"Password": "$2a$11$1zW3U/d6DC56zxifl8nATuGMQ8zhM8gmyx1t3fFtXAQg8a.xD5cBG"
6+
},
7+
{
8+
"Username": "Andrew",
9+
"Email": "[email protected]",
10+
"Password": "$2a$11$lu2VT2RXFNqI5Up8DYSkUuo1nampE5REmWJXQEcsvD69.icuTXUta"
11+
},
12+
{
13+
"Username": "Janet",
14+
"Email": "[email protected]",
15+
"Password": "$2a$11$42zEoWxWxtReaL3Sgs9haer9Uxb3OnrWa1FM0T9icweSJphEimy/q"
16+
}
17+
]

0 commit comments

Comments
 (0)