我正在将身份验证过程转换为支持异步,VS 2015 IDE 警告我以下消息: 异步方法缺少“等待”运算符并将同步运行...等等...
不管怎样,代码连接到 LDAP 存储并验证用户的帐户等等...我已经尝试过使用 wait 进行各种操作,但我只是在这里遗漏了一些东西。我将代码恢复到之前的状态。我将不胜感激任何有关使其正确支持异步的指导...
这是代码:
public async Task<User> GetAsyncADUser(PrincipalContextParameter param)
    {
        try
        {
            if (UseLDAPForIdentityServer3)
            {
                using (var pc = new PrincipalContext(ContextType.Domain, param.ADDomain, param.ADServerContainer, param.ADServerUser, param.ADServerUserPwd))
                {
                    UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(pc, param.UserNameToValidate);
                    if (userPrincipal != null)
                    {
                        bool isvalid = pc.ValidateCredentials(userPrincipal.DistinguishedName, param.UserPasswordToValidate, ContextOptions.SimpleBind);
                        if (isvalid)
                        {
                            User user = new User { ad_guid = userPrincipal.Guid.ToString(), Username = param.UserNameToValidate, Password = param.UserPasswordToValidate };
                            return user;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        { …Run Code Online (Sandbox Code Playgroud) 我正在尝试让我的 .Net Web API(使用 OWIN 的 Azure API 应用程序)接受用于 client_credentials 授予的 OAuth Bearer 令牌,但我不断收到 401 Unauthorized。
似乎所有 Microsoft 示例都已过时(不符合 Owin 的最新 nuget 包)。
JwtFormat 需要一个 IIssuerSecurityTokenProvider,但它不再存在 - 相反,JwtFormat 需要一个 IIssuerSecurityKeyProvider,但我无法理解如何使用它。
Azure OAuth 服务器正在运行
我已在 Azure Active Directory 中注册了两个应用程序(api 和客户端)。由于这只是快速演示,我将向您提供所有 id 和秘密;)
我可以从 Azure AD 获取令牌,请参阅https://reqbin.com/817shtc2以获取完整的请求,到目前为止一切顺利。
应用程序编程接口
客户端ID:44cf7574-88a2-42d6-9497-bff43cc8dc09
端点:https ://apim-demo-mglentoft.azure-api.net/api/Values (GET)
客户
客户端ID:5f7ee334-b8db-46d3-972f-09f52e186d1d
秘密:ggKp94]HZHWZ.c*5wUC?ToSVfknyqLB3
我按照https://github.com/azureadquickstarts/appmodelv2-nativeclient-dotnet上的示例进行操作,但它引用了 Microsoft.Owin.Security.Jwt.IIssuerSecurityTokenProvider,它在 nuget v4.0.1.0 中不存在。
我尝试仅注释掉 JwtFormat 的第二个参数,但这不起作用。有什么想法如何使用 Microsoft.Owin.Security.Jwt.IIssuerSecurityKeyProvider 来实现此功能吗?
下面是整个startup.cs
我可以使用 .Net Core 来实现此功能,但由于各种原因,我必须坚持使用 .Net Framework 4.7.2
using …Run Code Online (Sandbox Code Playgroud) 我现在在 .Net Core 项目上工作,我需要 AuthenticationManager 接口 IAuthenticationManager
据微软称,这已经过时了。
要获得 ApplicationSignInManager 我有这个方法
      private ApplicationSignInManager getSignInManager(ApplicationUserManager manager, IAuthenticationManager auth)
    {
        return new ApplicationSignInManager(manager, auth);
    }
Run Code Online (Sandbox Code Playgroud)
应用登录管理器
 public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager)
    {
    }
    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}
Run Code Online (Sandbox Code Playgroud)
由于使用调用 CreatePerOwinContext,这在 Mvc 项目中确实有效
    app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
Run Code Online (Sandbox Code Playgroud)
但是如何在 .Net Core 中激活这个类?
也曾在这里了解到,这CreateOwinContext是.NET中的核心obsolote这里,但无法弄清楚如何调用创建的方法ApplicationSignInManager?
我有一个使用 Open Id Connect 身份验证(使用 Azure 作为身份验证服务器)的 .NET 应用程序,直到最近才开始工作。
堆栈跟踪:
[IOException: IDX20807: Unable to retrieve document from: 'System.String'. HttpResponseMessage: 'System.Net.Http.HttpResponseMessage', HttpResponseMessage.Content: 'System.String'.]
   Microsoft.IdentityModel.Protocols.<GetDocumentAsync>d__16.MoveNext() +1152
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   Microsoft.IdentityModel.Protocols.OpenIdConnect.<GetAsync>d__3.MoveNext() +391
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   Microsoft.IdentityModel.Protocols.<GetConfigurationAsync>d__24.MoveNext() +958
[InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'.]
   Microsoft.IdentityModel.Protocols.<GetConfigurationAsync>d__24.MoveNext() +1699
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   Microsoft.Owin.Security.OpenIdConnect.<ApplyResponseChallengeAsync>d__10.MoveNext() +565
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   Microsoft.Owin.Security.Infrastructure.<ApplyResponseCoreAsync>d__40.MoveNext() +349
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   Microsoft.Owin.Security.Infrastructure.<ApplyResponseAsync>d__39.MoveNext() +447
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   Microsoft.Owin.Security.Infrastructure.<TeardownAsync>d__34.MoveNext() +196
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task …Run Code Online (Sandbox Code Playgroud) string path = "/SomeSubPath";
            app.Map(new PathString(path),
                (application) =>
                {
                    app.Run((ctx) =>
                    {
                        Debug.WriteLine("{0} : {1}", path, ctx.Request.Path);
                        return Task.FromResult(0);
                    });
                });
            app.Use(async (ctx, next) =>
            {
                var watch = new Stopwatch();
                watch.Start();
                await next();
                watch.Stop();
                Debug.WriteLine("Request handled in {0} [ms]", watch.ElapsedMilliseconds);
            });
            app.Use(async (ctx, next) =>
            {
                Debug.WriteLine("{0} : {1}", "/", ctx.Request.Path);
                await next();
            });
Run Code Online (Sandbox Code Playgroud)
考虑上面的管道配置.
在我的启动类中,我想将"SomeSubPath"映射到一个独有的中间件处理程序.IE浏览器.以"/ SomeSubPath"开头的请求应该由一些独占的中间件处理,而所有其他请求应该由管道的其余部分处理.我正在使用此处找到的IAppBuilder.Map扩展.令我惊讶的是,中间件正在拦截所有请求,从而抑制应用程序的其余部分处理这些请求.
由于字体很棒4.3,他们将字体添加为woff2格式.
当我试图通过owin提供这个文件时,我正在问404:
app.UseFileServer(new FileServerOptions() {
    RequestPath = PathString.Empty,
    FileSystem = new PhysicalFileSystem(@"banana")
});
Run Code Online (Sandbox Code Playgroud)
如何通过owin中的文件服务器提供woff2 mime类型文件?
我一直在寻找SO一段时间,但找不到我特定问题的答案:
如何使用Autofac将数据(通过构造函数或属性)注入到OWIN Startup类中?
我在Windows服务中使用Autofac,它也处理后端服务的创建等.所以我在那里进行所有配置读取和容器构建.
我希望能够注册Startup类,这样我就可以为CORS注入允许的原点,但即使我用这样的属性注册对象:
var builder = new ContainerBuilder();
// This will actually be read from config.
var origins = new[]
              {
                  "http://localhost",
                  "http://localhost:8082",
              };
builder.Register(c => new Startup(origins));
var container = builder.Build();
Run Code Online (Sandbox Code Playgroud)
在运行时,实例化Startup类时,callstack显示它来自外部代码,而我的Autofac构建器没有推送该属性.
理想情况下,我希望将Autofac注册保存在一个地方(Windows服务类),然后将所需数据注入Startup,这样我就可以执行以下操作(将allowedOrigins其设置为属性或通过构造函数注入)
 public void Configuration(IAppBuilder app)
 {
     var configuration = new HttpConfiguration();
     ...
     var origins = string.Join(",", allowedOrigins);
     var cors = new EnableCorsAttribute(origins, "*", "*") { SupportsCredentials = true };
     configuration.EnableCors(cors);
     ....
 }
Run Code Online (Sandbox Code Playgroud)
任何想法将不胜感激.谢谢
peteski
UPDATE
我应该补充一点,在尝试Autofac注册和构建之后,我开始执行以下操作来启动OWIN自我主机应用程序:
var webApp = WebApp.Start<Startup>(baseAddress);
Run Code Online (Sandbox Code Playgroud)
通过与朋友的对话,他们建议创建Startup对象并将其传递给 …
我得到了ASP.NET MVC应用程序,它通过OWIN库通过Google帐户验证用户.
用户有时会在主机(客户)计算机,公共计算机上登录Web应用程序来管理Web应用程序中的某些数据.
有一个登录按钮,可将您重定向到Google登录页面,用户输入用户名和密码,然后重定向回此Web应用程序.到目前为止,这是好的,这就是OWIN通常的工作方式.
我担心用户忘记注销应用程序而有人会从Web应用程序捕获数据.这在任何网络应用程序中都存在风险,我必须接受它.但是,如果用户忘记退出,则会有额外的风险,即有人会捕获来自Gmail,Google文档和所有相关Google服务的所有电子邮件.
我希望修改Owin身份验证,以便在Owin将用户重定向到Google登录页面后,Google只会将授权传递给Web应用,而无需登录用户访问Gmail以及Web浏览器中的所有相关Google服务.
以下代码也会登录Gmail作为Web应用程序身份验证的副作用.我看到OWIN有很多配置选项.我相信它是可以实现的:
public partial class Startup
{
    private double _expirationTimeCookies = 30; // minutes - sliding expiration
    public static ApplicationUserManager ApplicationUserManagerCreate(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var userStore = new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>());
        var tokenProvider = new DataProtectorTokenProvider<ApplicationUser>(options.DataProtectionProvider.Create("ASP.NET Identity"));
        ApplicationUserManager manager = new ApplicationUserManager(userStore);
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = tokenProvider;
        }
        return ApplicationUserManager.Create(tokenProvider, manager);
    }
    public void ConfigureAuth(IAppBuilder app)
    {           
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManagerCreate);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
        app.UseCookieAuthentication(new …Run Code Online (Sandbox Code Playgroud) 我使用这样的例子来创建一个自托管的API控制器.它可以HttpPost和HttpGet一个Customer对象.
获得CustomerId 的(简化)函数是:
[RoutePrefix("test")]
public class MyTestController : ApiController
{
    [Route("getcustomer")]
    [HttpGet]
    public Customer GetCustomer(int customerId)
    {    // as a test: react as if this customer exists:
         return new Customer()
         {
              Id = customerId,
              Name = "John Doe",
         };     
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)
这很好用.在我的客户端,我可以通过Id向该测试服务器询问客户,并且我获得具有预期数据的客户.
显然,调用函数知道如何将返回的Customer包装到HttpResponseMessage可以传输到我的客户端的对象(?)中.
下一步:如果找不到客户,则返回错误404.
[Route("getcustomer")]
[HttpGet]
public Customer GetCustomer(int customerId)
{    // as a test: only customer 1 exists
     if (customerId == 1)
     {
         return new Customer() …Run Code Online (Sandbox Code Playgroud) 我以前从未从事过身份验证工作,想学习 asp.net web api 中的身份验证
我创建了一个项目,并在这个项目的帮助下开始工作 教程
但我收到以下错误
尝试加载应用程序时发生以下错误。- 在“OwinBasedToken.Startup、OwinBasedToken、Version=1.0.0.0、Culture=neutral、PublicKeyToken=null”类中找不到“配置”方法。要禁用 OWIN 启动发现,请在 web.config 中添加值为“false”的 appSetting owin:AutomaticAppStartup。要指定 OWIN 启动程序集、类或方法,请在 web.config 中添加带有完全限定启动类或配置方法名称的 appSetting owin:AppStartup。
描述:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。
异常详细信息:System.EntryPointNotFoundException:尝试加载应用程序时发生以下错误。- 在“OwinBasedToken.Startup、OwinBasedToken、Version=1.0.0.0、Culture=neutral、PublicKeyToken=null”类中找不到“配置”方法。要禁用 OWIN 启动发现,请在 web.config 中添加值为“false”的 appSetting owin:AutomaticAppStartup。要指定 OWIN 启动程序集、类或方法,请在 web.config 中添加带有完全限定启动类或配置方法名称的 appSetting owin:AppStartup。
这是我的代码
WebApiConfig.cs
using System.Web.Http;
namespace OwinBasedToken
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional …Run Code Online (Sandbox Code Playgroud) owin ×11
c# ×7
asp.net-mvc ×3
asp.net ×2
adfs ×1
asp.net-core ×1
asynchronous ×1
autofac ×1
azure ×1
fileserver ×1
font-awesome ×1
katana ×1
ldap ×1
mime-types ×1
oauth ×1
oauth-2.0 ×1
saml-2.0 ×1
self-hosting ×1
token ×1
woff2 ×1