Asp.net 我希望web(MVC)和API在同一个数据库上

Asp.net 我希望web(MVC)和API在同一个数据库上,asp.net,asp.net-mvc,asp.net-web-api,web-applications,asp.net-identity-2,Asp.net,Asp.net Mvc,Asp.net Web Api,Web Applications,Asp.net Identity 2,我有一个数据库,需要用于管理和管理(交易数量、账单和其他管理)的web界面,并“手动”从数据库(产品)提供数据,并使用API向其他更大的客户提供数据(产品)。显然,所有这些都由SSL和https保护 我制作了一个asp.NETMVC5应用程序(业务逻辑和管理),并希望实现API(API中的noob)来向用户交付数据 不知道如何实现从MVC到API(同一数据库)的安全性 这个应用程序很小,我可以重写它。我想尝试使用core,但担心我会遇到同样的问题 具体问题:在MVC 5代或.core(MVC 6

我有一个数据库,需要用于管理和管理(交易数量、账单和其他管理)的web界面,并“手动”从数据库(产品)提供数据,并使用API向其他更大的客户提供数据(产品)。显然,所有这些都由SSL和https保护

我制作了一个asp.NETMVC5应用程序(业务逻辑和管理),并希望实现API(API中的noob)来向用户交付数据

不知道如何实现从MVC到API(同一数据库)的安全性

这个应用程序很小,我可以重写它。我想尝试使用core,但担心我会遇到同样的问题

具体问题:在MVC 5代或.core(MVC 6)中,我应该采取什么方法,以及是否应该使用一个数据库来存储数据、用户及其授权


(我希望避免推送所有真正的API)

好的,我的项目完成了。我在MVC5上取得了进步

(我向你们这些完美主义者道歉,但我现在没有时间去掉不必要的东西,所以我把所有文件都原封不动地扔掉了:)

第一次进近-放弃

首先,我尝试将其设计为推荐的internet:.MVC解决方案、.DB数据库和.API解决方案

结论:身份验证和实体框架存在很多问题。最后我放弃了这种方法

第二个成功的方法

只有一个解决方案,MVC

真正的NuGet安装了.NETAPI,使用集成授权扩展,使用的教程很少(没有一个有效)。请注意,我使用和

以下是修改和插件:

App_Start->IdentityConfig.cs

public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
    // *** ADD INT TYPE ARGUMENT TO CONSTRUCTOR CALL:
    public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(
        IdentityFactoryOptions<ApplicationUserManager> options,
        IOwinContext context)
    {
        // *** PASS CUSTOM APPLICATION USER STORE AS CONSTRUCTOR ARGUMENT:
        var manager = new ApplicationUserManager(
            new ApplicationUserStore(context.Get<ApplicationDbContext>()));

        // Configure validation logic for usernames

        // *** ADD INT TYPE ARGUMENT TO METHOD CALL:
        manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };


            // other code removed for brevity      
        manager.UserLockoutEnabledByDefault = Convert.ToBoolean(ConfigurationManager.AppSettings["UserLockoutEnabledByDefault"].ToString());
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(Double.Parse(ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString()));
        manager.MaxFailedAccessAttemptsBeforeLockout = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"].ToString());


        // Register two factor authentication providers. 
        // This application uses Phone and Emails as a step of receiving a 
        // code for verifying the user You can write your own provider and plug in here.

        // *** ADD INT TYPE ARGUMENT TO METHOD CALL:
        //manager.RegisterTwoFactorProvider("PhoneCode",
        //  new PhoneNumberTokenProvider<ApplicationUser, int>
        //  {
        //      MessageFormat = "Your security code is: {0}"
        //  });

        //// *** ADD INT TYPE ARGUMENT TO METHOD CALL:
        //manager.RegisterTwoFactorProvider("EmailCode",
        //  new EmailTokenProvider<ApplicationUser, int>
        //  {
        //      Subject = "SecurityCode",
        //      BodyFormat = "Your security code is {0}"
        //  });

        //manager.EmailService = new EmailService();
        //manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            // *** ADD INT TYPE ARGUMENT TO METHOD CALL:
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser, int>(
                    dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}


// PASS CUSTOM APPLICATION ROLE AND INT AS TYPE ARGUMENTS TO BASE:
public class ApplicationRoleManager : RoleManager<ApplicationRole, int>
{
    // PASS CUSTOM APPLICATION ROLE AND INT AS TYPE ARGUMENTS TO CONSTRUCTOR:
    public ApplicationRoleManager(IRoleStore<ApplicationRole, int> roleStore)
        : base(roleStore)
    {
    }

    // PASS CUSTOM APPLICATION ROLE AS TYPE ARGUMENT:
    public static ApplicationRoleManager Create(
        IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(
            new ApplicationRoleStore(context.Get<ApplicationDbContext>()));
    }
}


public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.
        return Task.FromResult(0);
    }
}


public class SmsService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Plug in your sms service here to send a text message.
        return Task.FromResult(0);
    }
}

//This is useful if you do not want to tear down the database each time you run the application.
//public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
//This example shows you how to create a new database if the Model changes
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
{
    protected override void Seed(ApplicationDbContext context)
    {
        //InitializeIdentityForEF(context); //- Do not Seed - IGOR
        //base.Seed(context);
    }

    //Create User=Admin@Admin.com with password=Admin@123456 in the Admin role        
    //public static void InitializeIdentityForEF(ApplicationDbContext db)
    //{
    //  var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
    //  var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
    //  const string name = "igor@email.mail";
    //  const string password = "LolLol1";
    //  const string roleName = "lol";

    //  //Create Role Admin if it does not exist
    //  var role = roleManager.FindByName(roleName);
    //  if (role == null)
    //  {
    //      role = new ApplicationRole(roleName);
    //      var roleresult = roleManager.Create(role);
    //  }

    //  var user = userManager.FindByName(name);
    //  if (user == null)
    //  {
    //      user = new ApplicationUser { UserName = name, Email = name };
    //      var result = userManager.Create(user, password);
    //      result = userManager.SetLockoutEnabled(user.Id, false);
    //  }

    //  // Add user admin to Role Admin if not already added
    //  var rolesForUser = userManager.GetRoles(user.Id);
    //  if (!rolesForUser.Contains(role.Name))
    //  {
    //      var result = userManager.AddToRole(user.Id, role.Name);
    //  }
    //}
}


public class ApplicationSignInManager : SignInManager<ApplicationUser, int>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) :
        base(userManager, authenticationManager)
    { }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}
MySysAdmin控制器,用于角色和初始用户的初始插入和编辑

public SysAdminController(ApplicationUserManager userManager,
        ApplicationRoleManager roleManager)
    {
        UserManager = userManager;
        RoleManager = roleManager;
    }

    private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        set
        {
            _userManager = value;
        }
    }

    private ApplicationRoleManager _roleManager;
    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

    public ActionResult RoleIndex()
    {
        return View(RoleManager.Roles);
    }

    public ActionResult RoleCreate()
    {
        return View();
    }

    [HttpPost]
    public async Task<ActionResult> RoleCreate(SysAdminVM.RoleViewModel roleViewModel)
    {
        if (ModelState.IsValid)
        {
            // Use ApplicationRole, not IdentityRole:
            var role = new ApplicationRole(roleViewModel.Name);
            var roleresult = await RoleManager.CreateAsync(role);
            if (!roleresult.Succeeded)
            {
                ModelState.AddModelError("", roleresult.Errors.First());
                return View();
            }
            return RedirectToAction("RoleIndex");
        }
        return View();
    }

    public async Task<ActionResult> RoleEdit(int id)
    {
        if (id > 0)
        {
            var role = await RoleManager.FindByIdAsync(id);
            if (role == null)
            {
                return HttpNotFound();
            }
            SysAdminVM.RoleViewModel roleModel = new SysAdminVM.RoleViewModel { Id = role.Id, Name = role.Name };
            return View(roleModel);
        }
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> RoleEdit([Bind(Include = "Name,Id")] SysAdminVM.RoleViewModel roleModel)
    {
        if (ModelState.IsValid)
        {
            var role = await RoleManager.FindByIdAsync(roleModel.Id);
            role.Name = roleModel.Name;
            await RoleManager.UpdateAsync(role);
            return RedirectToAction("RoleIndex");
        }
        return View();
    }

    [AllowAnonymous]
    public async Task<ActionResult> Initialize()
    {
        if (db.App.Where(x => x.Name.Contains("Initialize")).FirstOrDefault() == null)
        {
            await InitRoleCreate();
            await InitUser();
            db.App.Add(
                new App { Name = "Initialize", Val = "true" }
            );
            db.SaveChanges();
            return View();
        }
        return HttpNotFound();
    }

    private async Task InitRoleCreate()
    {
        var model = new List<string>()
    {
        "SysAdmin",
        "Admin",
        "User",
    };
        foreach (var item in model)
        {
            var role = new ApplicationRole(item);
            await RoleManager.CreateAsync(role);
        }
    }

    private async Task InitUser()
    {
        var user = new ApplicationUser
        {
            UserName = "HerGiz",
            Email = "hergiz@outlook.com",
            Name = "Igor Hermanović",
            Contact = "098 185 3131",
            TwoFactorEnabled = false,
            LockoutEnabled = true,
            EmailConfirmed = true
        };
        var adminResult = await UserManager.CreateAsync(user, "W7xtc2ywfb");
        await UserManager.AddToRolesAsync(user.Id, "SysAdmin");
    }
}
Global.asax

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        GlobalConfiguration.Configure(WebApiConfig.Register);

        MvcHandler.DisableMvcResponseHeader = true;

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        App_Start.AutoMapperConfig.DefineMaps();

        ModelBinders.Binders.Add(typeof(decimal), new Extensions.DecimalModelBinder());
        ModelBinders.Binders.Add(typeof(decimal?), new Extensions.DecimalModelBinder());
    }
Web.config

<appSettings>
    <add key="UserLockoutEnabledByDefault" value="true" />
    <add key="DefaultAccountLockoutTimeSpan" value="30" />
    <add key="MaxFailedAccessAttemptsBeforeLockout" value="4" />
 </appSettings>


您当前是否在现有MVC 5应用程序中使用ASP.Net Identity?这里有一个链接,指向“我使用的是股票识别2.2的扩展版iP实现”中的示例和参考。Int表示用户名,username表示电子邮件登录,否则股票解决方案您在回答中使用的是正确的,您甚至可以将其拆分为微服务,1用于交易,1用于计费等。这是一个非常常见的解决方案,您最终构建的并不是您自己问题的答案,而是一个非常过时的解决方案,我敦促您深入到微服务和容器世界,它是美丽、快速和现实的。这似乎是一个奇怪的解决方案,你想要的;一个API、一个数据库和一个应用程序,可能因为某种原因而将它们分开?最终你决定合并API和网站?这意味着当您的API被DDoS攻击时,您的网站将关闭,反之亦然?
[Authorize]
public class ApiKeysController : ApiController
{
    [Authorize]
    [Route("api/getkey/{term}")]
    public ShowFullKeyVM Get(string term)
    {
        if (User.Identity.IsAuthenticated == true)
        {
            if (!string.IsNullOrWhiteSpace(term) && (term.Length == 15 || term.Length == 16))
            {
                var lKey = new LKey();
                var vm = lKey.Search(term);
                if (vm != null)
                {
                    return vm;
                }
            }
            return new ShowFullKeyVM() { Error = "IMEI either is not valid :(", SearchIMEI = term };
        }
        return new ShowFullKeyVM() { Error = "Not Authenticated!!!", SearchIMEI = term };
    }
}
protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        GlobalConfiguration.Configure(WebApiConfig.Register);

        MvcHandler.DisableMvcResponseHeader = true;

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        App_Start.AutoMapperConfig.DefineMaps();

        ModelBinders.Binders.Add(typeof(decimal), new Extensions.DecimalModelBinder());
        ModelBinders.Binders.Add(typeof(decimal?), new Extensions.DecimalModelBinder());
    }
<appSettings>
    <add key="UserLockoutEnabledByDefault" value="true" />
    <add key="DefaultAccountLockoutTimeSpan" value="30" />
    <add key="MaxFailedAccessAttemptsBeforeLockout" value="4" />
 </appSettings>