Esempio n. 1
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            if (!File.Exists(SqliteBaseRepository.DbLocation))
            {
                SqliteBaseRepository.CreateDatabase();
            }

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(7),
                Provider = myProvider
            };

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

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Esempio n. 2
0
        public void Configuration(IAppBuilder app)
        {
            // ENABLE CORS
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            // IDENTITY SECURITY
            var myProvider = new AuthorizationServerProvider();

            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(5),
                Provider = myProvider
            };

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

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);

            // SignalR Mapper
            app.MapSignalR("/dothelpnationchat", new Microsoft.AspNet.SignalR.HubConfiguration());
        }
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            //enable cors origin requests
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            app.MapSignalR();

            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
                Provider             = myProvider,
                RefreshTokenProvider = new RefreshTokenProvider()
            };

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

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Esempio n. 4
0
        public void Configuration(IAppBuilder app)
        {
            //ConfigureAuth(app);

            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                //AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(Convert.ToInt32(ConfigurationManager.AppSettings["TokenExpire"].ToString())),
                Provider = myProvider
            };

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


            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "Your Google Client Id",
            //    ClientSecret = "Your Google Client Secret"
            //});

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Esempio n. 5
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); //enable cors origin request


            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"), //url where we get the signed token from (i.e. localhost:1236/token)
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),     //We’ve specified the expiry for token to be 24 hours, so if the user tried to use the same token for authentication after 24 hours from the issue time, his request will be rejected and HTTP status code 401 is returned
                Provider = myProvider
            };



            //Token Generation
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()).UseStageMarker(PipelineStage.Authenticate);
            app.UseOAuthAuthorizationServer(options); //we tell the app user our configuration

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }
Esempio n. 6
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); //enable cors origin request


            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };



            //Token Generation
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()).UseStageMarker(PipelineStage.Authenticate);
            app.UseOAuthAuthorizationServer(options); //we tell the app user our configuration

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }
        /// <summary>
        /// Specifies how the ASP.NET application will respond to individual HTTP request.
        /// </summary>
        /// <param name="app">Instance of <see cref="IAppBuilder"/>.</param>
        public void Configuration(IAppBuilder app)
        {
            //enable cors origin request
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
                Provider          = myProvider,
                AccessTokenFormat = new CustomJwtFormat()
            };

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            new ApiConfig(app)
            .ConfigureCorsMiddleware(ConfigurationManager.AppSettings["cors"])
            .ConfigureAufacMiddleware()
            .ConfigureFormatters()
            .ConfigureRoutes()
            .ConfigureExceptionHandling()
            .ConfigureSwagger()
            .UseWebApi();
        }
Esempio n. 8
0
        public JObject GenerateLocalAccessTokenResponse(SocialRegisterModel socialRegisterModel)
        {
            //ToSocialregisterModel
            try
            {
                if (socialRegisterModel != null)
                {
                    var tokenExpiration = TimeSpan.FromSeconds(2);
                    var props           = new AuthenticationProperties()
                    {
                        IssuedUtc  = DateTime.UtcNow,
                        ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
                    };
                    var            user     = IService.ToSocialregisterModel(socialRegisterModel);
                    ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
                    identity.AddClaim(new Claim(ClaimTypes.Role, "SuperAdmin"));
                    identity.AddClaim(new Claim(ClaimTypes.Name, socialRegisterModel.UserName));
                    identity.AddClaim(new Claim("UserId", user.Id.ToString()));
                    identity.AddClaim(new Claim("DisplayName", user.DisplayName));
                    identity.AddClaim(new Claim("isAdmin", user.IsAdmin.ToString()));
                    identity.AddClaim(new Claim("LastLoginDate", user.LastLoginTime.ToString()));

                    AuthenticationProperties properties = AuthorizationServerProvider.CreateProperties(
                        socialRegisterModel.UserName, user.Id.ToString(), user.DisplayName, user.IsNGO.ToString(), user.CanEndorse.ToString(),
                        user.IsAdmin.ToString(), user.LastLoginTime.ToString());

                    //        //AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                    AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);

                    // var ticket = new AuthenticationTicket(identity, props);

                    var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

                    JObject tokenResponse = new JObject(
                        new JProperty("userName", socialRegisterModel.UserName),
                        new JProperty("UserId", user.Id.ToString()),
                        new JProperty("DisplayName", user.DisplayName),
                        new JProperty("IsNGO", user.IsNGO.ToString()),
                        new JProperty("canEndorse", user.CanEndorse.ToString()),
                        new JProperty("access_token", accessToken),
                        new JProperty("token_type", "bearer"),
                        new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
                        new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
                        new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString()),
                        new JProperty(".isAdmin", user.IsAdmin.ToString()),
                        new JProperty(".LastLoginDate", user.LastLoginTime.ToString())
                        );

                    return(tokenResponse);
                }
                else
                {
                    JObject tokenResponse = new JObject(new JProperty("response", "BadRequest"));
                    return(tokenResponse);
                }
            }
            catch (Exception ex)
            { throw ex; }
        }
Esempio n. 9
0
 public bool update([FromBody] Post post)
 {
     if (post.UserId == AuthorizationServerProvider.getUserId())
     {
         return(false);
     }
     return(source.Update(post));
 }
 public Boolean UpdateCommentaire([FromBody] Commentaire commentaire)
 {
     if (commentaire != null && commentaire.userId == AuthorizationServerProvider.getUserId())
     {
         source.Update(commentaire);
         return(true);
     }
     else
     {
         return(false);
     }
 }
Esempio n. 11
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                                 externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = AuthorizationServerProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return(Ok());
        }
        public void TestMethod1()
        {
            var provider = new AuthorizationServerProvider <OAuthAuthenticator>(new OAuthAuthenticator());

            provider.Configure()
            .AccessControlAllowOrigin("*")
            .AccessControlAllowCredentials(true)
            .TokenData(c => c.Map(p => p.Id)
                       .Map(p => p.Name)
                       .Map(p => p.IsAdmin))
            .Messages(m => m.Set(AuthResult.Unauthorized, "Vaza mermão")
                      .Set(AuthResult.Success, "lalala"))
            .OnError(args => { });
        }
Esempio n. 13
0
        public Boolean UpdateProfile([FromBody] User user)
        {
            if (user.userId != AuthorizationServerProvider.getUserId())
            {
                return(false);
            }
            if (user != null)
            {
                user.permision = Roles.USER_ROLE;

                return(source.Update(user));
            }
            else
            {
                return(false);
            }
        }
Esempio n. 14
0
        private void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/oauth/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider,
                //AccessTokenFormat = new CustomJwtFormat("http://localhost:55164")
                AccessTokenFormat = new CustomJwtFormat(urlhc)
                                    //AccessTokenFormat = new CustomJwtFormat("http://hoangchu.somee.com/")
                                    //AccessTokenFormat = new CustomJwtFormat("http://192.168.43.217/quanlynhansuCNTT/")
            };

            app.UseOAuthAuthorizationServer(OAuthServerOptions);
        }
Esempio n. 15
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var jpaProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/Token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = jpaProvider
            };

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

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Esempio n. 16
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

            app.UseCors(CorsOptions.AllowAll);
            var AuthenticationProvider = new AuthorizationServerProvider();

            OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = AuthenticationProvider
            };

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

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Esempio n. 17
0
        public void Configuration(IAppBuilder app)
        {
            app.Use(typeof(HeaderSetter));
            app.UseCors(CorsOptions.AllowAll);

            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
                Provider             = myProvider,
                RefreshTokenProvider = new RefreshTokenProvider()
            };

            app.UseOAuthAuthorizationServer(options);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);
        }
Esempio n. 18
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
                Provider = myProvider
            };

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

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);

            GlobalConfiguration.Configuration.Filters
            .Add(new Helpers.Filters.GeneralExceptionAttribute(new ExceptionLoggerToDB(new ExceptionDao())));
            //.Add(new Helpers.Filters.GeneralExceptionAttribute(new ExceptionLoggerToFile()));
        }
Esempio n. 19
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(3600),
                Provider             = myProvider,
                RefreshTokenProvider = new RefreshTokenProvider()
            };

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

            OAuthBearerAuthenticationOptions OAuthBearerOptions = new OAuthBearerAuthenticationOptions()
            {
                Provider = new QueryStringOAuthBearerProvider()
            };

            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            // Configure the db context, user manager and signin manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.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
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
                    OnApplyRedirect = ctx =>
                    {
                        if (!IsAjaxRequest(ctx.Request))
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                    }
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // 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 = ""
            //});
        }
Esempio n. 20
0
 public IEnumerable <Post> GetUserPost()
 {
     return(source.GetPostByUser(AuthorizationServerProvider.getUserId()));
 }
Esempio n. 21
0
 public Boolean DeleteUser()
 {
     return(source.Delete(AuthorizationServerProvider.getUserId()));
 }
 public Boolean DeleteCommentaire(int id)
 {
     return(source.Delete(AuthorizationServerProvider.getUserId(), id));
 }
Esempio n. 23
0
 public void Create([FromBody] Post post)
 {
     post.UserId = AuthorizationServerProvider.getUserId();
     source.Add(post);
 }
Esempio n. 24
0
 public bool Delete(int id)
 {
     return(source.DeleteUserPost(AuthorizationServerProvider.getUserId(), id));
 }
Esempio n. 25
0
 public Boolean DeleteLike(int postId)
 {
     return(source.Delete(postId, AuthorizationServerProvider.getUserId()));
 }