1
1
using System ;
2
+ using System . Collections ;
2
3
using System . Collections . Generic ;
3
4
using System . Configuration ;
4
5
using System . Linq ;
@@ -17,7 +18,7 @@ public class TasksController : ApiController
17
18
private static List < Models . Task > db = new List < Models . Task > ( ) ;
18
19
private static int taskId ;
19
20
20
- // OWIN auth middleware constants
21
+ // OWIN auth middleware constants -> These claims must match what's in your JWT, like for like. Click the 'claims' tab to check.
21
22
public const string scopeElement = "http://schemas.microsoft.com/identity/claims/scope" ;
22
23
public const string objectIdElement = "http://schemas.microsoft.com/identity/claims/objectidentifier" ;
23
24
@@ -31,7 +32,9 @@ public class TasksController : ApiController
31
32
public IEnumerable < Models . Task > Get ( )
32
33
{
33
34
HasRequiredScopes ( ReadPermission ) ;
34
- string owner = ClaimsPrincipal . Current . FindFirst ( objectIdElement ) . Value ;
35
+
36
+ var owner = CheckClaimMatch ( objectIdElement ) ;
37
+
35
38
IEnumerable < Models . Task > userTasks = db . Where ( t => t . Owner == owner ) ;
36
39
return userTasks ;
37
40
}
@@ -46,7 +49,8 @@ public void Post(Models.Task task)
46
49
if ( String . IsNullOrEmpty ( task . Text ) )
47
50
throw new WebException ( "Please provide a task description" ) ;
48
51
49
- string owner = ClaimsPrincipal . Current . FindFirst ( objectIdElement ) . Value ;
52
+ var owner = CheckClaimMatch ( objectIdElement ) ;
53
+
50
54
task . Id = taskId ++ ;
51
55
task . Owner = owner ;
52
56
task . Completed = false ;
@@ -61,11 +65,31 @@ public void Delete(int id)
61
65
{
62
66
HasRequiredScopes ( WritePermission ) ;
63
67
64
- string owner = ClaimsPrincipal . Current . FindFirst ( objectIdElement ) . Value ;
68
+ var owner = CheckClaimMatch ( objectIdElement ) ;
69
+
65
70
Models . Task task = db . Where ( t => t . Owner . Equals ( owner ) && t . Id . Equals ( id ) ) . FirstOrDefault ( ) ;
66
71
db . Remove ( task ) ;
67
72
}
68
73
74
+ /*
75
+ * Check user claims match task details
76
+ */
77
+ private string CheckClaimMatch ( string claim )
78
+ {
79
+ try
80
+ {
81
+ return ClaimsPrincipal . Current . FindFirst ( claim ) . Value ;
82
+ }
83
+ catch ( Exception e )
84
+ {
85
+ throw new HttpResponseException ( new HttpResponseMessage
86
+ {
87
+ StatusCode = HttpStatusCode . BadRequest ,
88
+ ReasonPhrase = $ "Unable to match claim '{ claim } ' against user claims; click the 'claims' tab to double-check."
89
+ } ) ;
90
+ }
91
+ }
92
+
69
93
// Validate to ensure the necessary scopes are present.
70
94
private void HasRequiredScopes ( String permission )
71
95
{
0 commit comments