Exemplo n.º 1
0
        public void Configuration(IAppBuilder app)
        {
            dependencyResolver.Register(this.GetType().Assembly);

            var oAuthAuthorizationServerProvider = new OAuthAuthorizationServerProvider()
            {
                OnValidateClientAuthentication  = async c => await this.ValidateClientAuthentication(c),
                OnGrantResourceOwnerCredentials = async c => await this.GrantResourceOwnerCredentials(c),
            };

            var oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString(this.GetTokenEndpointPath()),
                Provider          = oAuthAuthorizationServerProvider,
                AllowInsecureHttp = true,
            };

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            //app.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions);
            app.UseConfiguration(dependencyResolver);

            dependencyResolver.Resolve <HttpConfiguration>()
            .EnableSwagger(c => c.SingleApiVersion("v1", "PhoneChoiceHelper API"))
            .EnableSwaggerUi();

            dependencyResolver.Resolve <HttpConfiguration>()
            .Count()
            .Filter()
            .OrderBy()
            .Expand()
            .Select()
            .MaxTop(null)
            .EnableDependencyInjection();
            ;
        }
 private void LookupClient(OAuthAuthorizationServerProvider provider,
                           string knownClientId,
                           string knownClientSecret,
                           string knownRedirectUri)
 {
     provider.OnValidateClientRedirectUri = ctx =>
     {
         LastLookupClientId = ctx.ClientId;
         if (string.Equals(ctx.ClientId, knownClientId, StringComparison.Ordinal))
         {
             ctx.Validated(knownRedirectUri);
         }
         return(Task.FromResult(0));
     };
     provider.OnValidateClientAuthentication = ctx =>
     {
         string clientId;
         string clientSecret;
         if (ctx.TryGetBasicCredentials(out clientId, out clientSecret) ||
             ctx.TryGetFormCredentials(out clientId, out clientSecret))
         {
             LastLookupClientId = clientId;
             if (string.Equals(clientId, knownClientId, StringComparison.Ordinal) &&
                 string.Equals(clientSecret, knownClientSecret, StringComparison.Ordinal))
             {
                 ctx.Validated(clientId);
             }
         }
         return(Task.FromResult(0));
     };
 }
Exemplo n.º 3
0
        //OAuth身份验证
        public static void OAuth(IAppBuilder app)
        {
            var oauthProvider = new OAuthAuthorizationServerProvider
            {
                OnGrantResourceOwnerCredentials = async context =>
                {
                    if (context.UserName == "rranjan" && context.Password == "password@123")
                    {
                        var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                        claimsIdentity.AddClaim(new Claim("user", context.UserName));
                        claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                        claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "ApiUser"));
                        claimsIdentity.AddClaim(new Claim(ClaimTypes.UserData, "{Name:'User',Age:12}"));
                        context.Validated(claimsIdentity);
                        return;
                    }
                    context.Rejected();
                },
                OnValidateClientAuthentication = async context =>
                {
                    string clientId;
                    string clientSecret;
                    if (context.TryGetBasicCredentials(out clientId, out clientSecret))
                    {
                        if (clientId == "rajeev" && clientSecret == "secretKey")
                        {
                            context.Validated();
                        }
                    }
                    else if (context.TryGetFormCredentials(out clientId, out clientSecret))
                    {
                        if (clientId == "rajeev" && clientSecret == "secretKey")
                        {
                            context.Validated();
                        }
                    }
                    //context.Validated();
                }
            };

            var oauthOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/accesstoken"),
                Provider          = oauthProvider,
                AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
                AccessTokenExpireTimeSpan       = TimeSpan.FromHours(3),
                SystemClock = new SystemClock()
            };

            app.UseOAuthAuthorizationServer(oauthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Exemplo n.º 4
0
        private static void ConfigureAuth(IAppBuilder app, OAuthAuthorizationServerProvider oAuthServerProvider)
        {
            var oAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = oAuthServerProvider,
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),

                // Only do this for demo!!
                AllowInsecureHttp = true
            };

            app.UseOAuthAuthorizationServer(oAuthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
        public void Configuration(IAppBuilder app)
        {
            var oauthProvider = new OAuthAuthorizationServerProvider
            {
                OnGrantResourceOwnerCredentials = async context =>
                {
                    if (context.UserName == "xyz" && context.Password == "xyz@123")
                    {
                        var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                        claimsIdentity.AddClaim(new Claim("user", context.UserName));
                        context.Validated(claimsIdentity);
                        return;
                    }
                    context.Rejected();
                },
                OnValidateClientAuthentication = async context =>
                {
                    string clientId;
                    string clientSecret;
                    if (context.TryGetBasicCredentials(out clientId, out clientSecret))
                    {
                        if (clientId == "xyz" && clientSecret == "secretKey")
                        {
                            context.Validated();
                        }
                    }
                }
            };
            var oauthOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/accesstoken"),
                Provider          = oauthProvider,
                AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
                AccessTokenExpireTimeSpan       = TimeSpan.FromMinutes(3),
                SystemClock = new SystemClock()
            };

            app.UseOAuthAuthorizationServer(oauthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            app.UseWebApi(config);
        }
Exemplo n.º 6
0
        public void Configuration(IAppBuilder app)
        {
            var provider = new OAuthAuthorizationServerProvider
            {
                OnValidateClientAuthentication = ctx =>
                {
                    ctx.Validated();
                    return(Task.FromResult(0));
                },
                OnGrantResourceOwnerCredentials = ctx =>
                {
                    if (ctx.UserName == "maurice" && ctx.Password == "pass")
                    {
                        var identity = new ClaimsIdentity(new[]
                        {
                            new Claim(ClaimTypes.Name, ctx.UserName)
                        }, "password");
                        ctx.Validated(identity);
                    }
                    return(Task.FromResult(0));
                }
            };

            var options = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/token"),
                Provider          = provider,
                AllowInsecureHttp = true // Never do this in production
            };

            app.UseOAuthAuthorizationServer(options);

            var authenticationOptions = new OAuthBearerAuthenticationOptions();

            app.UseOAuthBearerAuthentication(authenticationOptions);


            app.Map("/api", apiApp =>
            {
                var config = new HttpConfiguration();
                config.MapHttpAttributeRoutes();
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationAttribute(authenticationOptions.AuthenticationType));
                apiApp.UseWebApi(config);
            });
        }
Exemplo n.º 7
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login")
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            #region ServerOAuth

            app.UseOAuthBearerAuthentication(new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions
                                                 ()
            {
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                AuthenticationType = "Emad",
                Realm = "EHM"     //anything
            });

            var options = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions();
            options.TokenEndpointPath     = new PathString("/account/token");
            options.AuthorizeEndpointPath = new PathString("/account/auth");
            options.AllowInsecureHttp     = true; //Don't do that!! always be on secure scheme, this is set to "true" for demo purposes
            var provider = new OAuthAuthorizationServerProvider();

            provider.OnValidateClientRedirectUri = (context) =>
            {
                return(Task.Run(() =>
                {
                    //Caution: this is not to validate that the uri is valid syntax wise, this is to validate it business wise. If this uri is not
                    //valid syntax wise this entry will not be hit in the first place, and your authentication process will not work!
                    context.Validated();
                }));
            };

            provider.OnValidateAuthorizeRequest = (context) =>
            {
                return(Task.Run(() =>
                {
                    //Authorization validation here
                    //Somewhere in the request you should create the identity and sign in with it, I put it here, it could be a page on your app?
                    context.OwinContext.Authentication.SignIn(new System.Security.Claims.ClaimsIdentity("Bearer"));
                    context.Validated();
                }));
            };

            provider.OnAuthorizeEndpoint = (context) =>
            {
                return(Task.Run(() =>
                {
                    //This is the last chance to alter the request, you can either end it here using RequestCompleted and start resonding,
                    //or you can let it go through to the subsequent middleware,
                    //except that you have to make sure the response returns a 200, otherwise the whole thing will not work
                    context.RequestCompleted();
                    var str = context.Options.AccessTokenFormat;
                }));
            };


            provider.OnValidateClientAuthentication = (context) =>
            {
                return(Task.Run(() =>
                {
                    //Client validation here
                    context.Validated();
                }));
            };

            options.Provider = provider;

            AuthenticationTokenProvider authTokenProvider = new AuthenticationTokenProvider();
            authTokenProvider.OnCreate = (context) =>
            {
                //create a dummy token
                context.SetToken("MyTokenblablabla");
            };

            //This is called when a client is requesting with Authorization header and passing the token, like this "Authorization: Bearer jdksjkld"
            authTokenProvider.OnReceive = (context) =>
            {
                //create dummy identity regardless of the validty of the token :)
                var claimsIdentity = new System.Security.Claims.ClaimsIdentity("Bearer");
                claimsIdentity.AddClaim(new Claim("something", "Ahmad")); //This claim type "something" is used for protection from anti-forgery...
                //Check the Global.asax for "AntiForgeryConfig.UniqueClaimTypeIdentifier = "something";"
                //you can avoid setting this, but you have to use the default claims type. check http://bartwullems.blogspot.com.au/2013/09/aspnet-mvc-4-error-when-using-anti.html

                context.SetTicket(new Microsoft.Owin.Security.AuthenticationTicket(claimsIdentity,
                                                                                   new Microsoft.Owin.Security.AuthenticationProperties
                {
                    ExpiresUtc = new System.DateTimeOffset(2015, 3, 1, 1, 1, 1, new System.TimeSpan()),
                }
                                                                                   ));
            };

            options.AuthorizationCodeProvider = authTokenProvider;
            options.RefreshTokenProvider      = authTokenProvider;
            options.AccessTokenProvider       = authTokenProvider;

            app.UseOAuthBearerTokens(options);

            #endregion

            //app.UseGoogleAuthentication();
        }
Exemplo n.º 8
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            var oauthProvider = new OAuthAuthorizationServerProvider
            {
                OnGrantResourceOwnerCredentials = async context =>
                {
                    if (context.UserName == "xyz" && context.Password == "xyz@123")
                    {
                        var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                        claimsIdentity.AddClaim(new Claim("user", context.UserName));
                        context.Validated(claimsIdentity);
                        return;
                    }
                    context.Rejected();
                },
                OnValidateClientAuthentication = async context =>
                {
                    string clientId;
                    string clientSecret;
                    if (context.TryGetBasicCredentials(out clientId, out clientSecret))
                    {
                        if (clientId == "xyz" && clientSecret == "secretKey")
                        {
                            context.Validated();
                        }
                    }
                }
            };
            var oauthOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/accesstoken"),
                Provider          = oauthProvider,
                AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
                AccessTokenExpireTimeSpan       = TimeSpan.FromMinutes(3),
                SystemClock = new SystemClock()
            };

            app.UseOAuthAuthorizationServer(oauthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            app.UseWebApi(config);
            //  // Configure the db context and user manager to use a single instance per request
            //  app.CreatePerOwinContext(ApplicationDbContext.Create);
            //  app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            //  // Enable the application to use a cookie to store information for the signed in user
            //  // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            //  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(),
            //      AuthorizeEndpointPath = new PathString("/api/SignProcess/Validateuser"),
            //      AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            //      // In production mode set AllowInsecureHttp = false
            //      AllowInsecureHttp = true
            //  };

            //  // Enable the application to use bearer tokens to authenticate users
            //  app.UseOAuthBearerTokens(OAuthOptions);

            //  // Uncomment the following lines to enable logging in with third party login providers
            //  //app.UseMicrosoftAccountAuthentication(
            //  //    clientId: "",
            //  //    clientSecret: "");

            //  //app.UseTwitterAuthentication(
            //  //    consumerKey: "",
            //  //    consumerSecret: "");

            //  //app.UseFacebookAuthentication(
            //  //    appId: "",
            //  //    appSecret: "");

            //  //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //  //{
            //  //    ClientId = "",
            //  //    ClientSecret = ""
            //  //});
        }