Setting up Forms Authentication for multiple Web Apps in MVC 5 based on OWIN

后端 未结 4 1180
我寻月下人不归
我寻月下人不归 2021-02-06 15:07

I am in process of setting up my 1st MVC Web App. I know I need to provide a Forms Based Authentication model as well as I know I will be reusing it for multiple other internal

4条回答
  •  情书的邮戳
    2021-02-06 15:40

    Detailed explanation I was searching for a way to use OWIN istead of FormsAuthentication, but without all that usermanager, userstore stuff. I suppose you want the same.

    In your Login Action check for user credentials in DB with your own code and if user is correct then create Claims with desired info and call AuthenticationManager.SignIn with those Claims:

    var claims = new List
    {
        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
        ,new Claim(ClaimTypes.Name, user.UserName)
        ,new Claim(ClaimTypes.Email, user.Email)
    };
    var identity = new ClaimsIdentity(claims,
                                DefaultAuthenticationTypes.ApplicationCookie);
    
    HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    

    Now you are logged in just like FormsAuthentication.SetAuthCookie method.

    Now you can get User info through claims:

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            var ctx = filterContext.HttpContext.Request.GetOwinContext();
            var identity = (ClaimsPrincipal)filterContext.HttpContext.User;
            var enumerable = identity.Claims as IList ?? identity.Claims.ToList();
            var username = enumerable.Where(x => x.Type == ClaimTypes.Name).Select(x => x.Value).FirstOrDefault();
            var userId = enumerable.Where(x => x.Type == ClaimTypes.NameIdentifier).Select(x => x.Value).FirstOrDefault();
    
        }
        base.OnActionExecuting(filterContext);
    }
    

    You have it under your control, instead of all the EF Code fist stuff that comes with MVC template

提交回复
热议问题