标签: owin

如何在没有ASP.NET和没有MVC的情况下在owin中创建身份验证

我正在为我工​​作的公司OWIN自托管做一些研究.但是身份验证部分我无法使其工作,我可以找到的所有示例都不清楚或为ASP.NET编写,而我只允许使用C#.我想要做的是有一个列表,xml文件或数据库,其中一个现在无关紧要,但我想使用其中一个源为OWIN自托管创建我自己的自定义身份验证,而不使用ASP.NET和MVC.连接将是HTTPS,客户端是基于HTML/JavaScript的.我希望有人可以指出我正确的方向或给我一个例子.

c# self-hosting owin

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

如何在OWIN Katana中处理页面未找到错误?

假设我有hotfound.html页面,我想在找不到页面(或wab api方法)时显示它.

如何在OWIN应用程序中处理它?

谢谢

.net http-status-code-404 asp.net-web-api owin katana

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

无法解析符号'Owin'

我目前正在尝试在AngularJS单页面应用程序中实现AspNet.Identity身份验证.奇怪的是,在我的ApplicationUserManager类中,我想使用Microsoft.Owin和Microsoft.AspNet.Identity.Owin但在这两种情况下我都得到一个"无法解析符号'Owin'"的错误消息.

有谁知道发生了什么?我已将依赖项包含在我的project.json中并下载了这些包.ApplicationUserManager类的简化版本是这样的:

using Matimez.Models;
using Matimez.Models.Users;
using Microsoft.AspNet.Identity.Owin;  //Error message
using Microsoft.Owin;                  //Error message
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;


public class ApplicationUserManager : UserManager<NewUser>
{ 
    public ApplicationUserManager(IUserStore<NewUser> store)
    : base(store)
        {
        }

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
    var appDbContext = context.Get<MyAppContext>();
    var appUserManager = new ApplicationUserManager(new UserStore<NewUser>(appDbContext));

    return appUserManager;
}
}
Run Code Online (Sandbox Code Playgroud)

以下是我的project.json中的依赖项,如下所示:

  "dependencies": {
   "EntityFramework": "7.0.0-beta4",
   "EntityFramework.Commands": "7.0.0-beta4",
   "EntityFramework.SqlServer": "7.0.0-beta4",
   "MyApp.Models": "1.0.0-*",
   "MyApp.Services": "1.0.0-*",
   "Microsoft.AspNet.Diagnostics": "1.0.0-beta4",
   "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-beta4",
   "Microsoft.AspNet.Identity": "3.0.0-beta4",
   "Microsoft.AspNet.Mvc": "6.0.0-beta4",
   "Microsoft.AspNet.Server.IIS": "1.0.0-beta4",
   "Microsoft.AspNet.Server.WebListener": "1.0.0-beta4",
   "Microsoft.AspNet.StaticFiles": "1.0.0-beta4", …
Run Code Online (Sandbox Code Playgroud)

c# owin asp.net-identity

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

如何针对仅限SSL的Web Api控制器单元测试请求?

我有一个单元测试,它使用OWIN TestServer类来托管我的Web Api ApiController类进行测试.

当REST API没有将HTTPS(SSL)要求烘焙到Controller自身时,我首先编写了单元测试.

我的单元测试看起来像这样:

[TestMethod]
[TestCategory("Unit")]
public async Task Test_MyMethod()
{
    using (var server = TestServer.Create<TestStartup>())
    {
        //Arrange
        var jsonBody = new JsonMyRequestObject();
        var request = server.CreateRequest("/api/v1/MyMethod")
            .And(x => x.Method = HttpMethod.Post)
            .And(x => x.Content = new StringContent(JsonConvert.SerializeObject(jsonBody), Encoding.UTF8, "application/json"));

        //Act
        var response = await request.PostAsync();
        var jsonResponse =
            JsonConvert.DeserializeObject<JsonMyResponseObject>(await response.Content.ReadAsStringAsync());

        //Assert
        Assert.IsTrue(response.IsSuccessStatusCode);
    }

}
Run Code Online (Sandbox Code Playgroud)

现在我已应用该属性来强制执行HTTPS,我的单元测试失败.

如何修复我的测试,以便在所有条件相同的情况下,测试再次通过?

c# ssl unit-testing owin asp.net-web-api2

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

AuthenticationProperties无法在基于令牌的身份验证中工作

我在项目中使用基于OAuth Bearer令牌的身份验证.成功登录请求后,我收到以下json.

{"access_token":"some token","token_type":"bearer","expires_in":1232}
Run Code Online (Sandbox Code Playgroud)

我想在json下面发送更多信息数据.我创建了身份验证票证并添加了authenticationproperties.但它并没有起作用.

GrantResourceOwnerCredentials方法代码:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        try
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            var schoolId = context.UserName;
            var password = context.Password;
            logger.InfoFormat(CommonConstants.LoginInfoLogMessageFormat, schoolId);
            var loginOperator = new LoginManager();
            var result = loginOperator.IsUser(schoolId, password);
            if (result)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "user"));
                var authenticationProperties = GetUserAuthenticationProperties();
                var authenticationTicket = new AuthenticationTicket(identity, authenticationProperties);
                context.Validated(authenticationTicket);
            }
            else
            {
                context.SetError("invalid_grant", "Kullan?c? ad? veya ?ifre yanl??.");
            }
        }
        catch (Exception exception)
        { …
Run Code Online (Sandbox Code Playgroud)

oauth owin asp.net-web-api2

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

Microsoft.Owin.Host.HttpListener 没有被复制到引用项目的构建输出

我正在从同一解决方案中的另一个项目引用 Visual Studio 解决方案中的一个项目。被引用的项目(项目 B)具有 Microsoft.Owin.Host.HttpListener nuget 包,因此其中引用了 .dll。正在构建引用项目 B(项目 A)的项目。输出文件夹获取项目 B 中引用的所有 dll,但 Microsoft.Owin.Host.HttpListener.dll 除外,即使它被标记为 Copy Local - true。

Microsoft.Owin.Host.HttpListener.dll 是迄今为止我遇到的唯一一个拒绝将其作为 MSBuild 的 _CopyFilesMarkedCopyLocal 步骤的一部分复制到项目 A 的构建输出,而不管设置如何。

我试图将它添加到 app.config 中的条目中,但没有帮助。

我已经安排了展示引用问题的示例项目并将其上传到 GitHub here

您可以随意设置。

在问这个问题之前,我已经查看了 Stackoverflow 中的相关问题,但没有回答或不相关。

请给我一个提示,如何按预期将 .HttpListener.dll 与其他 .dll 一起复制到引用项目输出。

reference self-hosting copy-local visual-studio owin

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

Formsauthentication 和 owin facebook 身份验证并排(网络表单)

我需要使用表单身份验证将 Facebook(以及后来的 google 等)身份验证添加到现有的 asp.net webforms 应用程序。

我快到了,但表单身份验证和 owin 身份验证之间似乎存在冲突。我的解决方案基于标准的 VS 2015 模板。

重定向到外部身份验证提供程序(facebook)的相关代码如下:

string redirectUrl =
                ResolveUrl(String.Format(CultureInfo.InvariantCulture,
                    "~/Account/RegisterExternalLogin?{0}={1}&returnUrl={2}", IdentityHelper.ProviderNameKey,
                    provider, ReturnUrl));
            var properties = new AuthenticationProperties { RedirectUri = redirectUrl };

            Context.GetOwinContext().Authentication.Challenge(properties, provider);
            Response.StatusCode = 401;
            Response.End();
Run Code Online (Sandbox Code Playgroud)

如果我关闭表单身份验证,这会起作用。如果我有表单身份验证,用户将被重定向到 web.config 中定义的表单身份验证 URL:

    <authentication mode="Forms">
      <forms name=".ASPXAUTH_Test" loginUrl="~/start/login.aspx" timeout="60" >
        </forms>
    </authentication>
Run Code Online (Sandbox Code Playgroud)

根据我的理解,Http 状态代码 (401) 会触发重定向到 web.config 中的 Url。我试图设置其他状态代码,但它们根本不起作用。当我在 web.config 中关闭表单身份验证时,实际的登录过程仍然有效(令人惊讶)但是如果我在未登录的情况下访问受保护的页面,则会得到一个丑陋的 IIS 错误页面,而不是被重定向。

看来,我无法获得工作表单身份验证和外部身份验证才能正常工作:-(

到目前为止,所有替代方案对我来说似乎都不诱人: - 切换到身份框架(在我们的特定环境中,这绝对不是一个选项。我只是为了完整性才提到它) - 尝试使用 web.api 或其他东西类似(可能有同样的问题) - 放弃 owin 外部身份验证并手动实现所有内容

有没有人能够完成这项工作?任何帮助表示赞赏。提前致谢。

asp.net webforms formsauthentication owin

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

HttpClient默认标头不能与Microsoft.Owin.Testing.TestServer一起使用

我正在使用该Microsoft.Owin.Testing库集成测试我的API在内存中.我已经在OWIN JWT中间件中添加了我的身份验证需求,现在我正在尝试传递生成的令牌来测试需要授权的控制器的请求.我可以向您保证JWT中间件设置正确,因为它在正常使用时工作得很好.但是,我正在观察TestServer.HttpClient对象的一些奇怪行为.当我在HttpClient上设置默认授权头以传递令牌时,我的测试永远不会通过,因为无法识别令牌.但是,当我使用时TestServer.CreateRequest(...),测试正确传递并识别令牌.我更喜欢使用HttpClient方法,因为它们使用所提供的所有扩展方法使事情变得简单得多PostAsJsonAsync,等等.我开始认为在TestServer.HttpClient我或者我有一个完全缺少某些东西的错误.

这是我的测试类(使用NUnit3):

public class DefinitionsControllerTests
{
    private TestServer _server;
    private string _accessToken;

    [SetUp]
    public void Setup()
    {
        _server = TestServer.Create<Startup>();

        var credentials = new FormUrlEncodedContent(new[] {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", "john.doe@mail.com"),
            new KeyValuePair<string, string>("password", "testing123")
        });

        // get token from OWIN JWT middleware
        dynamic resultBody = JObject.Parse(
            _server.HttpClient.PostAsync("/oauth/token", credentials).Result.Content.ReadAsStringAsync().Result);

        _accessToken = (string)resultBody.access_token;

        // this does not appear to ever work
        _server.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
    } …
Run Code Online (Sandbox Code Playgroud)

integration-testing owin katana asp.net-web-api2

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

是否可以在运行时使用两个不同的 Owin 启动文件?

我正在使用带有MEF 框架的 Asp.net MVC 5 应用程序,以允许我将 MVC 应用程序设计为主应用程序中的插件。

我需要我的一个插件需要有自己的OwinStartup 类,该类在属于我的主应用程序的主 Owin 类之后运行。

换句话说,main.dllStartup一个总是需要先运行plugin.dllStartup类,然后有一个需要第二个运行的类。

是否可以拥有 2 个自己的创业班?

来自关于检测StartUp 类的文档

OwinStartup属性会覆盖命名约定。您还可以使用此属性指定友好名称,但是,使用友好名称需要您还使用appSetting配置文件中的元素。

所以我试着像这样添加一个友好的名字

[assembly: OwinStartup("pluginStartup", typeof(plugin.Startup))]
Run Code Online (Sandbox Code Playgroud)

在配置文件中添加了以下内容

<appSettings>  
  <add key="owin:appStartup" value="Main.Startup, Main" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

但这并没有归档我Plugin.Startup它只运行Main.Startup.

有没有办法运行两个不同的Startup类?

https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection

c# asp.net-mvc mef owin asp.net-mvc-5

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

Unity MVC5 依赖注入 - InjectionFactory 已弃用

在最新版本的 Unity (MVC5) 中,不推荐使用 InjectionFactory。以下是您在尝试使用它时将收到的过时警告。

[Obsolete("InjectionFactory has been deprecated and will be removed in next release. Please use IUnityContainer.RegisterFactory(...) method instead.", false)]
Run Code Online (Sandbox Code Playgroud)

不幸的是,我缺乏有关此 API 的知识来进行适当的修复。

正如您从下面的代码中看到的,我正在尝试使用利用 InjectionFactory 的旧解决方案注册 IAuthenticationManager。有谁知道新解决方案的外观如何?

public static void RegisterComponents()
{
    var container = new UnityContainer();

    container.RegisterType<IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
Run Code Online (Sandbox Code Playgroud)

下面我还包含了一个引用此对象的控制器。

public class AccountController : Controller
{
    private AdAuthenticationService _signInService;

    public AccountController() { }

    public AccountController(IAuthenticationManager signInManager)
    {
        this._signInService = new AdAuthenticationService(signInManager);
    }

    etc...
Run Code Online (Sandbox Code Playgroud)

如果你们有任何其他问题,请告诉我,并感谢您的帮助。

asp.net-mvc dependency-injection owin

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