Browse Source

[Authentication] Fixed AuthFilter when no roles; added user data in token

develop
Robin Thoni 9 years ago
parent
commit
63f80c65c1

+ 13
- 3
Authentication-test/Controllers/ValuesController.cs View File

1
-using System.Collections.Generic;
1
+using System;
2
+using System.Collections.Generic;
2
 using System.Web.Http;
3
 using System.Web.Http;
3
 using Authentication_test.DBO;
4
 using Authentication_test.DBO;
4
 using iiie.Authentication.Business;
5
 using iiie.Authentication.Business;
8
 {
9
 {
9
     public class ValuesController : ApiController
10
     public class ValuesController : ApiController
10
     {
11
     {
12
+        [AuthFilter]
13
+        public IEnumerable<string> Post()
14
+        {
15
+            return new[] { "value1", "value2" };
16
+        }
17
+
11
         [AuthFilter((int)UserRoles.Root)]
18
         [AuthFilter((int)UserRoles.Root)]
12
         public IEnumerable<string> Get()
19
         public IEnumerable<string> Get()
13
         {
20
         {
17
         [AuthFilter((int)UserRoles.NotRoot)]
24
         [AuthFilter((int)UserRoles.NotRoot)]
18
         public string Get(int id)
25
         public string Get(int id)
19
         {
26
         {
20
-            return "value";
27
+            return UserStorage.BasicUserDbo.Username + " " + UserStorage.BasicUserDbo.TokenData;
21
         }
28
         }
22
 
29
 
23
         [Route("api/login")]
30
         [Route("api/login")]
24
         [HttpGet]
31
         [HttpGet]
25
         public string Login(string username)
32
         public string Login(string username)
26
         {
33
         {
27
-            return TokenManager.GetToken(username, "");
34
+            return TokenManager.GetToken(username, "", new
35
+            {
36
+                Date = DateTime.Now
37
+            });
28
         }
38
         }
29
     }
39
     }
30
 }
40
 }

+ 1
- 3
Authentication/Business/AuthFilter.cs View File

32
         public override void OnActionExecuting(HttpActionContext actionContext)
32
         public override void OnActionExecuting(HttpActionContext actionContext)
33
         {
33
         {
34
             base.OnActionExecuting(actionContext);
34
             base.OnActionExecuting(actionContext);
35
-            if (!UserRoles.Any())
36
-                return;
37
             OpResult<bool> error = null;
35
             OpResult<bool> error = null;
38
             if (UserStorage.BasicUserDbo == null)
36
             if (UserStorage.BasicUserDbo == null)
39
             {
37
             {
40
                 error = OpResult<bool>.Error(ResultStatus.PermissionError, "User is not recognized. Missing token?", "").Log();
38
                 error = OpResult<bool>.Error(ResultStatus.PermissionError, "User is not recognized. Missing token?", "").Log();
41
             }
39
             }
42
-            else if (!UserRoles.Contains(UserStorage.BasicUserDbo.Role))
40
+            else if (UserRoles.Any() && !UserRoles.Contains(UserStorage.BasicUserDbo.Role))
43
             {
41
             {
44
                 error = OpResult<bool>.Error(ResultStatus.PermissionError, string.Format("User has role {0}, but only {1} are allowed",
42
                 error = OpResult<bool>.Error(ResultStatus.PermissionError, string.Format("User has role {0}, but only {1} are allowed",
45
                     UserStorage.BasicUserDbo.Role, string.Join(",", UserRoles.Select(x => x.ToString()))), "Permission denied").Log();
43
                     UserStorage.BasicUserDbo.Role, string.Join(",", UserRoles.Select(x => x.ToString()))), "Permission denied").Log();

+ 5
- 2
Authentication/Business/JWT/TokenManager.cs View File

3
 using System.IdentityModel.Tokens;
3
 using System.IdentityModel.Tokens;
4
 using System.Security.Claims;
4
 using System.Security.Claims;
5
 using System.ServiceModel.Security.Tokens;
5
 using System.ServiceModel.Security.Tokens;
6
+using Newtonsoft.Json;
6
 
7
 
7
 namespace iiie.Authentication.Business.JWT
8
 namespace iiie.Authentication.Business.JWT
8
 {
9
 {
32
         /// </summary>
33
         /// </summary>
33
         /// <param name="username">The user username</param>
34
         /// <param name="username">The user username</param>
34
         /// <param name="salt">The user salt</param>
35
         /// <param name="salt">The user salt</param>
36
+        /// <param name="data">Additionnal user data</param>
35
         /// <returns>The token</returns>
37
         /// <returns>The token</returns>
36
-        public static string GetToken(string username, string salt)
38
+        public static string GetToken(string username, string salt, object data = null)
37
         {
39
         {
38
             var stringValidator = ConfigurationManager.AppSettings["StringValidator"];
40
             var stringValidator = ConfigurationManager.AppSettings["StringValidator"];
39
             JwtSecurityToken jst = new JwtSecurityToken("urn:" + stringValidator,
41
             JwtSecurityToken jst = new JwtSecurityToken("urn:" + stringValidator,
41
                                               new []
43
                                               new []
42
                                                {
44
                                                {
43
                                                    new Claim(ClaimTypes.Name, username),
45
                                                    new Claim(ClaimTypes.Name, username),
44
-                                                   new Claim(ClaimTypes.Authentication, salt)
46
+                                                   new Claim(ClaimTypes.Authentication, salt),
47
+                                                   new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(data)) 
45
                                                }, null, DateTime.Now.AddDays(1),
48
                                                }, null, DateTime.Now.AddDays(1),
46
                                               CreateSigningCredentials());
49
                                               CreateSigningCredentials());
47
 
50
 

+ 7
- 1
Authentication/Business/JWT/TokenValidationHandler.cs View File

11
 using iiie.Authentication.DBO;
11
 using iiie.Authentication.DBO;
12
 using iiie.Logs.DataAccess;
12
 using iiie.Logs.DataAccess;
13
 using iiie.Logs.DBO;
13
 using iiie.Logs.DBO;
14
+using Newtonsoft.Json;
14
 
15
 
15
 namespace iiie.Authentication.Business.JWT
16
 namespace iiie.Authentication.Business.JWT
16
 {
17
 {
52
         /// <returns>The HTTP response</returns>
53
         /// <returns>The HTTP response</returns>
53
         protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
54
         protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
54
         {
55
         {
55
-            OpResult<bool> error = null;
56
+            OpResult<bool> error;
56
             string token;
57
             string token;
57
 
58
 
58
             if (!TryRetrieveToken(request, out token))
59
             if (!TryRetrieveToken(request, out token))
67
 
68
 
68
                 var name = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
69
                 var name = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
69
                 var salt = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Authentication);
70
                 var salt = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Authentication);
71
+                var data = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.UserData);
70
 
72
 
71
                 if (name == null || salt == null)
73
                 if (name == null || salt == null)
72
                 {
74
                 {
82
                     }
84
                     }
83
                     else
85
                     else
84
                     {
86
                     {
87
+                        if (data != null)
88
+                        {
89
+                            user.TokenData = JsonConvert.DeserializeObject(data.Value);
90
+                        }
85
                         UserStorage.BasicUserDbo = user;
91
                         UserStorage.BasicUserDbo = user;
86
                         return base.SendAsync(request, cancellationToken);
92
                         return base.SendAsync(request, cancellationToken);
87
                     }
93
                     }

+ 2
- 0
Authentication/DBO/BasicUserDbo.cs View File

7
         public string Username { get; set; }
7
         public string Username { get; set; }
8
 
8
 
9
         public int Role { get; set; }
9
         public int Role { get; set; }
10
+
11
+        public object TokenData { get; set; }
10
     }
12
     }
11
 }
13
 }

Loading…
Cancel
Save