标签: owin

asp.net mvc5表单身份验证,OWIN如何进入?

我启动了一个新的MVC5项目并实现了表单身份验证(我曾经使用自定义代码来检查用户凭据以及FormsAuthentication登录和注销的对象).

现在我已经读过身份模型已经改变了,但是我在生成的代码中看到了这行代码:

  private IAuthenticationManager AuthenticationManager
    {

        get
        {
            return HttpContext.GetOwinContext().Authentication;
        }
    }
Run Code Online (Sandbox Code Playgroud)

因为稍后登录是在该对象上完成的(AuthenticationManager.SignIn)

我想确保我有正确的对象.

我已经读过OWIN是关于将ASP.NET与IIS分离的,所以我不确定为什么我需要这个GetOwinContext,因为我没有使用OWIN(至少我认为)?

asp.net-mvc forms-authentication owin asp.net-identity

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

MVC Bootstrap主题

我想在我的MVC 5应用程序中包含对bootswatch主题的主题支持.

我希望用户主题在登录时保存并加载.

我扩展了我的用户类以包含主题,并且可以在编辑用户页面上成功设置和保存主题.

public class User : IdentityUser
{       
public string BootstrapTheme {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

在BootstrapTheme属性中,我将保存bootstrap css链接的href属性.例如 "~/Content/bootstrap.flatly.min.css"

计划是在布局页面中设置主题.

<link href="~/Content/bootstrap.spacelab.min.css" rel="stylesheet" />

如何在不加载每个页面的情况下查询数据库的情况下如何执行此操作?

能够做一些像<link href="@User.BootstrapTheme" rel="stylesheet" />理想的事情.

以下是使用localstorage http://wdtz.org/bootswatch-theme-selector.html保存一页的链接

asp.net-mvc twitter-bootstrap owin asp.net-identity

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

Fiddler:与'localhost'的连接失败了.与owin selfhost

我有以下简单的控制台应用程序使用Owin SelfHost托管webapi.来自控制台本身的响应有效,但如果从fiddler尝试我只是得到与localhost的连接失败.(与浏览器相同).

class Program
    {
        static void Main()
        {
            string baseAddress = "http://localhost:34300/";
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("da-dk");
            // Start OWIN host 
            using (WebApp.Start<Startup>(url: baseAddress))
            {
                // Create HttpCient and make a request to api/values 
                HttpClient client = new HttpClient();

                var response = client.GetAsync(baseAddress + "api/GpsPositions").Result;

                Console.WriteLine(response);
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
                Console.WriteLine("Listening on " + baseAddress);
            }

            Console.ReadLine();
        } 
    }
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

asp.net-web-api owin

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

vNext Owin中间件

我有一个简单的中间件:

public class MiddlewareInterceptor
{
    RequestDelegate _next;
    public MiddlewareInterceptor(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext ctx)
    {
        ctx.Response.WriteAsync("<h2>From SomeMiddleWare</h2>");
        return _next(ctx);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的Startup.cs配置方法中,我像这样挂钩:

app.UseMiddleware<MiddlewareInterceptor>();
Run Code Online (Sandbox Code Playgroud)

上面的构建和应用程序似乎运行正常,但我在拦截器Invoke方法中的断点永远不会命中.同样,从来没有任何产出.我也试过了Debug.WriteLine.

现在,我也试过这个方法:

public class MiddlewareInterceptor : OwinMiddleware
{
    public MiddlewareInterceptor(OwinMiddleware next) : base(next){}

    public override async Task Invoke(IOwinContext context)
    {
        Debug.WriteLine(context.Request.Uri.ToString());
        await Next.Invoke(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的Startup.cs配置方法中,我像这样挂钩:

app.Use(next => new MiddlewareInterceptor(next).Invoke);
Run Code Online (Sandbox Code Playgroud)

不幸的是,基础OwinMiddleware构造函数正在寻找下一个OwinMiddleware作为参数,与你不同RequestDelegate.所以我的app.Use实例化MiddlewareInterceptor失败是因为next类型RequestDelegate.

最后,我在Configure方法中直接尝试了一个内联函数,它也永远不会遇到断点:

app.Use(async (ctx, next) => …
Run Code Online (Sandbox Code Playgroud)

middleware owin asp.net-core

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

使用用于AzureBearerAuthentication的JWT获取Access令牌

我有一个WebApi应用程序正在使用Windows Azure Active Directory承载身份验证来验证用户.用户通过身份验证后,我想查询Azure的Graph Api以获取有关该用户的更多信息.

我有一个有效的解决方案,但似乎非常hacky.我读取了Authorization标头并删除了承载部分,然后我使用AquireToken获取新标记:

var authHeader = HttpContext.Current.Request.Headers["Authorization"];
var tokenMatch = Regex.Match(authHeader, @"(?<=^\s*bearer\s+).+$", RegexOptions.IgnoreCase);

var result = authInfo.AuthContext.AcquireToken(resourceId, authInfo.Credential, 
    new UserAssertion(tokenMatch.Value));

return result.AccessToken;
Run Code Online (Sandbox Code Playgroud)

必须有一个更好的方法,但我已经尝试过AcquireToken许多不同的重载,这是我能让它工作的唯一方法.我尝试了AcquireTokenSilent,它在我的客户端应用程序中工作,因为TokenCache中有一个令牌,但是当我尝试使用WebApi时,似乎没有任何地方可以实现TokenCache.

authentication jwt asp.net-web-api owin azure-active-directory

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

如何使用带有Owin的WebApi 2的swashbuckle生成文档

我使用这篇文章创建了一个WebApi项目.

事情很好.但现在我的客户想要使用Swagger查看文档.我试着做配置,但事情没有用.没有获得控制器列表及其操作.

在此输入图像描述

下面是招摇配置:

using System.Web.Http;
using WebActivatorEx;
using DC.SUMS.WebAPI1;
using Swashbuckle.Application;
using System;
using System.Linq;
using Swashbuckle.Swagger;
using Swashbuckle.Dummy.SwaggerExtensions;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]

namespace DC.SUMS.WebAPI1
{
    public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration 
                .EnableSwagger(c =>
                {

                        // By default, the service root url is inferred from the request used to access the docs.
                        // However, there may be situations (e.g. proxy and load-balanced environments) where this does not
                        // resolve correctly. You …
Run Code Online (Sandbox Code Playgroud)

swagger owin webapi2

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

无法使用Owin注销Web Api

我已经使用owin登录但无法退出.
在开始:

 
public void ConfigureOAuth(IAppBuilder app)
        {
   OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
                Provider = new AuthorizationServerProvider(),
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie               
            };
            app.UseOAuthBearerTokens(OAuthServerOptions);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
        }

在AuthorizationServerProvider中:

 public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult(null);
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*"});
            using (demoEntities _repo = new demoEntities())
            {
                if (!_repo.users.Where(x => x.username == context.UserName && x.pass == context.Password).Any())
                {
                    context.SetError("invalid_grant", "wrong.");
                    //context.Rejected();
                    return;
                } …

asp.net-web-api owin

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

User.Identity.GetUserId()Owin Moq单元测试

我有ChangePassword方法,我必须User.Identity.GetUserId()找到UserId.

问题:它总是返回null.不明白为什么.

我在另一篇文章中读到了GetUserById使用下面的代码行查找Id.我不知道如何嘲笑ClaimsTypes.NameIdentifier.

return ci.FindFirstValue(ClaimTypes.NameIdentifier);

ChangePassword方法(单位测试的方法)

public async Task<IHttpActionResult> ChangePassword(string NewPassword, string OldPassword)
{

    _tstService = new TestService();
    IdentityResult result = await _tstService.ChangePassword(User.Identity.GetUserId(), OldPassword, NewPassword);

    if (!result.Succeeded)
    {
        return GetErrorResult(result);
    }

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

单元测试

var mock = new Mock<MyController>();
mock.CallBase = true;
var obj = mock.Object;

obj.ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() };
obj.Request.SetOwinContext(CommonCodeHelper.mockOwinContext());

IPrincipal user = GetPrincipal();
obj.ControllerContext.RequestContext.Principal = user;
var result = …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq asp.net-web-api owin

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

OWIN中间件+ Web API +简单注入器

我目前正在使用WebApiRequestLifestyle具有默认的范围生活方式.我想在OWIN中间件和其中一个API控制器中注入一个服务,服务的范围应该仍然是WebAPI,即对于整个请求,应该只有一个服务实例.

public class TestMiddleware : OwinMiddleware
{
    private readonly ITestService _testService;

    public TestMiddleware(OwinMiddleware next, ITestService testService) : base(next)
    {
        _testService = testService;
    }

    public override async Task Invoke(IOwinContext context)
    {
        var test = _testService.DoSomething();
        await Next.Invoke(context);
    }
}

public class ValuesController : ApiController
{
    private readonly ITestService _testService;

    public ValuesController(ITestService testService)
    {
        _testService = testService;
    }
}
Run Code Online (Sandbox Code Playgroud)

整个请求的ITestService实例应该相同.我该如何注册中间件?

这就是我现在这样做的方式:

     using (container.BeginExecutionContextScope())
        {
            var testService = container.GetInstance<ITestService>();
            app.Use<TestMiddleware>(testService);
        }
Run Code Online (Sandbox Code Playgroud)

这种方法的问题是 - 在注册期间为中间件创建一个ITestService实例并永久保留(如单例),并且对于每个webapi请求,都会在控制器之间创建和共享新实例(webapi范围)

请不要指出这些问题 - WebApi + Simple Injector + OWIN

使用Simple …

c# dependency-injection simple-injector asp.net-web-api owin

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

Facebook身份验证AuthenticationManager.GetExternalLoginInfoAsync()突然返回NULL

public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {


            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null) { return RedirectToAction("Login"); }
            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
Run Code Online (Sandbox Code Playgroud)

所以在我的ExternalLoginCallback方法AuthenticationManager.GetExternalLoginInfoAsync()中工作得很好,然后突然几天前它不再做任何事情并返回NULL,导致整个"注册Facebook"进程被跳过,将用户重定向到登录页面.

我有一个单独的ASP.NET MVC5项目,我只是用Facebook Graph API来玩,当我回到它时(我在2周前离开它,注册/登录Facebook在这个项目上工作得很好)它有同样的问题,它返回null!将用户重定向到登录页面.

有可能我的Facebook应用程序有什么东西吗?或他们的API?我没有通过应用程序审查3次(在代码中有一些问题),把它放回到开发模式试图解决它现在它甚至没有达到上一个问题,它停在AuthenticationManager.GetExternalLoginInfoAsync()那里我无法理解什么是去因为我上周没有这个问题.

这是ExternalLogin方法:

public ActionResult ExternalLogin(string provider, string returnUrl)
        {

            ControllerContext.HttpContext.Session.RemoveAll();

            return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
        }
Run Code Online (Sandbox Code Playgroud)

我添加ControllerContext.HttpContext.Session.RemoveAll();了一个建议,我在stackoverflow上找到了它,但似乎没有做任何事情.

authentication asp.net-mvc facebook facebook-graph-api owin

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