Commit 0409824b authored by 梁桐铭's avatar 梁桐铭 🏅
Browse files

升级项目到.NET Core3.1

parent 29b7aa9a
......@@ -373,7 +373,7 @@ namespace StudentManagement.Controllers
#region 管理用户中的角色
[HttpGet]
[Authorize(Policy = "EditRolePolicy")]
//[Authorize(Policy = "EditRolePolicy")]
public async Task<IActionResult> ManageUserRoles(string userId)
{
ViewBag.userId = userId;
......@@ -387,7 +387,7 @@ namespace StudentManagement.Controllers
var model = new List<RolesInUserViewModel>();
var roles = await roleManager.Roles.ToListAsync();
var roles = await roleManager.Roles.ToListAsync();
foreach (var role in roles)
{
var rolesInUserViewModel = new RolesInUserViewModel
......
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting.Internal;
using Microsoft.Extensions.Logging;
using StudentManagement.Models;
using StudentManagement.Security.CustomTokenProvider;
......@@ -18,13 +19,13 @@ namespace StudentManagement.Controllers
public class HomeController : Controller
{
private readonly IStudentRepository _studentRepository;
private readonly HostingEnvironment hostingEnvironment;
private readonly IWebHostEnvironment hostingEnvironment;
private readonly ILogger logger;
private readonly IDataProtector dataProtector;
//使用构造函数注入的方式注入IStudentRepository
public HomeController(IStudentRepository studentRepository, HostingEnvironment hostingEnvironment,
public HomeController(IStudentRepository studentRepository, IWebHostEnvironment hostingEnvironment,
ILogger<HomeController> logger,DataProtectionPurposeStrings dataProtectionPurposeStrings,IDataProtectionProvider dataProtectionProvider)
{
_studentRepository = studentRepository;
......
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
......@@ -17,7 +17,7 @@ namespace StudentManagement.Security.CustomTokenProvider
public class CustomEmailConfirmationTokenProvider<TUser> : DataProtectorTokenProvider<TUser> where TUser : class
{
public CustomEmailConfirmationTokenProvider(IDataProtectionProvider dataProtectionProvider,
IOptions<CustomEmailConfirmationTokenProviderOptions> options) : base(dataProtectionProvider, options)
IOptions<CustomEmailConfirmationTokenProviderOptions> options, ILogger<DataProtectorTokenProvider<TUser>> logger) : base(dataProtectionProvider, options,logger)
{
}
}
......
......@@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StudentManagement.Data;
using StudentManagement.Middlewares;
using StudentManagement.Models;
......@@ -36,8 +37,6 @@ namespace StudentManagement
options => options.UseSqlServer(_configuration.GetConnectionString("StudentDBConnection"))
);
services.Configure<IdentityOptions>(options =>
{
options.Password.RequiredLength = 6;
......@@ -57,7 +56,6 @@ namespace StudentManagement
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
});
/// 修改所有令牌类型的有效时间为10个小时
services.Configure<DataProtectionTokenProviderOptions>(
opt =>
......@@ -91,13 +89,11 @@ namespace StudentManagement
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddErrorDescriber<CustomIdentityErrorDescriber>()
.AddEntityFrameworkStores<AppDbContext>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders()
.AddTokenProvider<CustomEmailConfirmationTokenProvider<ApplicationUser>>("ltmEmailConfirmation")
;
;
// 策略结合声明授权
services.AddAuthorization(options =>
......@@ -118,8 +114,6 @@ namespace StudentManagement
options.InvokeHandlersAfterFailure = false;
});
services.AddAuthentication().AddMicrosoftAccount(opt =>
{
opt.ClientId = _configuration["Authentication:Microsoft:ClientId"];
......@@ -130,8 +124,7 @@ namespace StudentManagement
options.ClientSecret = _configuration["Authentication:Github:ClientSecret"];
});
services.AddMvc(config =>
services.AddControllersWithViews(config =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
config.Filters.Add(new AuthorizeFilter(policy));
......@@ -142,15 +135,11 @@ namespace StudentManagement
services.AddSingleton<IAuthorizationHandler, CanEditOnlyOtherAdminRolesAndClaimsHandler>();
services.AddSingleton<IAuthorizationHandler, SuperAdminHandler>();
services.AddSingleton<DataProtectionPurposeStrings>();
services.AddSingleton<DataProtectionPurposeStrings>();
}
// This method gets called by the runtim0e. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//如果环境是 Development,调用 Developer Exception Page
if (env.IsDevelopment())
......@@ -165,18 +154,29 @@ namespace StudentManagement
app.UseStaticFiles();
//身份认证中间件
app.UseAuthentication();
app.UseRouting();
//身份认证(authentication)和授权(authorization)
app.UseAuthorization();
app.UseDataInitializer();
app.UseMvc(routes =>
// UseEndpoints 是一个可以处理跨不同中间件系统(如MVC、 Razor Pages、 Blazor、 SignalR和gRPC) 的路由系统。通过终结点路由可以使端点相互协作,并使系统比没有相互对话的终端中间件更全面。当然本书暂时不会涉及Razor Pages、 Blazor、 SignalR和gRPC,但是为了项目的长远规划,dotnet开发团队推荐使用终结点路由。
app.UseEndpoints(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
routes.MapControllerRoute("default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
//授权访问
private bool AuthorizeAccess(AuthorizationHandlerContext context)
{
......@@ -184,6 +184,5 @@ namespace StudentManagement
context.User.HasClaim(claim => claim.Type == "Edit Role" && claim.Value == "true") ||
context.User.IsInRole("Super Admin");
}
}
}
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
<!--<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>-->
<AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
<UserSecretsId>fcab2e64-11c3-498d-bf3f-30ca4dd0d391</UserSecretsId>
......@@ -20,8 +20,14 @@
<ItemGroup>
<PackageReference Include="AspNet.Security.OAuth.GitHub" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.MicrosoftAccount" Version="3.1.8" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.8.4" />
</ItemGroup>
......
......@@ -19,7 +19,7 @@
"MyKey": "appsetting.json MyKey",
"ConnectionStrings": {
"StudentDBConnection": "server=(localdb)\\MSSQLLocalDB;database=StudentDB;Trusted_Connection=true"
"StudentDBConnection": "server=(localdb)\\MSSQLLocalDB;database=StudentDB;Trusted_Connection=true;MultipleActiveResultSets=True"
},
"Authentication": {
......@@ -35,5 +35,5 @@
}
// 支付宝的密钥 微信的密钥
// 支付宝的密钥 微信的密钥
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment