Movatterモバイル変換


[0]ホーム

URL:


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

Commit2c04d03

Browse files
committed
增加connect/token 端点方法
1 parent444f2d4 commit2c04d03

File tree

5 files changed

+163
-27
lines changed

5 files changed

+163
-27
lines changed

‎src/Destiny.Core.Flow.OpenIddict.EntityFrameworkCore/OpenIddictEntityFrameworkCoreModule.cs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
usingMicrosoft.EntityFrameworkCore;
77
usingMicrosoft.Extensions.DependencyInjection;
88
usingSystem;
9+
usingSystem.IO;
910
usingSystem.Linq;
1011

1112
namespaceDestiny.Core.Flow.OpenIddict.EntityFrameworkCore
@@ -27,9 +28,11 @@ public override void ConfigureServices(ConfigureServicesContext context)
2728
protectedoverrideIServiceCollectionAddDbContextWithUnitOfWork(IServiceCollectionservices)
2829
{
2930
varsettings=services.GetObjectOrNull<AppOptionSettings>();
30-
varconnection="server=47.100.213.49;userid=test;pwd=pwd123456;database=Destiny.Core.Flow.OpenIddict;port=3307";//settings.DbContexts.Values.First().ConnectionString;
31+
varconnection=settings.DbContexts.Values.First().ConnectionString;
3132
vardatabaseType=settings.DbContexts.Values.First().DatabaseType;
3233
varassemblyName=settings.DbContexts.Values.First().MigrationsAssemblyName;
34+
35+
3336
services.AddDestinyDbContext<OpenIddictEntityDefaultDbContext>(x=>
3437
{
3538
x.ConnectionString=connection;
@@ -38,8 +41,10 @@ protected override IServiceCollection AddDbContextWithUnitOfWork(IServiceCollect
3841
},
3942
(_,options)=>
4043
{
44+
varconnStr=connection.IsTxtFile()?File.ReadAllText(connection):connection;
45+
Console.WriteLine(connStr);
4146
options.UseOpenIddict<OpenIddictApplication,OpenIddictAuthorization,OpenIddictScope,OpenIddictToken,Guid>();
42-
options.UseMySql(connection,ServerVersion.AutoDetect(connection),null);
47+
options.UseMySql(connStr,ServerVersion.AutoDetect(connStr),null);
4348
});
4449
services.AddUnitOfWork<OpenIddictEntityDefaultDbContext>();
4550
returnservices;
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
usingDestiny.Core.Flow.Model.Entities.Identity;
2+
usingMicrosoft.AspNetCore;
3+
usingMicrosoft.AspNetCore.Authentication;
4+
usingMicrosoft.AspNetCore.Identity;
5+
usingMicrosoft.AspNetCore.Mvc;
6+
usingOpenIddict.Abstractions;
7+
usingOpenIddict.Server.AspNetCore;
8+
usingSystem;
9+
usingSystem.Collections.Generic;
10+
usingSystem.Linq;
11+
usingSystem.Security.Claims;
12+
usingSystem.Threading.Tasks;
13+
usingstaticOpenIddict.Abstractions.OpenIddictConstants;
14+
15+
namespaceDestiny.Core.Flow.OpenIddict.Controllers
16+
{
17+
publicclassAuthorizationController:Controller
18+
{
19+
privatereadonlySignInManager<User>_signInManager;
20+
privatereadonlyUserManager<User>_userManager;
21+
22+
publicAuthorizationController(
23+
SignInManager<User>signInManager,
24+
UserManager<User>userManager)
25+
{
26+
_signInManager=signInManager;
27+
_userManager=userManager;
28+
}
29+
30+
[HttpPost("~/connect/token"),Produces("application/json")]
31+
publicasyncTask<IActionResult>Exchange()
32+
{
33+
varrequest=HttpContext.GetOpenIddictServerRequest();
34+
if(request.IsPasswordGrantType())
35+
{
36+
varuser=await_userManager.FindByNameAsync(request.Username);
37+
if(user==null)
38+
{
39+
varproperties=newAuthenticationProperties(newDictionary<string,string>
40+
{
41+
[OpenIddictServerAspNetCoreConstants.Properties.Error]=Errors.InvalidGrant,
42+
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription]=
43+
"The username/password couple is invalid."
44+
});
45+
46+
returnForbid(properties,OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
47+
}
48+
49+
// Validate the username/password parameters and ensure the account is not locked out.
50+
varresult=await_signInManager.CheckPasswordSignInAsync(user,request.Password,lockoutOnFailure:true);
51+
if(!result.Succeeded)
52+
{
53+
varproperties=newAuthenticationProperties(newDictionary<string,string>
54+
{
55+
[OpenIddictServerAspNetCoreConstants.Properties.Error]=Errors.InvalidGrant,
56+
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription]=
57+
"The username/password couple is invalid."
58+
});
59+
60+
returnForbid(properties,OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
61+
}
62+
63+
// Create a new ClaimsPrincipal containing the claims that
64+
// will be used to create an id_token, a token or a code.
65+
varprincipal=await_signInManager.CreateUserPrincipalAsync(user);
66+
67+
// Set the list of scopes granted to the client application.
68+
principal.SetScopes(new[]
69+
{
70+
Scopes.OpenId,
71+
Scopes.Email,
72+
Scopes.Profile,
73+
Scopes.Roles
74+
}.Intersect(request.GetScopes()));
75+
76+
foreach(varclaiminprincipal.Claims)
77+
{
78+
claim.SetDestinations(GetDestinations(claim,principal));
79+
}
80+
81+
returnSignIn(principal,OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
82+
}
83+
84+
thrownewNotImplementedException("The specified grant type is not implemented.");
85+
}
86+
87+
privateIEnumerable<string>GetDestinations(Claimclaim,ClaimsPrincipalprincipal)
88+
{
89+
// Note: by default, claims are NOT automatically included in the access and identity tokens.
90+
// To allow OpenIddict to serialize them, you must attach them a destination, that specifies
91+
// whether they should be included in access tokens, in identity tokens or in both.
92+
93+
switch(claim.Type)
94+
{
95+
caseClaims.Name:
96+
yieldreturnDestinations.AccessToken;
97+
98+
if(principal.HasScope(Scopes.Profile))
99+
yieldreturnDestinations.IdentityToken;
100+
101+
yieldbreak;
102+
103+
caseClaims.Email:
104+
yieldreturnDestinations.AccessToken;
105+
106+
if(principal.HasScope(Scopes.Email))
107+
yieldreturnDestinations.IdentityToken;
108+
109+
yieldbreak;
110+
111+
caseClaims.Role:
112+
yieldreturnDestinations.AccessToken;
113+
114+
if(principal.HasScope(Scopes.Roles))
115+
yieldreturnDestinations.IdentityToken;
116+
117+
yieldbreak;
118+
119+
// Never include the security stamp in the access and identity tokens, as it's a secret value.
120+
case"AspNet.Identity.SecurityStamp":yieldbreak;
121+
122+
default:
123+
yieldreturnDestinations.AccessToken;
124+
yieldbreak;
125+
}
126+
}
127+
}
128+
}

‎src/Destiny.Core.Flow.OpenIddictServer/Destiny.Core.Flow.OpenIddictServer.csproj‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
<ItemGroup>
2323
<NoneUpdate="DestinyCoreDb.txt">
24-
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
24+
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
2525
</None>
2626
<NoneUpdate="DestinyCoreMongoDb.txt">
2727
<CopyToOutputDirectory>Always</CopyToOutputDirectory>

‎src/Destiny.Core.Flow.OpenIddictServer/IMigrationService.cs‎

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -64,23 +64,23 @@ await manager.CreateAsync(new OpenIddictApplicationDescriptor
6464
newUri("http://localhost:4200")
6565
},
6666
Permissions=
67-
{
68-
Permissions.Endpoints.Authorization,
69-
Permissions.Endpoints.Logout,
70-
Permissions.Endpoints.Token,
71-
Permissions.GrantTypes.AuthorizationCode,
72-
Permissions.GrantTypes.RefreshToken,
73-
Permissions.ResponseTypes.Code,
74-
Permissions.Scopes.Email,
75-
Permissions.Scopes.Profile,
76-
Permissions.Scopes.Roles,
77-
Permissions.Prefixes.Scope+"server_scope",
78-
Permissions.Prefixes.Scope+"api_scope"
79-
},
67+
{
68+
Permissions.Endpoints.Authorization,
69+
Permissions.Endpoints.Logout,
70+
Permissions.Endpoints.Token,
71+
Permissions.GrantTypes.AuthorizationCode,
72+
Permissions.GrantTypes.RefreshToken,
73+
Permissions.ResponseTypes.Code,
74+
Permissions.Scopes.Email,
75+
Permissions.Scopes.Profile,
76+
Permissions.Scopes.Roles,
77+
Permissions.Prefixes.Scope+"server_scope",
78+
Permissions.Prefixes.Scope+"api_scope"
79+
},
8080
Requirements=
81-
{
82-
Requirements.Features.ProofKeyForCodeExchange
83-
}
81+
{
82+
Requirements.Features.ProofKeyForCodeExchange
83+
}
8484
});
8585
}
8686

@@ -92,9 +92,11 @@ await manager.CreateAsync(new OpenIddictApplicationDescriptor
9292
DisplayName="API Service",
9393
ClientSecret="my-api-secret",
9494
Permissions=
95-
{
96-
Permissions.Endpoints.Introspection
97-
}
95+
{
96+
Permissions.Endpoints.Introspection,
97+
Permissions.GrantTypes.Password,
98+
Permissions.Endpoints.Token
99+
}
98100
};
99101

100102
awaitmanager.CreateAsync(descriptor);
@@ -136,13 +138,13 @@ await manager.CreateAsync(new OpenIddictScopeDescriptor
136138

137139
staticasyncTaskEnsureAdministratorRole(IServiceProviderprovider)
138140
{
139-
varmanager=provider.GetRequiredService<RoleManager<IdentityRole>>();
141+
varmanager=provider.GetRequiredService<RoleManager<Role>>();
140142

141143
varrole="admin";
142144
varroleExists=awaitmanager.RoleExistsAsync(role);
143145
if(!roleExists)
144146
{
145-
varnewRole=newIdentityRole(role);
147+
varnewRole=newRole{Name=role};
146148
awaitmanager.CreateAsync(newRole);
147149
}
148150
}
@@ -157,14 +159,15 @@ static async Task EnsureAdministratorUser(IServiceProvider provider)
157159
varapplicationUser=newUser
158160
{
159161
UserName="admin",
160-
Email="admin@qq.com"
162+
Email="admin@qq.com",
163+
NickName="管理员"
161164
};
162165

163166
varuserResult=awaitmanager.CreateAsync(applicationUser,"Pass123$");
164167
if(!userResult.Succeeded)return;
165168

166169
awaitmanager.SetLockoutEnabledAsync(applicationUser,false);
167-
awaitmanager.AddToRoleAsync(applicationUser,"role");
170+
awaitmanager.AddToRoleAsync(applicationUser,"admin");
168171
}
169172
}
170173
}

‎src/Destiny.Core.Flow.OpenIddictServer/Startup.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
7373
}
7474
catch(Exceptionex)
7575
{
76-
Console.WriteLine("An error occurred while migrating the database."+ex);
76+
Console.WriteLine("An error occurred while migrating the database."+ex);
7777
}
7878
}
7979
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp