5
5
using Microsoft . AspNetCore . Mvc . Filters ;
6
6
using Serilog ;
7
7
using WebServer . Model . Auth ;
8
- using JsonSerializer = System . Text . Json . JsonSerializer ;
9
8
10
9
namespace WebServer . Auth ;
11
10
12
11
[ AttributeUsage ( AttributeTargets . Class | AttributeTargets . Method ) ]
13
12
public class AuthorizeAttribute : Attribute , IAuthorizationFilter
14
13
{
15
- public string Roles { get ; set ; } = "" ;
14
+ private readonly Role [ ] _roles ;
15
+
16
+ public AuthorizeAttribute ( params Role [ ] roles )
17
+ {
18
+ _roles = roles ;
19
+ }
16
20
17
21
public void OnAuthorization ( AuthorizationFilterContext context )
18
22
{
@@ -28,25 +32,19 @@ public void OnAuthorization(AuthorizationFilterContext context)
28
32
return ;
29
33
}
30
34
31
- var unauthorizedResult = new JsonResult ( new { message = "Unauthorized" } ) { StatusCode = StatusCodes . Status401Unauthorized } ;
32
-
33
35
var account = ( Account ? ) context . HttpContext ? . Items ? [ GlobalConstants . CONTEXT_ACCOUNT_KEY ] ;
34
36
35
- logger . Debug ( "Account: {Account}" , JsonSerializer . Serialize ( account ) ) ;
36
- logger . Debug ( "Roles: {Roles}" , Roles ) ;
37
-
38
37
if ( account == null )
39
38
{
40
- context . Result = unauthorizedResult ;
39
+ context . Result = new JsonResult ( new { message = "Unauthorized" } ) { StatusCode = StatusCodes . Status401Unauthorized } ;
41
40
return ;
42
41
}
43
42
44
- if ( string . IsNullOrWhiteSpace ( Roles ) ) return ;
45
-
46
- var roleList = Roles . Split ( "," ) . Select ( r => r . Trim ( ) . ToUpper ( ) ) ;
47
-
48
- if ( roleList . All ( role => account . Roles . Contains ( role ) ) ) return ;
43
+ if ( _roles . Length == 0 || _roles . Any ( role => account . Roles . Contains ( role . ToString ( ) . ToUpper ( ) ) ) )
44
+ {
45
+ return ;
46
+ }
49
47
50
- context . Result = unauthorizedResult ;
48
+ context . Result = new JsonResult ( new { message = "Forbidden" } ) { StatusCode = 403 } ;
51
49
}
52
50
}
0 commit comments