Skip to content

Commit 75e7d50

Browse files
committed
swagger authorize option enable , db script file added & minor code changes
1 parent 362ae6b commit 75e7d50

File tree

4 files changed

+77
-16
lines changed

4 files changed

+77
-16
lines changed

ReactwithDotnetCore/Controllers/LoginController.cs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ namespace ReactwithDotnetCore.Controllers
1313
{
1414
public class LoginController(IConfiguration configuration) : Controller
1515
{
16-
private readonly IConfiguration _config = configuration ?? throw new ArgumentNullException(nameof(configuration));
1716
private readonly string _connectionString = configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string is missing.");
1817

1918
[AllowAnonymous]
@@ -60,7 +59,7 @@ public async Task<IActionResult> UserRegister([FromBody] User register)
6059
private string GenerateJSONWebToken(User userInfo)
6160
{
6261
// Ensure the key has at least 256 bits
63-
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"].PadRight(32)));
62+
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration?["Jwt:Key"]?.PadRight(32)));
6463
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
6564

6665
var claims = new[] {
@@ -70,8 +69,8 @@ private string GenerateJSONWebToken(User userInfo)
7069
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
7170
};
7271

73-
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
74-
_config["Jwt:Audience"],
72+
var token = new JwtSecurityToken(configuration?["Jwt:Issuer"],
73+
configuration?["Jwt:Audience"],
7574
claims,
7675
expires: DateTime.Now.AddMinutes(120),
7776
signingCredentials: credentials);

ReactwithDotnetCore/Controllers/StudentController.cs

Lines changed: 44 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,7 @@ public async Task<IActionResult> StudentData2(Student student)
3535
using IDbConnection dbConnection = new SqlConnection(_connectionString);
3636
dbConnection.Open();
3737

38-
// Assuming your table name is 'Students'
39-
string query = "INSERT INTO Students (name, email, phone, image) VALUES (@Name, @Email, @Phone, @Image)";
38+
string query = "INSERT INTO TBLB_Student (name, email, phone, image) VALUES (@Name, @Email, @Phone, @Image)";
4039
int rowsAffected = await dbConnection.ExecuteAsync(query, student);
4140

4241
if (rowsAffected > 0)
@@ -60,11 +59,47 @@ public async Task<IActionResult> GetAllStudents()
6059
{
6160
try
6261
{
62+
/*
63+
64+
//This code assumes that the token is in the "Bearer <token>" format in the Authorization header.
65+
//It splits the header and takes the last part as the token for validation. If your token format is
66+
//different, adjust the code accordingly.
67+
68+
// Retrieve the user name from the claims
69+
var userName = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
70+
71+
// Retrieve the token from the Authorization header
72+
var token = HttpContext.Request.Headers.Authorization.FirstOrDefault()?.Split(" ").Last();
73+
74+
if (string.IsNullOrEmpty(token))
75+
{
76+
return Unauthorized("Token not provided");
77+
}
78+
79+
// Validate the token
80+
var tokenHandler = new JwtSecurityTokenHandler();
81+
var validationParameters = new TokenValidationParameters
82+
{
83+
ValidateIssuer = true,
84+
ValidateAudience = true,
85+
ValidateLifetime = true,
86+
ValidateIssuerSigningKey = true,
87+
ValidIssuer = configuration?["Jwt:Issuer"]?.ToString(),
88+
ValidAudience = configuration?["Jwt:Audience"]?.ToString(),
89+
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration?["Jwt:Key"]?.PadRight(32)))
90+
};
91+
92+
var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
93+
94+
// At this point, the token is valid, and you can retrieve additional claims
95+
var dateOfJoin = principal.FindFirst("DateOfJoin")?.Value;
96+
97+
*/
98+
6399
using IDbConnection dbConnection = new SqlConnection(_connectionString);
64100
dbConnection.Open();
65101

66-
// Assuming your table name is 'Students'
67-
string query = "SELECT * FROM Students";
102+
string query = "SELECT * FROM TBLB_Student";
68103
var students = await dbConnection.QueryAsync<Student>(query);
69104

70105
return Ok(students);
@@ -75,7 +110,6 @@ public async Task<IActionResult> GetAllStudents()
75110
}
76111
}
77112

78-
79113
[HttpPost("insertstudent")]
80114
public async Task<IActionResult> InsertStudent(Student student)
81115
{
@@ -87,12 +121,12 @@ public async Task<IActionResult> InsertStudent(Student student)
87121
if (student.rollNumber.HasValue && student.rollNumber > 0)
88122
{
89123
// Update record if rollNumber is greater than 0
90-
string updateQuery = "UPDATE Students SET name = @Name, email = @Email, phone = @Phone, image = @Image WHERE rollNumber = @rollNumber;";
124+
string updateQuery = "UPDATE TBLB_Student SET name = @Name, email = @Email, phone = @Phone, image = @Image WHERE rollNumber = @rollNumber;";
91125
int rowsAffected = await dbConnection.ExecuteAsync(updateQuery, student);
92126

93127
if (rowsAffected > 0)
94128
{
95-
string query = "SELECT * FROM Students";
129+
string query = "SELECT * FROM TBLB_Student";
96130
var students = await dbConnection.QueryAsync<Student>(query);
97131

98132
return Ok(students);
@@ -105,12 +139,12 @@ public async Task<IActionResult> InsertStudent(Student student)
105139
else
106140
{
107141
// Insert record if rollNumber is not provided or less than or equal to 0
108-
string insertQuery = "INSERT INTO Students (name, email, phone, image) VALUES (@Name, @Email, @Phone, @Image);";
142+
string insertQuery = "INSERT INTO TBLB_Student (name, email, phone, image) VALUES (@Name, @Email, @Phone, @Image);";
109143
int rowsAffected = await dbConnection.ExecuteAsync(insertQuery, student);
110144

111145
if (rowsAffected > 0)
112146
{
113-
string query = "SELECT * FROM Students";
147+
string query = "SELECT * FROM TBLB_Student";
114148
var students = await dbConnection.QueryAsync<Student>(query);
115149

116150
return Ok(students);
@@ -135,8 +169,7 @@ public async Task<IActionResult> DeleteStudent(int rollNumber)
135169
using IDbConnection dbConnection = new SqlConnection(_connectionString);
136170
dbConnection.Open();
137171

138-
// Assuming your table name is 'Students'
139-
string query = "DELETE FROM Students WHERE rollNumber = @rollNumber";
172+
string query = "DELETE FROM TBLB_Student WHERE rollNumber = @rollNumber";
140173
int rowsAffected = await dbConnection.ExecuteAsync(query, new { RollNumber = rollNumber });
141174

142175
if (rowsAffected > 0)

ReactwithDotnetCore/Program.cs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Microsoft.AspNetCore.Authentication.JwtBearer;
22
using Microsoft.AspNetCore.Rewrite;
33
using Microsoft.IdentityModel.Tokens;
4+
using Microsoft.OpenApi.Models;
45
using System.Text;
56

67
const string CorsPolicyName = "_myCorsPolicy";
@@ -31,7 +32,35 @@
3132
builder.Services.AddControllers();
3233
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
3334
builder.Services.AddEndpointsApiExplorer();
34-
builder.Services.AddSwaggerGen();
35+
// Add Swagger
36+
builder.Services.AddSwaggerGen(c =>
37+
{
38+
c.SwaggerDoc("v1", new OpenApiInfo { Title = ".Net Core API", Version = "v1" });
39+
40+
// Add JWT token configuration
41+
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
42+
{
43+
Description = "JWT Authorization header using the Bearer scheme",
44+
Type = SecuritySchemeType.Http,
45+
Scheme = "bearer"
46+
});
47+
48+
// Add a requirement for the token
49+
c.AddSecurityRequirement(new OpenApiSecurityRequirement
50+
{
51+
{
52+
new OpenApiSecurityScheme
53+
{
54+
Reference = new OpenApiReference
55+
{
56+
Type = ReferenceType.SecurityScheme,
57+
Id = "Bearer"
58+
}
59+
},
60+
Array.Empty<string>()
61+
}
62+
});
63+
});
3564

3665
var app = builder.Build();
3766

ReactwithDotnetCore/db-script.sql

3.3 KB
Binary file not shown.

0 commit comments

Comments
 (0)