Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net web api - How to authenticate user

I have successfully logged in from web api controller. But when I try to get Authorized data from MVC Controller it returns me 401 unauthorized. here is my web api login controller.

using crudaspangularjs.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Description;

namespace crudaspangularjs.Controllers
{
    [RoutePrefix("api")]
    [Authorize]
    public class AuthController : ApiController
    {

        [Route("login")]
        [AllowAnonymous]
        [ResponseType(typeof(AdminLoginModel))]
        public IHttpActionResult Login(AdminLoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
                CrudAspAngularjsDbEntities2 db = new CrudAspAngularjsDbEntities2();
                Admin adminLoggedin = db.Admins.SingleOrDefault(x=>x.Email==model.Email && x.Password == model.Password);
                if (adminLoggedin == null)
                {
                    return BadRequest();

                }
                else
                {
                    var authUser = from admin in db.Admins
                                where admin.Email == adminLoggedin.Email
                                select new AdminLoginViewModel { Email = 
                                admin.Email, Name = admin.Name, RoleId = 
                                admin.RoleId, RoleName = admin.RoleName };
                    return Ok(authUser);

                }

        }
    }
}

here is the mvc controller.

using Rotativa;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using crudaspangularjs.Models;

namespace crudaspangularjs.Controllers
{
    [Authorize]
    public class UserController : Controller
    {
        private CrudAspAngularjsDbEntities db = null;
        public UserController()
        {
            db = new CrudAspAngularjsDbEntities();
        }
        [Authorize]
        public ActionResult Index()
        {

            var user = db.Users.ToList();
            return Json(user, JsonRequestBehavior.AllowGet);
        }


        [Authorize]
        public JsonResult Details(int id)
        {

            var user = db.Users.Find(id);
            return Json(user, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        [HttpPost]
        public JsonResult Create(User user)
        {
            db.Users.Add(user);
            db.SaveChanges();
            return Json(null);
        }
        [Authorize]
        [HttpPost]
        public JsonResult Edit(User user)
        {
            db.Entry(user).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
            return Json(null);
        }
        [Authorize]
        [HttpPost]
        public JsonResult Delete(int id)
        {
            var user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return Json(null);
        }
        [Authorize]
        public ActionResult PrintViewToPdf()
        {
            var report = new ActionAsPdf("Data") 
                 {
                    FileName = "ReportData.pdf",
                    PageSize = Rotativa.Options.Size.A4
                 };
            return report;
        }
        [Authorize]
        public ActionResult Data()
        {
            // ViewBag.user = db.Users.ToList();
            var user = db.Users.ToList();
            return View(user);
        }
    }
}

But everytime I perform an action it return 401 unauthorized. Looking for help! Thanks in advance

like image 647
Nayeem Azad Avatar asked Jul 18 '26 11:07

Nayeem Azad


2 Answers

To make a user authenticated you have to perform a sign in operation.
What you do in your Login method is checking the credentials, but sign in is where you (with help of some authentication API) set user identity into (most commonly) a cookie, like:

FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
like image 93
d_f Avatar answered Jul 22 '26 01:07

d_f


You can use ASP Identity as well. You can Authorize your users out of a box.

like image 27
michasaucer Avatar answered Jul 22 '26 01:07

michasaucer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!