OWIN - 自定义UserManager

时间:2014-02-14 17:24:45

标签: c# asp.net-mvc owin

我必须自定义UserManager类来查找和验证公司结构中的用户(将Active Directory身份验证与另一个Oracle身份验证混合)。虽然我已实施FindAsyncCreateIdentityAsync,但用户未设置为已通过身份验证。

我的UserManager实施:

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);  
        }
    }
}

我的用户需要验证哪些内容?

4 个答案:

答案 0 :(得分:2)

尝试更改此行。

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

到此

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

这应该为您生成所需的cookie。

答案 1 :(得分:1)

UserManager管理数据库中的用户身份以及验证凭据。简而言之,它是一个数据库查找工具。要让用户“登录”您的应用,您需要发布某种令牌(如浏览器应用的cookie或api应用的令牌)。 ASP.NET中最新的方法是使用针对浏览器应用程序的Cookie身份验证中间件。有关cookie中间件的更多信息,请参见此处:

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

答案 2 :(得分:1)

查看由ASP.NET MVC 5默认项目创建的SignIn方法,我们可以看到以下代码:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

我们可以注意到的是AuthenticationManager是一个负责注解黄疸的人,在我们获得身份后,需要使用AuthenticationManager登录。所以也许你的问题不在于UserManager

此代码检索 Controller 类中的AuthenticationManager实例:

private IAuthenticationManager AuthenticationManager
{
    get
    {
        return HttpContext.GetOwinContext().Authentication;
    }
}

答案 3 :(得分:1)

Oracle Data Provider for .NET目前不支持异步查询和保存。