c# - 예제 - razor pages




UI 취소 등록자로서의.NET 핵심 신원 (2)

ASP.NET 웹 페이지의 경우 ASP.Net 면도기 웹 페이지를 포함하기 이전에 답변을 추가 할 수 있습니다. 나는 누군가가 그들을 필요로하고 서로 혼동하지 않는 것처럼 이것을 구분했다. 웹 페이지는 웹 폼처럼 코드 숨김을 포함하기 때문에 다릅니다.

먼저 페이지> _LoginPartial.cshtml을 편집합니다.

행 삭제 <li><a asp-page="/Account/Register">Register</a></li>

다음 페이지 편집> 계정> Login.cshtml. 다음을 제거하십시오.

                <div class="form-group">
                <p>
                    <a asp-page="./ForgotPassword">Forgot your password?</a>
                </p>
                <p>
                    <a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
                </p>
            </div>

또한 삭제 :

<div class="col-md-6 col-md-offset-2">
    <section>
        <h4>Use another service to log in.</h4>
        <hr />
        @{
            if ((Model.ExternalLogins?.Count ?? 0) == 0)
            {
                <div>
                    <p>
                        There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
                        for details on setting up this ASP.NET application to support logging in via external services.
                    </p>
                </div>
            }
            else
            {
                <form asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
                    <div>
                        <p>
                            @foreach (var provider in Model.ExternalLogins)
                            {
                                <button type="submit" class="btn btn-default" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
                            }
                        </p>
                    </div>
                </form>
            }
        }
    </section>
</div>

이제 Login.cshtml.cs 뒤에있는 코드를 편집하십시오. 풀다:

public IList<AuthenticationScheme> ExternalLogins { get; set; }

또한 제거 :

// Clear the existing external cookie to ensure a clean login process
        await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

        ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

페이지 편집> 계정> 관리> _ManageNav.cshtml

풀다:

    @if (hasExternalLogins)
{
    <li class="@ManageNavPages.ExternalLoginsNavClass(ViewContext)"><a asp-page="./ExternalLogins">External logins</a></li>
}

다음으로 Pages> Account 디렉토리에서 다음 파일을 제거합니다.

  • ExternalLogin.cshtml
  • ForgotPassword.cshtml
  • ForgotPasswordConfirmation.cshtml
  • Register.cshtml
  • ResetPassword.cshtml
  • ResetPasswordConfirmation.cshtml

Pages> 계정> 관리 디렉토리에서 다음 파일을 제거하십시오.

  • ExternalLogin.cshtml

UI 응용 프로그램으로 .NET Core 2.1 + Identity의 'Register'옵션을 취소하고 싶습니다.

물론 페이지의 버튼을 제거 할 수는 있지만 질문은 안전한가요?

내 다른 옵션은 무엇입니까? Register 코드를 생성하기 위해 스캐 폴딩을 사용해야합니까?

(같은 SetPassword 등)

감사


Model-View-Controller 웹 애플리케이션에 대해 이야기하고 있다고 가정합니다. 나는 그 버튼이나 심지어보기를 제거하는 것이 안전하지 않다고 말할 수 있습니다.

또한 등록 된 사용자를 생성하는 제 3 자 로그인을 제거하려고한다고 가정합니다.

나는 다음을 할 것이다 :

계정 컨트롤러에서 다음을 제거하십시오.

[HttpGet]
    [AllowAnonymous]
    public IActionResult Register(string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");

                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                await _signInManager.SignInAsync(user, isPersistent: false);
                _logger.LogInformation("User created a new account with password.");
                return RedirectToLocal(returnUrl);
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

또한 계정 컨트롤러에서 다음을 제거하십시오.

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public IActionResult ExternalLogin(string provider, string returnUrl = null)
    {
        // Request a redirect to the external login provider.
        var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
        return Challenge(properties, provider);
    }

    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
    {
        if (remoteError != null)
        {
            ErrorMessage = $"Error from external provider: {remoteError}";
            return RedirectToAction(nameof(Login));
        }
        var info = await _signInManager.GetExternalLoginInfoAsync();
        if (info == null)
        {
            return RedirectToAction(nameof(Login));
        }

        // Sign in the user with this external login provider if the user already has a login.
        var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
            return RedirectToLocal(returnUrl);
        }
        if (result.IsLockedOut)
        {
            return RedirectToAction(nameof(Lockout));
        }
        else
        {
            // If the user does not have an account, then ask the user to create an account.
            ViewData["ReturnUrl"] = returnUrl;
            ViewData["LoginProvider"] = info.LoginProvider;
            var email = info.Principal.FindFirstValue(ClaimTypes.Email);
            return View("ExternalLogin", new ExternalLoginViewModel { Email = email });
        }
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                throw new ApplicationException("Error loading external login information during confirmation.");
            }
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await _userManager.CreateAsync(user);
            if (result.Succeeded)
            {
                result = await _userManager.AddLoginAsync(user, info);
                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent: false);
                    _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                    return RedirectToLocal(returnUrl);
                }
            }
            AddErrors(result);
        }

        ViewData["ReturnUrl"] = returnUrl;
        return View(nameof(ExternalLogin), model);
    }

또한 제거

[HttpGet]
    [AllowAnonymous]
    public IActionResult ForgotPassword()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);
            if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
            {
                // Don't reveal that the user does not exist or is not confirmed
                return RedirectToAction(nameof(ForgotPasswordConfirmation));
            }

            // For more information on how to enable account confirmation and password reset please
            // visit https://go.microsoft.com/fwlink/?LinkID=532713
            var code = await _userManager.GeneratePasswordResetTokenAsync(user);
            var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
            await _emailSender.SendEmailAsync(model.Email, "Reset Password",
               $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
            return RedirectToAction(nameof(ForgotPasswordConfirmation));
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    [HttpGet]
    [AllowAnonymous]
    public IActionResult ForgotPasswordConfirmation()
    {
        return View();
    }

    [HttpGet]
    [AllowAnonymous]
    public IActionResult ResetPassword(string code = null)
    {
        if (code == null)
        {
            throw new ApplicationException("A code must be supplied for password reset.");
        }
        var model = new ResetPasswordViewModel { Code = code };
        return View(model);
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var user = await _userManager.FindByEmailAsync(model.Email);
        if (user == null)
        {
            // Don't reveal that the user does not exist
            return RedirectToAction(nameof(ResetPasswordConfirmation));
        }
        var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
        if (result.Succeeded)
        {
            return RedirectToAction(nameof(ResetPasswordConfirmation));
        }
        AddErrors(result);
        return View();
    }

    [HttpGet]
    [AllowAnonymous]
    public IActionResult ResetPasswordConfirmation()
    {
        return View();
    }

이제 모델 아래에서 다음 파일을 삭제할 수 있습니다.

  • ExternalLoginViewModel
  • ForgotPasswordViewModel
  • RegisterViewModel
  • ResetPasswordViewModel

Views에서 나는 다음을 제거 할 것입니다 :

  • ConfirmEmail
  • ExternalLogin
  • 비밀번호를 잊으 셨나요
  • 잊어 버린 암호 확인
  • 레지스터
  • 암호를 재설정
  • ResetPassword 확인

또한 계정보기에서 Login.cshtml을 편집하고 다음을 제거하십시오.

                <div class="form-group">
                <p>
                    <a asp-page="./ForgotPassword">Forgot your password?</a>
                </p>
                <p>
                    <a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
                </p>
            </div>

또한 삭제 :

<div class="col-md-6 col-md-offset-2">
    <section>
        <h4>Use another service to log in.</h4>
        <hr />
        @{
            if ((Model.ExternalLogins?.Count ?? 0) == 0)
            {
                <div>
                    <p>
                        There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
                        for details on setting up this ASP.NET application to support logging in via external services.
                    </p>
                </div>
            }
            else
            {
                <form asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
                    <div>
                        <p>
                            @foreach (var provider in Model.ExternalLogins)
                            {
                                <button type="submit" class="btn btn-default" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
                            }
                        </p>
                    </div>
                </form>
            }
        }
    </section>
</div>

이제 공유보기 아래에서 _LoginPartial.cshtml을 열고 다음을 삭제하십시오.

<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>

보기 관리 _ManageNav.cshtml에서 다음을 삭제하십시오.

    @if (hasExternalLogins)
{
    <li class="@ManageNavPages.ExternalLoginsNavClass(ViewContext)"><a asp-action="ExternalLogins">External logins</a></li>
}

이제 yourapp.com/Account/URL에 가보더라도 404 페이지를 얻을 수 있습니다.

희망이 도움이됩니다.





asp.net-core-mvc