多个提供商web api

时间:2016-10-03 12:54:27

标签: c# asp.net asp.net-web-api

我正在开发一个ASP.NET WEB API多客户端应用程序。第一个客户端通过用户名和密码验证,第二个客户端通过代码验证(字符串类型)。

是否可以在同一个应用中拥有多个提供商? 这是代码:

public void ConfigureAuth(IAppBuilder app)
{
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";

          OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),

            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

 }

在我的ApplicationOAuthProvider类中,我也验证了代码,但第一个应用程序不使用代码。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{   
    var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
    ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
    ApplicationUser userByName = await userManager.FindByNameAsync(context.UserName);

    var data = await context.Request.ReadFormAsync();
    var code = data["code"];

    if (userByName == null || userByName.Code != code)
    {
        context.SetError("invalid_grant", "The user name or password is incorrect.");
        return;
    }


    ClaimsIdentity oAuthIdentity = await userByName.GenerateUserIdentityAsync(userManager,                   OAuthDefaults.AuthenticationType);
    ClaimsIdentity cookiesIdentity = await userByNameCristina.GenerateUserIdentityAsync(userManager,
    CookieAuthenticationDefaults.AuthenticationType);

    AuthenticationProperties properties = CreateProperties(userByNameCristina.UserName,data["code"]);
    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
    context.Validated(ticket);
    context.Request.Context.Authentication.SignIn(cookiesIdentity);
}

1 个答案:

答案 0 :(得分:0)

我启用了OAuth和基于自定义Cookie的解决方案。

Web Api配置

   app.UseWebLoginAuthentication(Container); // Custom cookie solution
   ConfigureIdentityManager(app); // Identify manager
   ConfigureAuth(app); // OAuth provider

AuthenticationMiddleware 充当工厂

public class WebLoginAuthenticationMiddleware : AuthenticationMiddleware<WebLoginAuthenticationOptions>
{
    public WebLoginAuthenticationMiddleware(OwinMiddleware nextMiddleware,
                                            WebLoginAuthenticationOptions authOptions)
        : base(nextMiddleware, authOptions)
    {

    }

    protected override AuthenticationHandler<WebLoginAuthenticationOptions> CreateHandler()
    {
        return new WebLoginAuthenticationHandler();
    }
}

<强>的AuthenticationHandler

internal class WebLoginAuthenticationHandler : AuthenticationHandler<WebLoginAuthenticationOptions>
{
    protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
    {
        await Task.Yield();

        var cookie = Context.Request.Cookies[config.CookieName];

        // Return unauthorized if no cookie exists.
        if (cookie == null)
            return null;

        //Check authentication
        // do stuff...

        //User is authenticated - cookie match found 
        var authenticationProperties = CreateAuthenticationProperties(session);

        var identity = CreateIdentity(buildings, session);
        return new AuthenticationTicket(identity, authenticationProperties);
    }

    private static AuthenticationProperties CreateAuthenticationProperties()
    {
        return new AuthenticationProperties
        {
            IssuedUtc = DateTime.UtcNow,
            ExpiresUtc = DateTime.UtcNow.AddHours(12),
            AllowRefresh = true,
            IsPersistent = true
        };
    }

    private ClaimsIdentity CreateIdentity()
    {
        var identity = new ClaimsIdentity(Options.AuthenticationType);
        // add claims
        return identity;
    }
}