标签: asp.net-identity-2

在我的自定义OAuthAuthorizationServerProvider中的ValidateClientAuthentication期间获取IdentityDbContext

我正在构建一个使用令牌进行授权的web.api服务.我跟着他的博客使用多米尼克拜尔的准则在这里.

今天我已经更新了Owin,Entity Framework和ASP.NET web.api的所有软件包,我发现很多东西都已经改变了.

我在网上发现了一些文章(显然没有关于这些主题的文档)并开始转换我的web.api服务.

职位有关的新的ASP.NET身份2.0.0帮我把几乎所有转变,但现在我被困在一个简单的愚蠢的事情.

我已经设法按照博客中的建议创建我的客户ApplicationUserManagerApplicationDbContext.

在我的Startup中,我将我的2个对象与Owin Context相关联:

app.CreatePerOwinContext<ApplicationDatabaseContext>(ApplicationDatabaseContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
Run Code Online (Sandbox Code Playgroud)

我已经定义了一个自定义的OAuthAuthorizationServerProvider,因为我想使用Bearer身份验证:

var OAuthOptions = new OAuthAuthorizationServerOptions
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/oauth/Token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
    Provider = new MyAuthorizationServerProvider(),
    RefreshTokenProvider = new MyRefreshTokenProvider(DateTime.UtcNow.AddHours(8))
};
Run Code Online (Sandbox Code Playgroud)

在我的MyAuthorizationServerProvider中,我已经覆盖了ValidateClientAuthentication,因为我想检查客户端凭据.

一切似乎工作正常,我可以从OwinContext获取我的IAuthenticationManager:

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
    string clientId = string.Empty;
    string clientSecret = string.Empty;

    if (context.TryGetBasicCredentials(out clientId, out …
Run Code Online (Sandbox Code Playgroud)

c# owin asp.net-identity asp.net-identity-2

2
推荐指数
1
解决办法
3793
查看次数

.net标识忽略LoginPath

标题说真的,我的LoginPath被完全忽略了,所以每当我尝试访问授权页面时,它都会带我到"/ Account/Login"页面,我从来没有在任何地方定义,而不是"/ Accounts"页面我已经定义了.不完全确定为什么会发生这种情况,因为之前我曾经将我重定向到正确的位置,而且我很久没有接触到任何与身份验证有关的事情了

这是我的Startup.Auth.cs

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using App.Models;
using Owin;
using System;

namespace App
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Accounts"),
                Provider = new CookieAuthenticationProvider
                { 
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc-5 asp.net-identity-2

2
推荐指数
1
解决办法
1166
查看次数

无法使用Microsoft.Owin.Security.WsFederation和ADFS 3登录

在一个评估各种不同身份提供者的项目中,我有一个代码库已经使用WsFederation Owin包成功通过Azure AAD和Okta进行了身份验证.评估列表中的下一个是内部托管的ADFS.和前两个一样:

我进入了idp登录页面,

登录,

使用带有表单变量的POST发送回主机(在本地运行),包括wtresult表单变量中的RequestSecurityTokenResponse.

发出外部登录cookie

我的ExternalLoginCallback函数被调用

不同之处在于:

        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if (loginInfo == null)
        {
            return RedirectToAction("Login");
        }
Run Code Online (Sandbox Code Playgroud)

loginInfo为null.以下是我尚未解读的潜在线索.如果我没有设置

  app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
Run Code Online (Sandbox Code Playgroud)

在我的初创公司中,我在User.Identity中获得了经过身份验证的声明身份.但是,此身份中没有用户名,姓名或角色声明.如果比较从Okta和ADFS返回的令牌,则有两个不同之处.两者都有upn,name和role声明,但ADFS声明是SAML 1.0声明,其中Okta是SAML 2.0.另一个区别是ADFS签名方法是sha265,其中Okta是sha1.

这些差异会导致我的问题吗?配置ADFS的人不知道指定这些东西的方法,是否可以将WsFederation中间件配置为请求特定的东西或使用ADFS正在使用的东西?

ws-federation owin asp.net-identity asp.net-identity-2

2
推荐指数
1
解决办法
1764
查看次数

ASP.NET Identity 2 无效,不存在两个因素提供程序

由于某种原因,EmailCode 未显示在有效的两因素身份验证提供程序中。然而,在我删除 PhoneCode 之前,它现在什么也没有显示。我已经调试过,它显示在 UserManager 下,但由于某些奇怪的原因 GetValidTwoFactorProvidersAsync 没有检索它。我已经尝试通过绕过该方法并手动检索值来手动添加它,但随后它会抛出 Microsoft.AspNet.Identity.EmailTokenProvider 不存在的错误消息。我无法解释为什么这不起作用。

        public async Task<ActionResult> SendCode(string returnUrl)
        {
            var userId = await SignInManager.GetVerifiedUserIdAsync();
            if (userId == null)
            {
                return View("Error");
            }
            var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
            var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
            return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl });
        }
Run Code Online (Sandbox Code Playgroud)

身份配置

            manager.RegisterTwoFactorProvider("EmailCode", new Microsoft.AspNet.Identity.EmailTokenProvider<SystemUser>
                {
                    Subject = "SecurityCode",
                    BodyFormat = "Your security code is {0}"
                });

            manager.EmailService = new …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-mvc two-factor-authentication asp.net-mvc-5 asp.net-identity-2

2
推荐指数
1
解决办法
3816
查看次数

Identity 2.0 Code First 表重命名

我正在尝试将身份表重命名为 Roles、Users、UserRoles、UserLogins 和 UserClaims。我部分成功地执行并使用命令 Update-Table 更新了我的数据库。

但是我似乎无法摆脱 AspNetUsers 表,它总是只生成一列,即 Id 列,尽管我得到了另一个带有完整列列表的 Users 表和另一个 Id 列。

Update-Database 生成的脚本

Applying automatic migration: 201501190035078_AutomaticMigration.
CREATE TABLE [dbo].[Roles] (
    [Id] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.Roles] PRIMARY KEY ([Id])
)
CREATE TABLE [dbo].[UserRoles] (
    [UserId] [nvarchar](128) NOT NULL,
    [RoleId] [nvarchar](128) NOT NULL,
    [IdentityUser_Id] [nvarchar](128),
    CONSTRAINT [PK_dbo.UserRoles] PRIMARY KEY ([UserId], [RoleId])
)
CREATE TABLE [dbo].[Users] (
    [Id] [nvarchar](128) NOT NULL,
    [Email] [nvarchar](max),
    [EmailConfirmed] [bit] NOT NULL,
    [PasswordHash] [nvarchar](max),
    [SecurityStamp] [nvarchar](max),
    [PhoneNumber] [nvarchar](max), …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-identity asp.net-identity-2

2
推荐指数
1
解决办法
1605
查看次数

MVC Identity 2使用FormsAuthenticationTicket

我正在用自定义版本替换(HttpContext.Current.User)IPrincipal,以便我可以存储更多信息登录和用户.我在使用FormsAuthtenticationTicket之前已完成此操作,但其他方式基于Memberhipship和SimpleMembership提供程序.

我的问题是,我可以使用FormsAuthenticationTicket来存储我的ICustomPrincipal的cookie,它会干扰或破坏OWIN Identity Pipline吗?我觉得我会混合苹果和橘子.

示例保存:

var user = userRepository.Users.Where(u => u.Email == viewModel.Email).First();

    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
    serializeModel.UserId = user.Id;
    serializeModel.FirstName = user.FirstName;
    serializeModel.LastName = user.LastName;

    JavaScriptSerializer serializer = new JavaScriptSerializer();

    string userData = serializer.Serialize(serializeModel);

    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
             1,
             viewModel.Email,
             DateTime.Now,
             DateTime.Now.AddMinutes(15),
             false,
             userData);

    string encTicket = FormsAuthentication.Encrypt(authTicket);
    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
    Response.Cookies.Add(faCookie);
Run Code Online (Sandbox Code Playgroud)

示例检索:

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        JavaScriptSerializer …
Run Code Online (Sandbox Code Playgroud)

forms-authentication asp.net-mvc-5 asp.net-identity-2

2
推荐指数
1
解决办法
3354
查看次数

验证用户名和密码而不验证用户身份

使用 Asp.Net Identity 2.x 和 WebApi 2.x(均为最新版本),是否可以仅验证给定的用户名和密码,以便了解所提供的信息是否有效,而无需实际验证用户身份?

我正在我们的身份服务中进行部分登录,在提供有效凭据后,在 EULA 许可协议获得批准之前,我必须不对用户进行身份验证。这就是我正在挣扎的地方......

抱歉没有提供任何代码,我希望问题很明显:)

asp.net-web-api asp.net-identity-2

2
推荐指数
1
解决办法
2829
查看次数

当Context从IdentityDbContext继承时,OnModelCreating失败

我的数据访问实现如下,并且正在运行

  1. Contexct继承自DB Context
  2. 有OnModelCreating配置
  3. 手动添加配置

但是我修改了我的背景下inherit,从IdentityDbContext<ApplicationUser>和停止手动生成的配置,之后的OnModelCreating失败,数据库更新不会发生的.

如果我删除它OnModelCreating,它工作正常.我一运行应用程序.

任何人都可以指导我这里出错吗?

ef-code-first asp.net-identity-2

2
推荐指数
1
解决办法
500
查看次数

在asp.net身份2.2.1中使用密码哈希创建测试用户

我想为我的 ASP.net MVC 应用程序创建一些测试用户。身份版本为2.2.1

我的代码很好地生成用户,但我想分配允许这些测试帐户登录的密码。所以我相信我需要调用以正常方式创建用户时使用的相同散列函数。

我的代码是

ApplicationDbContext db = new ApplicationDbContext();
...

for (var i=0; i<100; i++)
{
    var name = "User" + i;
    var user = db.Users.FirstOrDefault(u => u.UserName == name);

    if (user == null)
    {
        user = new ApplicationUser() {
                        UserName = name,
                        Email = name + "@" + name + "." + name,
                        PasswordHash = ?????hash of name ?????
                    };
         db.Users.Add(user);
         db.SaveChanges();

    }
}
Run Code Online (Sandbox Code Playgroud)

是的,我正在尝试为 User1 输入 User1 的密码,为 User2 输入 User2 的密码,依此类推。

问候, 约翰

c# asp.net asp.net-mvc asp.net-identity-2

2
推荐指数
1
解决办法
5399
查看次数

EF Code First Fluent API - 级联删除

我有两个型号:

public class User
{
   .....
   public virtual UserProfile UserProfile { get; set;}
}


public class UserProfile
{
   .....
   public virtual User User { get; set;}
}
Run Code Online (Sandbox Code Playgroud)

User是主表和关系是一一对应的.一个用户只有一个UserProfile.

如何使用EF CodeFirst Fluent API定义User和UserProfile之间的关系,以便当我从User表中删除一个用户时,Userprofile中的用户配置文件也会被删除?

entity-relationship entity-framework asp.net-mvc-5 asp.net-identity-2

1
推荐指数
1
解决办法
4183
查看次数