Как мне настроить идентификацию в asp net core 3.1? - PullRequest
2 голосов
/ 05 мая 2020

Я пытаюсь выполнить аутентификацию Google для своего asp net core 3.1 mvc веб-сайта. У меня проблемы с идентичностью. Это ошибка, которую я получаю.

InvalidOperationException: Невозможно разрешить службу для типа «Microsoft.AspNetCore.Identity.SignInManager`1 [RapLegendFinal.Data.RapLegendFinalIdContext]» при попытке активировать rapLegend.Controllers.ContactController '.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using rapLegend.Controllers;
using Microsoft.EntityFrameworkCore;
using RapLegendFinal.Data;
using RapLegendFinal.Areas.Identity;
//using RapLegendFinal.Data;

namespace RapLegendFinal
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {


            services.AddDbContext<DbContext>(options =>
       options.UseSqlServer(Configuration.GetConnectionString("RapLegendFinalIdContextConnection")));




            services.AddControllersWithViews();

            services.AddAuthentication().AddGoogle(options =>
            {

                IConfigurationSection googleAuthNSection =
                Configuration.GetSection("Authentication:Google");

                options.ClientId = "client id";
                options.ClientSecret = "client secret";

            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Вот контекст идентичности ..

namespace RapLegendFinal.Data
{
    public class RapLegendFinalIdContext : IdentityDbContext<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>
    {
        public RapLegendFinalIdContext()
        {

        }
        public RapLegendFinalIdContext(DbContextOptions<DbContext> options)
            : base(options.ToString())
        {
        }

    }
}

Код контактного контроллера ..

namespace rapLegend.Controllers
{
    public class ContactController : Controller
    {
        emailSuggesters newsuggester = new emailSuggesters();

         private readonly RapLegendFinalContext _context;
        private readonly SignInManager<RapLegendFinalIdContext> _signInManager;

        public ContactController(RapLegendFinalContext context, SignInManager<RapLegendFinalIdContext> signInManager)
        {
            _context = context;
            _signInManager = signInManager;
        }

        public async Task<IActionResult> Index()
        {
            await Task.Delay(100);
            return View();
        }


        [HttpPost]
        public async Task<IActionResult> Index(emailSuggesters model)
        {
            newsuggester.Name = model.Name;
            newsuggester.Email = model.Email;
            newsuggester.Message = model.Message;

             _context.emailSuggesters.Add(newsuggester);
             await _context.SaveChangesAsync();


            return View();
        }



        [HttpGet]
        public async Task<IActionResult> Authentication(string returnUrl)
        {
            newsuggester.ReturnUrl = returnUrl;
            newsuggester.ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            return View(newsuggester);
        }

        [HttpPost]
        public IActionResult ExternalLogin(string provider, string returnUrl)
        {
            var redirectUrl = Url.Action("ExternalLoginCallback", "ContactController", new { ReturnUrl = returnUrl });
            var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);

            return new ChallengeResult(provider, properties);
        }


        public async Task<IActionResult> Send(emailSuggesters model)
        {

            await Task.Delay(100);

            try
            {

                MimeMessage newmessage = new MimeMessage();

                newmessage.To.Add(new MailboxAddress("Arthur", "artulidis@gmail.com"));
                newmessage.From.Add(new MailboxAddress(model.Name, model.Email));
                newmessage.Subject = "New Song Suggestion!";
                newmessage.Body = new TextPart("plain")
                {
                    Text = model.Message
                };


                using (var gmail = new SmtpClient())
                {
                    gmail.Connect("smtp.gmail.com", 587, false);

                    gmail.Authenticate(model.Email, model.Password);


                    gmail.Send(newmessage);
                    gmail.Disconnect(true);
                }

                using (var yahoo = new SmtpClient())
                {
                    yahoo.Connect("smtp.yahoo.com", 587, false);

                    yahoo.Authenticate(model.Email, model.Password);


                    yahoo.Send(newmessage);
                    yahoo.Disconnect(true);
                }



            }
            catch (ArgumentNullException)
            {

            }

            return View();
        }


    }
}

Если есть какие-либо другие файлы кода, необходимые для изучите эту проблему, буду рад включить ее. Спасибо!

Ответы [ 2 ]

0 голосов
/ 06 мая 2020

Вы должны сначала добавить asp. net базовую службу идентификации для использования SignInManager:

services.AddDbContext<RapLegendFinalIdContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options =>
    options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<RapLegendFinalIdContext>();

И добавить промежуточное ПО для аутентификации в методе Configure:

app.UseAuthentication();
app.UseAuthorization(); 

Затем введите SignInManager<TUser> в свой контроллер:

private readonly SignInManager<IdentityUser> _signInManager;

public ContactController(SignInManager<IdentityUser> signInManager)
{
        _signInManager = signInManager;
}

Для внешнего использования Google вы можете нажать здесь и здесь для просмотра документа и образца кода.

0 голосов
/ 06 мая 2020

частный только для чтения SignInManager _signInManager;

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...