Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OWIN - Customizing UserManager

I had to customize the UserManager class to find and authenticate users in the company structure (mixes Active Directory Authentication with another Oracle Authetication). Though I have implemented the FindAsync and CreateIdentityAsync, the user is not set as authenticated.

My UserManager implementation:

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Security.Claims;
using System.Web;
using MyProject.Common;
using MyProject.Models;
using Microsoft.AspNet.Identity;
using System.Threading.Tasks;

namespace MyProject.Infrastructure
{
    public class GNUserManager : UserManager<ApplicationUser>
    {
        public GNUserManager(IUserStore<ApplicationUser> store) : base(store)
        {

        }        

        public override async Task<ApplicationUser> FindAsync(string userName, string password)
        {
            /* Performs some logic here that returns true */

            if (foundUser) {
                return await Task.Run(() => new ApplicationUser
                {
                    UserName = userName, 
                    Id = userName
                });
            }

            throw new Exception("User not found.");
        }

        public override async Task<ClaimsIdentity> CreateIdentityAsync(ApplicationUser user, string authenticationType)
        {
            IList<Claim> claimCollection = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Country, "Brazil"),
                new Claim(ClaimTypes.Email, user.UserName)
            };

            var claimsIdentity = new ClaimsIdentity(claimCollection, "Company Portal");

            return await Task.Run(() => claimsIdentity);  
        }
    }
}

What is lacking to have my user authenticated?

like image 505
Leonel Sanches da Silva Avatar asked Feb 14 '14 17:02

Leonel Sanches da Silva


2 Answers

Try changing this line.

 var claimsIdentity = new ClaimsIdentity(claimCollection, "Company Portal");

To this

var claimsIdentity = new ClaimsIdentity(claimCollection, DefaultAuthenticationTypes.ApplicationCookie);

That should generate your cookie for you that is needed.

like image 96
user3475140 Avatar answered Nov 14 '22 18:11

user3475140


The UserManager manages the user identity in the database as well as validating credentials. In short, it's a DB lookup tool. To get the user "logged into" your app, you need to issue some sort of token (like a cookie for browser apps, or a token for api apps). The most recent approach in ASP.NET is with the Cookie Authentication Middleware for browser apps. See here for more info on the cookie middleware:

http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/

like image 1
Brock Allen Avatar answered Nov 14 '22 19:11

Brock Allen