Aplicaciones de Windows
Contraer la tabla de contenido
Expandir la tabla de contenido

Controlador para autenticación (aplicaciones de la Tienda Windows)

Muestra el código que implementa un controlador System.Web.Mvc para la autenticación.

Servicio web de aplicación de banca para autenticación

La aplicación de la Tienda Windows para banca requiere un servicio web que proporcione autenticación basada en certificados y credenciales de contraseña.

El siguiente ejemplo de código muestra cómo implementar un controlador System.Web.Mvc que proporciona servicios de autenticación.



using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using BankServer.Models;
using System.Security.Cryptography.X509Certificates;

namespace BankServer.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

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

        [HttpPost]
        public JsonResult SimpleLogOn( string username, string password)
        {
            var result = new JsonResult(); 
            result.Data = new { user = username };
            return result;
        }

        [HttpPost]
	public JsonResult GetAccountInfo()
	{
	  var result = new JsonResult();
	  HttpClientCertificate clientCert = Request.ClientCertificate;
	  var strongAuth = false;
	  object[] accounts = new object[4];

	  accounts[0] = new
	    {
	      id = 43425453,
	      type = "Checking",
	      balance = 3000000
	    };
	  
	  accounts[1]= new
	    {
	      id = 43425453,
	      type = "Savings",
	      balance = 2000000000
	    };
	  
	  accounts[2] = new
	    {
	      id = 43425453,
	      type = "Credit Cards",
	      balance = 100.00
	    };

	  accounts[3] = new
	    {
	      id = 43425453,
	      type = "Loans",
	      balance = 545000
	    };

	  if (clientCert != null && clientCert.Certificate != null &&
              clientCert.Certificate.Length > 0) {
	    // Strong authentication. Allowed to access transfer/billpay.
	    strongAuth = true;
	  };
           
	  result.Data = new
	    {
	      accounts = accounts,
	      strongAuth = strongAuth
	    };

	  return result;
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

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

    }
}


Temas relacionados

System.Security.Cryptography.X509Certificates
System.Web.Mvc
CertificateEnrollmentManager
PasswordVault
Trabajo con certificados
Crear una aplicación de la Tienda Windows para banca
Crear una aplicación de la Tienda Windows para banca: recursos

 

 

Mostrar:
© 2018 Microsoft