Skip to content

Commit efb5263

Browse files
committed
#bug修复#
1 parent 64a6d1d commit efb5263

File tree

7 files changed

+104
-57
lines changed

7 files changed

+104
-57
lines changed
Lines changed: 41 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,53 @@
1-
usingSystem;
1+
usingRestSharp;
2+
usingSystem;
23

34
namespaceAPIJSON.NET.Test
45
{
56
classProgram
67
{
78
staticvoidMain(string[]args)
89
{
9-
//var client = new RestClient("http://localhost:5000/");
10-
//var request = new RestRequest("get", Method.POST);
11-
//request.AddJsonBody(@"{
12-
// 'User':{
13-
// 'id': 38710
14-
// }
15-
// }
16-
// ");
17-
//IRestResponse response = client.Execute(request);
18-
//Console.WriteLine(response.Content);
19-
20-
//request = new RestRequest("get", Method.POST);
21-
//request.AddJsonBody(@"{
22-
// 'User':{
23-
// 'id': 38710
24-
// },
25-
// '[]':{
26-
// 'page': 0,
27-
// 'count': 3,
28-
// 'Moment':{
29-
// 'userId': 38710
30-
// },
31-
// 'Comment[]':{
32-
// 'count': 3,
33-
// 'Comment':{
34-
// 'momentId@': '[]/Moment/id'
35-
// }
36-
// }
37-
// }
38-
//}
39-
// ");
40-
//IRestResponse response2 = client.Execute(request);
41-
//Console.WriteLine(response2.Content);
42-
stringstr="isContain(praiseUserIdList,userId)";
43-
Console.WriteLine(str.Substring(0,str.IndexOf("(")));
44-
Console.WriteLine(str.Substring(str.IndexOf("(")+1).TrimEnd(')'));
10+
varclient=newRestClient("http://localhost:5000/");
11+
12+
varlogin=newRestRequest("token",Method.POST);
13+
login.AddJsonBody(newTokenInput(){username="admin1",password="123456"});
14+
IRestResponse<TokenData>token=client.Execute<TokenData>(login);
15+
16+
Console.WriteLine(token.Data.data.AccessToken);
17+
18+
varrequest=newRestRequest("get",Method.POST);
19+
request.AddHeader("Content-Type","application/json");
20+
request.AddHeader("Authorization","Bearer "+token.Data.data.AccessToken);
21+
request.AddJsonBody(@"{
22+
'User':{
23+
'id': 38710
24+
}
25+
}
26+
");
27+
IRestResponseresponse=client.Execute(request);
28+
Console.WriteLine(response.Content);
29+
30+
31+
4532

4633
Console.ReadLine();
4734
}
4835
}
36+
publicclassTokenInput
37+
{
38+
publicstringusername{get;set;}
39+
publicstringpassword{get;set;}
40+
}
41+
publicclassTokenData
42+
{
43+
publicAuthenticateResultModeldata{get;set;}
44+
}
45+
publicclassAuthenticateResultModel
46+
{
47+
publicstringAccessToken{get;set;}
48+
49+
publicintExpireInSeconds{get;set;}
50+
51+
52+
}
4953
}

‎APIJSON.NET/APIJSON.NET/Controllers/JsonController.cs‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ public JsonController(SelectTable _selectTable, DbContext _db,IIdentityService i
3434
/// <param name="json"></param>
3535
/// <returns></returns>
3636
[HttpPost("/get")]
37+
3738
publicActionResultQuery([FromBody]stringjson)
3839
{
3940
json=HttpUtility.UrlDecode(json);
@@ -146,19 +147,19 @@ public ActionResult Query([FromBody]string json)
146147
}
147148
ht.Add("func",bb);
148149
}
149-
elseif(selectTable.IsTable(key))
150+
elseif(key.Equals("total@"))
151+
{
152+
ht.Add("total",total);
153+
}
154+
else
150155
{
151156
vartemplate=selectTable.GetFirstData(key,item.Value.ToString(),ht);
152157
if(template!=null)
153158
{
154159
ht.Add(key,JToken.FromObject(template));
155160
}
156161
}
157-
elseif(key.Equals("total@"))
158-
{
159-
ht.Add("total",total);
160-
}
161-
162+
162163
}
163164
}
164165
catch(Exceptionex)

‎APIJSON.NET/APIJSON.NET/Controllers/TokenController.cs‎

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,17 @@
66
usingSystem.Security.Claims;
77
usingSystem.Text;
88
usingSystem.Threading.Tasks;
9+
usingMicrosoft.AspNetCore.Authorization;
910
usingMicrosoft.AspNetCore.Http;
1011
usingMicrosoft.AspNetCore.Mvc;
1112
usingMicrosoft.Extensions.Options;
1213
usingNewtonsoft.Json.Linq;
1314

1415
namespaceAPIJSON.NET.Controllers
1516
{
16-
[Route("api/[controller]")]
17+
[Route("api/[controller]/[action]")]
1718
[ApiController]
19+
[Authorize]
1820
publicclassTokenController:ControllerBase
1921
{
2022
privateDbContextdb;
@@ -24,8 +26,9 @@ public TokenController(DbContext _db, IOptions<TokenAuthConfiguration> configura
2426
_configuration=configuration;
2527
db=_db;
2628
}
27-
[HttpGet("/token")]
28-
publicIActionResultCreate(TokenInputinput)
29+
[HttpPost("/token")]
30+
[AllowAnonymous]
31+
publicIActionResultCreate([FromBody]TokenInputinput)
2932
{
3033
JObjectht=newJObject();
3134
ht.Add("code","200");
@@ -45,13 +48,19 @@ public IActionResult Create(TokenInput input)
4548
returnOk(ht);
4649
}
4750
varidentity=newClaimsIdentity();
48-
identity.AddClaim(newClaim(ClaimTypes.NameIdentifier,us.userId.ToString()));
49-
identity.AddClaim(newClaim(ClaimTypes.Role,us.roleCode));
50-
identity.AddClaim(newClaim(JwtRegisteredClaimNames.Sub,input.username));
51-
identity.AddClaim(newClaim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()));
52-
identity.AddClaim(newClaim(JwtRegisteredClaimNames.Iat,DateTimeOffset.Now.ToUnixTimeSeconds().ToString(),ClaimValueTypes.Integer64));
53-
54-
varaccessToken=CreateAccessToken(identity.Claims.ToList());
51+
identity.AddClaim(newClaim(ClaimTypes.NameIdentifier,us.userId.ToString(CultureInfo.InvariantCulture)));
52+
identity.AddClaim(newClaim(ClaimTypes.Name,us.userId.ToString(CultureInfo.InvariantCulture)));
53+
identity.AddClaim(newClaim(ClaimTypes.Role,us.roleCode.ToString(CultureInfo.InvariantCulture)));
54+
varclaims=identity.Claims.ToList();
55+
56+
claims.AddRange(new[]
57+
{
58+
newClaim(JwtRegisteredClaimNames.Sub,us.userId.ToString(CultureInfo.InvariantCulture)),
59+
newClaim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
60+
newClaim(JwtRegisteredClaimNames.Iat,DateTimeOffset.Now.ToUnixTimeSeconds().ToString(),ClaimValueTypes.Integer64)
61+
});
62+
63+
varaccessToken=CreateAccessToken(claims);
5564

5665
vardata=newAuthenticateResultModel()
5766
{
@@ -62,6 +71,11 @@ public IActionResult Create(TokenInput input)
6271
ht.Add("data",JToken.FromObject(data));
6372
returnOk(ht);
6473
}
74+
[HttpGet]
75+
publicIActionResultGetRole()
76+
{
77+
returnOk(User.Identity.Name);
78+
}
6579
privatestringCreateAccessToken(IEnumerable<Claim>claims,TimeSpan?expiration=null)
6680
{
6781
varnow=DateTime.UtcNow;

‎APIJSON.NET/APIJSON.NET/Infrastructure/AuthConfigurer.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ public static void Configure(IServiceCollection services, IConfiguration configu
1616
{
1717
services.AddAuthentication(sharedOptions =>
1818
{
19-
sharedOptions.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
20-
sharedOptions.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
21-
}).AddJwtBearer(options =>
19+
sharedOptions.DefaultAuthenticateScheme="JwtBearer";
20+
sharedOptions.DefaultChallengeScheme="JwtBearer";
21+
}).AddJwtBearer("JwtBearer",options =>
2222
{
2323
options.Audience=configuration["Authentication:JwtBearer:Audience"];
2424
options.TokenValidationParameters=newTokenValidationParameters
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
usingMicrosoft.AspNetCore.Authentication;
2+
usingMicrosoft.AspNetCore.Authentication.JwtBearer;
3+
usingMicrosoft.AspNetCore.Builder;
4+
5+
namespaceAPIJSON.NET
6+
{
7+
publicstaticclassJwtTokenMiddleware
8+
{
9+
publicstaticIApplicationBuilderUseJwtTokenMiddleware(thisIApplicationBuilderapp)
10+
{
11+
returnapp.Use(async(ctx,next)=>
12+
{
13+
if(ctx.User.Identity?.IsAuthenticated!=true)
14+
{
15+
varresult=awaitctx.AuthenticateAsync("JwtBearer");
16+
if(result.Succeeded&&result.Principal!=null)
17+
{
18+
ctx.User=result.Principal;
19+
}
20+
}
21+
22+
awaitnext();
23+
});
24+
}
25+
}
26+
}

‎APIJSON.NET/APIJSON.NET/SelectTable.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
usingSqlSugar;
77
usingSystem;
88
usingSystem.Collections.Generic;
9+
usingSystem.Dynamic;
910
usingSystem.Linq;
1011
usingSystem.Reflection;
1112
usingSystem.Text.RegularExpressions;
@@ -121,7 +122,7 @@ public dynamic GetFirstData(string subtable, string json, JObject dd)
121122
returntb;
122123

123124
}
124-
privateISugarQueryable<System.Dynamic.ExpandoObject>sugarQueryable(stringsubtable,stringselectrole,JObjectvalues,JObjectdd)
125+
privateISugarQueryable<ExpandoObject>sugarQueryable(stringsubtable,stringselectrole,JObjectvalues,JObjectdd)
125126
{
126127
if(!IsTable(subtable))
127128
{

‎APIJSON.NET/APIJSON.NET/Startup.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
7575

7676
});
7777
app.UseAuthentication();
78+
app.UseJwtTokenMiddleware();
7879
DbInit.Initialize(app);
7980
}
8081
}

0 commit comments

Comments
(0)