· 7 years ago · Aug 01, 2018, 05:26 AM
1public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
2{
3 var token = context.Request.Headers.Authorization.Parameter;
4 var principal = await AuthenticateToken(token)
5 // Other code here ...
6}
7
8protected Task<IPrincipal> AuthenticateToken(string token)
9{
10 var secretKey = _authenticationBusiness.GetSecretKey(); // error triggers here.
11
12 // Other code here ...
13}
14
15//AuthenticationBusiness.cs
16public string GetSecretKey()
17{
18 using (_unitOfWork)
19 {
20 var token = _unitOfWork.Tokens.GetToken();
21
22 return token.SecretKey ?? string.Empty;
23 }
24}
25
26//Dependency Injection using Unity
27 container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
28 container.RegisterType<IContext, Context>(new HierarchicalLifetimeManager());
29
30//UnitOfWork.cs
31private readonly IContext _context;
32
33public UnitOfWork(IContext context, IJWTRepository tokens)
34{
35 _context = context;
36 Tokens = tokens;
37}
38
39public IJWTRepository Tokens { get; private set; }
40
41public void Dispose()
42{
43 _context.Dispose();
44}
45
46
47//Context.cs
48public class Context : DbContext, IContext
49{
50 public new void SaveChanges()
51 {
52 base.SaveChanges();
53 }
54
55 public new void Dispose()
56 {
57 base.Dispose();
58 }
59}
60
61//JWTRepository.cs
62public class JWTRepository : Repository<JsonWebToken>, IJWTRepository
63{
64 public JWTRepository(Context context) : base(context) { }
65
66 public JsonWebToken GetToken()
67 {
68 return Context.Tokens
69 .OrderBy(jwt => jwt.Id)
70 .Take(1)
71 .SingleOrDefault();
72 }
73
74 private Context Context => _context as Context;
75}