Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

‎APIJSON.NET/APIJSON.NET.Test/Program.cs

Lines changed: 41 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,53 @@
1-
using System;
1+
using RestSharp;
2+
using System;
23

34
namespace APIJSON.NET.Test
45
{
56
class Program
67
{
78
static void Main(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-
string str = "isContain(praiseUserIdList,userId)";
43-
Console.WriteLine(str.Substring(0,str.IndexOf("(")));
44-
Console.WriteLine(str.Substring(str.IndexOf("(")+1).TrimEnd(')'));
10+
var client = new RestClient("http://localhost:5000/");
11+
12+
var login = new RestRequest("token", Method.POST);
13+
login.AddJsonBody(new TokenInput() { username = "admin1", password = "123456" });
14+
IRestResponse<TokenData> token = client.Execute<TokenData>(login);
15+
16+
Console.WriteLine(token.Data.data.AccessToken);
17+
18+
var request = new RestRequest("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+
IRestResponse response = client.Execute(request);
28+
Console.WriteLine(response.Content);
29+
30+
31+
4532

4633
Console.ReadLine();
4734
}
4835
}
36+
public class TokenInput
37+
{
38+
public string username { get; set; }
39+
public string password { get; set; }
40+
}
41+
public class TokenData
42+
{
43+
public AuthenticateResultModel data { get; set; }
44+
}
45+
public class AuthenticateResultModel
46+
{
47+
public string AccessToken { get; set; }
48+
49+
public int ExpireInSeconds { 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
public ActionResult Query([FromBody]string json)
3839
{
3940
json = HttpUtility.UrlDecode(json);
@@ -146,19 +147,19 @@ public ActionResult Query([FromBody]string json)
146147
}
147148
ht.Add("func", bb);
148149
}
149-
else if (selectTable.IsTable(key))
150+
else if (key.Equals("total@"))
151+
{
152+
ht.Add("total", total);
153+
}
154+
else
150155
{
151156
var template = selectTable.GetFirstData(key, item.Value.ToString(), ht);
152157
if (template != null)
153158
{
154159
ht.Add(key, JToken.FromObject(template));
155160
}
156161
}
157-
else if (key.Equals("total@"))
158-
{
159-
ht.Add("total", total);
160-
}
161-
162+
162163
}
163164
}
164165
catch (Exception ex)

‎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
using System.Security.Claims;
77
using System.Text;
88
using System.Threading.Tasks;
9+
using Microsoft.AspNetCore.Authorization;
910
using Microsoft.AspNetCore.Http;
1011
using Microsoft.AspNetCore.Mvc;
1112
using Microsoft.Extensions.Options;
1213
using Newtonsoft.Json.Linq;
1314

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

5665
var data = new AuthenticateResultModel()
5766
{
@@ -62,6 +71,11 @@ public IActionResult Create(TokenInput input)
6271
ht.Add("data", JToken.FromObject(data));
6372
return Ok(ht);
6473
}
74+
[HttpGet]
75+
public IActionResult GetRole()
76+
{
77+
return Ok(User.Identity.Name);
78+
}
6579
private string CreateAccessToken(IEnumerable<Claim> claims, TimeSpan? expiration = null)
6680
{
6781
var now = 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 = new TokenValidationParameters
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using Microsoft.AspNetCore.Authentication;
2+
using Microsoft.AspNetCore.Authentication.JwtBearer;
3+
using Microsoft.AspNetCore.Builder;
4+
5+
namespace APIJSON.NET
6+
{
7+
public static class JwtTokenMiddleware
8+
{
9+
public static IApplicationBuilder UseJwtTokenMiddleware(this IApplicationBuilder app)
10+
{
11+
return app.Use(async (ctx, next) =>
12+
{
13+
if (ctx.User.Identity?.IsAuthenticated != true)
14+
{
15+
var result = await ctx.AuthenticateAsync("JwtBearer");
16+
if (result.Succeeded && result.Principal != null)
17+
{
18+
ctx.User = result.Principal;
19+
}
20+
}
21+
22+
await next();
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
using SqlSugar;
77
using System;
88
using System.Collections.Generic;
9+
using System.Dynamic;
910
using System.Linq;
1011
using System.Reflection;
1112
using System.Text.RegularExpressions;
@@ -121,7 +122,7 @@ public dynamic GetFirstData(string subtable, string json, JObject dd)
121122
return tb;
122123

123124
}
124-
private ISugarQueryable<System.Dynamic.ExpandoObject> sugarQueryable(string subtable, string selectrole, JObject values, JObject dd)
125+
private ISugarQueryable<ExpandoObject> sugarQueryable(string subtable, string selectrole, JObject values, JObject dd)
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)

AltStyle によって変換されたページ (->オリジナル) /