-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthenticationService.cs
71 lines (51 loc) · 2.42 KB
/
AuthenticationService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System.Security.Authentication;
using System.Web;
using Models;
using Repositories;
using Utils;
using static JWT.JWTService;
namespace UserAuthentication;
public interface UserAuthenticationServiceException;
public class UserAuthenticationServiceInvalidCredentials: Exception, UserAuthenticationServiceException;
public class UserAuthenticationServiceUserForbidden: Exception, UserAuthenticationServiceException;
public static class UserAuthenticationService {
public static async Task<ITry<JWTToken>> Authenticate(HttpContext ctx,
UserSignIn user,
UserRepository UserRepository){
var r = await UserRepository.getUser(user.Username);
if(r == null){
return new FailedTry<JWTToken>(new InvalidCredentialException());
}
var hashedPassword = Convert.ToHexString(System.Security.Cryptography.SHA1.HashData(System
.Text.Encoding.UTF8.GetBytes(user.Password)));
if(!r.GetValue<bool>("active")){
return new FailedTry<JWTToken>(new UserAuthenticationServiceUserForbidden());
}
if(r.GetValue<string>("password").CompareTo(hashedPassword) != 0){
return new FailedTry<JWTToken>(new UserAuthenticationServiceInvalidCredentials());
}
var now = DateTime.UtcNow;
var header = new JWT.JWTService.Header();
var payload = new JWT.JWTService.Payload {
Username = user.Username,
LoginExpirationUTC = now.AddDays(10),
TokenExpirationUTC = now.AddMinutes(2),
Id = System.Guid.NewGuid().ToString(),
Organization = "myorg"
};
var token = JWT.JWTService.createJWTToken(header, payload);
//var result = await UserRepository.updateToken(user.Username, tokenInfo.Token);
ctx.Response.Headers.Authorization = $"Bearer {token}";
ctx.Response.Headers["X-JWT"] = token;
ctx.Response.Cookies.Append("auth_token", HttpUtility
.UrlEncode(token));
/*var claims = new List<Claim> {
//new Claim(ClaimTypes.Name, user.Username)
new Claim("jwt-token", token)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(principal);*/
return new SuccessTry<JWTToken>(JWT.JWTService.validateJWTToken(token));
}
}