Skip to content

Commit 7d63844

Browse files
Gourav DwivediGourav Dwivedi
authored andcommitted
Added JWT authentication for sample application
1 parent 14ea3bc commit 7d63844

File tree

9 files changed

+283
-17
lines changed

9 files changed

+283
-17
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Mvc;
3+
using Microsoft.Extensions.Configuration;
4+
using Microsoft.IdentityModel.Tokens;
5+
using System;
6+
using System.Collections.Generic;
7+
using System.IdentityModel.Tokens.Jwt;
8+
using System.Text;
9+
10+
namespace WebApp.Controllers
11+
{
12+
[Route("api/[controller]")]
13+
[ApiController]
14+
public class LoginController : Controller
15+
{
16+
private IConfiguration _config;
17+
18+
public LoginController(IConfiguration config)
19+
{
20+
_config = config;
21+
}
22+
23+
[AllowAnonymous]
24+
[HttpPost]
25+
public IActionResult Login([FromBody]UserModel login)
26+
{
27+
IActionResult response = Unauthorized();
28+
var user = AuthenticateUser(login);
29+
30+
if (user != null)
31+
{
32+
var tokenString = GenerateJSONWebToken(user);
33+
response = Ok(new { token = tokenString });
34+
}
35+
36+
return response;
37+
}
38+
39+
[HttpGet]
40+
[Authorize]
41+
public ActionResult<IEnumerable<string>> Get()
42+
{
43+
return new string[] { "value1", "value2", "value3", "value4", "value5" };
44+
}
45+
46+
private string GenerateJSONWebToken(UserModel userInfo)
47+
{
48+
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
49+
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
50+
51+
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
52+
_config["Jwt:Issuer"],
53+
null,
54+
expires: DateTime.Now.AddMinutes(120),
55+
signingCredentials: credentials);
56+
57+
return new JwtSecurityTokenHandler().WriteToken(token);
58+
}
59+
60+
private UserModel AuthenticateUser(UserModel login)
61+
{
62+
UserModel user = null;
63+
64+
if (login.Username == "Test" && login.Password == "Abc@123")
65+
{
66+
user = new UserModel { Username = "Test", EmailAddress = "test@test.com" };
67+
}
68+
return user;
69+
}
70+
}
71+
72+
public class UserModel
73+
{
74+
public string Username { get; set; }
75+
public string EmailAddress { get; set; }
76+
public string Password { get; set; }
77+
}
78+
}

Samples/AspDotCore/WebApp/WebApp/Hubs/OneHub.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
using Microsoft.AspNetCore.SignalR;
1+
using Microsoft.AspNetCore.Authentication.JwtBearer;
2+
using Microsoft.AspNetCore.Authorization;
3+
using Microsoft.AspNetCore.SignalR;
24
using System;
35
using System.Threading.Tasks;
46

@@ -17,6 +19,14 @@ public async Task NotifySameClient(string data)
1719
await Clients.Client(connectionId).SendAsync("ReceiveData", $"Data Received: {data}");
1820
}
1921

22+
//[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
23+
[Authorize]
24+
public async Task EE(string data)
25+
{
26+
var connectionId = Context.ConnectionId;
27+
await Clients.Client(connectionId).SendAsync("ReceiveData", $"Data Received: {data}");
28+
}
29+
2030
public async Task NotifyAllClient(string data)
2131
{
2232
await Clients.All.SendAsync("ReceiveData", $"Data Received: {data}");

Samples/AspDotCore/WebApp/WebApp/Startup.cs

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Linq;
4+
using System.Text;
45
using System.Threading.Tasks;
6+
using Microsoft.AspNetCore.Authentication.JwtBearer;
57
using Microsoft.AspNetCore.Builder;
68
using Microsoft.AspNetCore.Hosting;
79
using Microsoft.AspNetCore.Http;
810
using Microsoft.AspNetCore.HttpsPolicy;
911
using Microsoft.AspNetCore.Mvc;
1012
using Microsoft.Extensions.Configuration;
1113
using Microsoft.Extensions.DependencyInjection;
14+
using Microsoft.IdentityModel.Tokens;
1215
using WebApp.Hubs;
1316

1417
namespace WebApp
@@ -35,6 +38,60 @@ public void ConfigureServices(IServiceCollection services)
3538
.WithOrigins("http://localhost:8080");
3639
}));
3740

41+
//services.AddAuthentication()
42+
//.AddJwtBearer(options => {
43+
// options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
44+
// {
45+
// OnTokenValidated = cotext => {
46+
47+
// return Task.CompletedTask;
48+
// },
49+
// OnMessageReceived = context =>
50+
// {
51+
// var accessToken = context.Request.Query["access_token"];
52+
// if (string.IsNullOrEmpty(accessToken) == false)
53+
// {
54+
// context.Token = accessToken;
55+
// }
56+
// return Task.CompletedTask;
57+
// }
58+
// };
59+
//});
60+
61+
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
62+
.AddJwtBearer(options =>
63+
{
64+
options.TokenValidationParameters = new TokenValidationParameters
65+
{
66+
ValidateIssuer = true,
67+
ValidateAudience = true,
68+
ValidateLifetime = true,
69+
ValidateIssuerSigningKey = true,
70+
ValidIssuer = Configuration["Jwt:Issuer"],
71+
ValidAudience = Configuration["Jwt:Issuer"],
72+
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
73+
};
74+
75+
options.Events = new JwtBearerEvents
76+
{
77+
//OnTokenValidated = cotext =>
78+
//{
79+
80+
// return Task.CompletedTask;
81+
//},
82+
OnMessageReceived = context =>
83+
{
84+
//This is used for SignalR authentication
85+
var accessToken = context.Request.Query["access_token"];
86+
if (string.IsNullOrEmpty(accessToken) == false)
87+
{
88+
context.Token = accessToken;
89+
}
90+
return Task.CompletedTask;
91+
}
92+
};
93+
});
94+
3895
services.Configure<CookiePolicyOptions>(options =>
3996
{
4097
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
@@ -62,11 +119,13 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
62119
app.UseHsts();
63120
}
64121

122+
app.UseAuthentication();
123+
65124
app.UseSignalR(option => {
66125
option.MapHub<OneHub>(new PathString("/Test/OneHub"));
67126
});
68127

69-
app.UseHttpsRedirection();
128+
//app.UseHttpsRedirection();
70129
app.UseStaticFiles();
71130
app.UseCookiePolicy();
72131

Samples/AspDotCore/WebApp/WebApp/WebApp.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
<PackageReference Include="Microsoft.AspNetCore.App" />
1111
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
1212
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0" />
13+
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />
1314
</ItemGroup>
1415

1516
</Project>
Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
{
2-
"Logging": {
3-
"LogLevel": {
4-
"Default": "Warning"
5-
}
6-
},
7-
"AllowedHosts": "*"
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Warning"
5+
}
6+
},
7+
"AllowedHosts": "*",
8+
"Jwt": {
9+
"Key": "ThisismySecretKey",
10+
"Issuer": "Test.com"
11+
}
812
}

package-lock.json

Lines changed: 80 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
"@webcomponents/webcomponentsjs": "^2.2.10",
2424
"bootstrap": "^4.3.1",
2525
"jquery": "^3.4.1",
26+
"mitt": "^1.1.3",
2627
"popper.js": "^1.15.0"
2728
},
2829
"devDependencies": {

src/js/components/srform.component.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ class SrFormComponent extends HTMLElement {
4545
</div>
4646
</div>
4747
48-
<div class="form-group row onconnect">
48+
<div class="form-group row ">
4949
<label for="authHeader" class="col-sm-2 col-form-label">Authentication Header</label>
5050
<div class="col-sm-10 offset-sm-2">
5151
<input type="text" class="form-control" id="authHeader" placeholder="Token">

0 commit comments

Comments
 (0)