Как настроить ASP.NET MVC Web App для использования сертификата клиента - PullRequest
0 голосов
/ 24 сентября 2019

Я пытаюсь использовать клиентские сертификаты для защиты моего веб-приложения.Я использую следующее руководство:

https://dotnetcodr.com/2016/01/25/using-client-certificates-in-net-part-5-working-with-client-certificates-in-a-web-project/

Что я сделал: 1. Успешно создал свой самоподписанный сертификат и установил их 2. Изменил код, чтобы сертификат былбыть проверено, когда веб-приложение запущено.Тем не менее, большинство изменений кода необходимо сделать в Program.cs.Однако в моем проекте нет файла program.cs, поэтому я сохранил весь код Program.cs в файле Startup.cs.Теперь, когда я запускаю свое приложение локально, ничего не загружается.Страница продолжает загружаться.Также нет сообщения об ошибке.

Вот мой код: я закомментировал код, и затем он работает, в противном случае это не так и просто пытается загрузить страницу.Инструменты разработчика на chrome тоже ничего не показывают.

startup.cs


using Microsoft.Owin;
using Owin;
using System;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;

[assembly: OwinStartupAttribute(typeof(CRUDOperations.Startup))]
namespace CRUDOperations
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);

            /*
            try
            {
                X509Certificate2 clientCert = GetClientCertificate();
                WebRequestHandler requestHandler = new WebRequestHandler();
                requestHandler.ClientCertificates.Add(clientCert);

                HttpClient client = new HttpClient(requestHandler)
                {
                    BaseAddress = new Uri("http://localhost:44309/")
                };

                HttpResponseMessage response = client.GetAsync("customers").Result;
                response.EnsureSuccessStatusCode();
                string responseContent = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(responseContent);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception while executing the test code: {0}", ex.Message);
            }
            //Console.ReadKey();

        */
        }





        //Method to locate the client certificate
        private static X509Certificate2 GetClientCertificate()
        {
            X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            try
            {
                userCaStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
                X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySubjectName, "localtestclientcert", true);
                X509Certificate2 clientCertificate = null;
                if (findResult.Count == 1)
                {
                    clientCertificate = findResult[0];
                }
                else
                {
                    throw new Exception("Unable to locate the correct client certificate.");
                }
                return clientCertificate;
            }
            catch
            {
                throw;
            }
            finally
            {
                userCaStore.Close();
            }
        }
    }
}

StudentApiController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using System.Data.Entity;
using CRUDOperations.Models;
using System.Security.Cryptography.X509Certificates;
using System.Net.Http.Headers;

namespace CRUDOperations.api
{
    [RoutePrefix("api/StudentAPI")]

    public class StudentAPIController : ApiController
    {
        StudentDBEntities dbContext = null;

        public StudentAPIController() {
            dbContext = new StudentDBEntities();
        }

        [ResponseType(typeof(tblStudent))]
        [HttpPost]
        //Saves a particular student in the database
        public HttpResponseMessage SaveStudent(tblStudent astudent) {
            int result = 0;
            try
            {
                dbContext.tblStudents.Add(astudent);
                dbContext.SaveChanges();
                result = 1;
            }
            catch (Exception e) {
                result = 0;
            }
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        //Gets all the students from the database:
        [ResponseType(typeof(tblStudent))]
        [HttpGet]


        public IHttpActionResult Get()
        {
            X509Certificate2 clientCertInRequest = RequestContext.ClientCertificate;
            //X509Certificate2 clientCertInRequest = Request.GetClientCertificate();
            if (clientCertInRequest != null)
            {
                IList<tblStudent> students = null;
                try
                {
                    students = dbContext.tblStudents.ToList();
                }
                catch (Exception e)
                {
                    students = null;
                }
                return Ok<IList<tblStudent>>(students);

            }
            AuthenticationHeaderValue authHeaderValue = new AuthenticationHeaderValue("ClientCert");
            return Unauthorized(authHeaderValue);
        }


        /*
        public List<tblStudent> GetStudents() {

            List<tblStudent> students = null;
            try {
                students = dbContext.tblStudents.ToList();
            } catch (Exception e) {
                students = null;
            }
            return students;
        }

        */
        //For eg a complete route will be: /api/StudentAPI/GetStudentByID/2
        //Edit the student data:

        //Constraint that the studentID needs to be an int
        [Route("GetStudentByID/{studentID:int}")]
        [ResponseType(typeof(tblStudent))]
        [HttpGet]
        public tblStudent GetStudentByID(int studentID)
        {
            tblStudent astudent = null;
            try
            {
                astudent = dbContext.tblStudents.Where(x => x.StudentID == studentID).SingleOrDefault();

            }
            catch (Exception e)
            {
                astudent = null;
            }

            return astudent;
        }

        //Updating the student details:
        [ResponseType(typeof(tblStudent))]
        [HttpPut]
        public HttpResponseMessage UpdateStudent(tblStudent astudent) {
            int result = 0;
            try {
                dbContext.tblStudents.Attach(astudent);
                dbContext.Entry(astudent).State = EntityState.Modified;
                dbContext.SaveChanges();
                result = 1;
            } catch {
                result = 0;
            }
            return Request.CreateResponse(HttpStatusCode.OK,result);
        }



        //Delete the student:
        [Route("DeleteStudent/{studentID:int}")]
        [ResponseType(typeof(tblStudent))]
        [HttpDelete]
        public HttpResponseMessage DeleteStudent(int studentID) {
            int result = 0;
            try {
                var student = dbContext.tblStudents.Where(x => x.StudentID == studentID).FirstOrDefault();
                //Attach lets us update only that entity, not every field in the table.
                dbContext.tblStudents.Attach(student);
                dbContext.tblStudents.Remove(student);
                dbContext.SaveChanges();
                result = 1;
            } catch (Exception e) {
                result = 0;
            }
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
    }
}

Может кто-нибудь указать, что яЯ делаю неправильно.Мой проект имеет следующую файловую структуру:

https://imgur.com/a/wlpyIxx

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