コード例 #1
0
        protected override async Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            TokenRequirement requirement)
        {
            IAuthOptions authOptions = requirement.AuthOptions; //GeneralContext.GetService<IAuthOptions>();
            var          httpContext = GeneralContext.HttpContext;

            string authHeader = httpContext.Request.Headers["Authorization"];

            if (!string.IsNullOrEmpty(authHeader))
            {
                authHeader = authHeader.Replace("Bearer ", "");
                if (Util.VerifyToken(authHeader, authOptions.KEY))
                {
                    context.Succeed(requirement);
                }
            }
            else
            {
                context.Fail();
                throw new UnauthorizedAccessException();
            }

            await Task.CompletedTask;
        }
コード例 #2
0
        internal static string[] GetScopes(this IAuthOptions options)
        {
            if (options.Scopes is null || options.Scopes.Length == 0)
            {
                return(new[] { $"{options.Tenant.GetTenantName()}/mobile/read" });
            }

            return(options.Scopes);
        }
コード例 #3
0
 public JWTlabberValidationParameters(IAuthOptions authOptions) : base()
 {
     ValidateIssuer           = true;
     ValidateAudience         = true;
     ValidateLifetime         = true;
     ValidateIssuerSigningKey = true;
     ValidIssuer      = authOptions.Issuer;
     ValidAudience    = authOptions.Audience;
     IssuerSigningKey = authOptions.GetSymmetricSecurityKey();
     ClockSkew        = TimeSpan.FromSeconds(0);
 }
コード例 #4
0
        public static JwtBearerEvents ConfigureJwtBearerEvents()
        {
            return(new JwtBearerEvents
            {
                OnAuthenticationFailed = context =>
                {
                    if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                    {
                        context.Response.Headers.Add("Token-Expired", "true");
                    }
                    return Task.CompletedTask;
                },
                OnTokenValidated = context =>
                {
                    // Add the access_token as a claim, as we may actually need it
                    var accessToken = context.SecurityToken as JwtSecurityToken;
                    if (accessToken != null)
                    {
                        ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity;
                        if (identity != null)
                        {
                            identity.AddClaim(new Claim("access_token", accessToken.RawData));
                            IAuthOptions authOptions = GeneralContext.GetService <IAuthOptions>();
                            AppUser appUser = Util.ReadToken <AppUser>(accessToken.RawData, authOptions.KEY);

                            if (appUser != null)
                            {
                                context.Success();
                            }
                            else
                            {
                                context.Fail("Unauthorized");
                            }
                        }
                    }

                    if (!context.Result.Succeeded)
                    {
                        context.Response.Headers.Add("Token-OnTokenValidated", "false");
                    }

                    return Task.CompletedTask;
                },
                OnChallenge = context =>
                {
                    if (context.Response.StatusCode < 200 || context.Response.StatusCode > 299)
                    {
                        context.Response.Headers.Add("Token-OnChallenge", "false");
                    }
                    return Task.CompletedTask;
                },
            });
        }
コード例 #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            ExperimentalToolLogger logger,
            IAuthOptions options)
        {
            logger.LogExperimentMessage();
            if (options.KeyAuthenticationMode == KeyAuthenticationMode.NoAuth)
            {
                logger.LogNoAuthMessage();
            }
            else
            {
                //Auth is enabled and we are binding on http. Make sure we log a warning.

                string   hostingUrl = Configuration.GetValue <string>(WebHostDefaults.ServerUrlsKey);
                string[] urls       = ConfigurationHelper.SplitValue(hostingUrl);
                foreach (BindingAddress address in urls.Select(BindingAddress.Parse))
                {
                    if (string.Equals(Uri.UriSchemeHttp, address.Scheme, StringComparison.OrdinalIgnoreCase))
                    {
                        logger.LogInsecureAuthMessage();
                        break;
                    }
                }
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseAuthentication();
            app.UseAuthorization();

            CorsConfiguration corsConfiguration = new CorsConfiguration();

            Configuration.Bind(nameof(CorsConfiguration), corsConfiguration);
            if (!string.IsNullOrEmpty(corsConfiguration.AllowedOrigins))
            {
                app.UseCors(builder => builder.WithOrigins(corsConfiguration.GetOrigins()).AllowAnyHeader().AllowAnyMethod());
            }

            app.UseResponseCompression();
            app.UseMvc();
        }
コード例 #6
0
        /// <summary>
        /// Add Authentication and Authorisation to the available app services
        /// </summary>
        /// <param name="services">The services collection to be configured</param>
        /// <param name="authOptions">An AuthOptions instance containing Auth configuration data</param>
        /// <param name="authClaims">An AuthClaims instance containing Claims configuration data</param>
        public static void AddCrudRAuthentication(this IServiceCollection services,
                                                  IAuthOptions authOptions,
                                                  IAuthClaims authClaims)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Audience = authOptions.Audience;

                if (!authOptions.UseLocalIssuerSigningKey)
                {
                    options.Authority = authOptions.Authority;
                }

                if (authOptions.UseLocalIssuerSigningKey)
                {
                    var signingKey = string.IsNullOrEmpty(authOptions.IssuerSigningKey) ?
                                     new X509SecurityKey(new X509Certificate2(authOptions.IssuerSigningKeyFilePath)) :
                                     new X509SecurityKey(new X509Certificate2(Encoding.ASCII.GetBytes(authOptions.IssuerSigningKey)));

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        ValidateIssuer           = true,
                        ValidIssuer      = authOptions.Authority,
                        IssuerSigningKey = signingKey
                    };
                }
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Get", policy =>
                                  policy.AddRequirements(DiscernRequirements(authClaims.GetAllowAnonymous, authClaims.GetClaim, authClaims.GetClaimValue)));

                options.AddPolicy("Post", policy =>
                                  policy.AddRequirements(DiscernRequirements(authClaims.PostAllowAnonymous, authClaims.PostClaim, authClaims.PostClaimValue)));

                options.AddPolicy("Put", policy =>
                                  policy.AddRequirements(DiscernRequirements(authClaims.PutAllowAnonymous, authClaims.PutClaim, authClaims.PutClaimValue)));

                options.AddPolicy("Delete", policy =>
                                  policy.AddRequirements(DiscernRequirements(authClaims.DeleteAllowAnonymous, authClaims.DeleteClaim, authClaims.DeleteClaimValue)));
            });
        }
コード例 #7
0
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            ClaimsPrincipal result = null;
            SecurityToken   token  = null;

            Task.WaitAll(Task.Run(() =>
            {
                IAuthOptions authOptions = GeneralContext.GetService <IAuthOptions>();
                AppUser appUser          = Util.ReadToken <AppUser>(securityToken, authOptions.KEY);
                if (appUser == null)
                {
                    result = null;
                    token  = null;
                }
                else
                {
                    var claims = new List <Claim> {
                        new Claim(ClaimTypes.Name, appUser.UserName)
                    };
                    var newClaimsIdentity = new ClaimsIdentity(claims);
                    result = new ClaimsPrincipal(newClaimsIdentity);

                    var key = Encoding.ASCII.GetBytes(authOptions.KEY);
                    token   = new ApiSecurityToken(appUser.Id, "Token",
                                                   new SymmetricSecurityKey(key),
                                                   new SymmetricSecurityKey(key),
                                                   DateTime.Now,
                                                   DateTime.Now.AddDays(authOptions.LIFETIME));

                    var authProperties = new AuthenticationProperties
                    {
                        AllowRefresh = true,
                        ExpiresUtc   = DateTimeOffset.Now.AddDays(365),
                        IsPersistent = true,
                    };

                    //AuthenticationOptions
                    //await GeneralContext.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, result, authProperties);
                    //if (GeneralContext.HttpContext.User.Identity.IsAuthenticated)
                    //{
                    //    //IAuthenticationService authenticationService = GeneralContext.GetService<IAuthenticationService>();
                    //    await GeneralContext.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, result);
                    //}
                }
            }));

            validatedToken = token;
            return(result);
        }
コード例 #8
0
        public async Task InvokeAsync(HttpContext context)
        {
            IAuthOptions authOptions = GeneralContext.GetService <IAuthOptions>();
            var          token       = context.GetRequestHeader(HttpRequestHeader.Authorization);
            var          loggedUser  = Util.ReadToken <AppUser>(token, authOptions.KEY);

            //var loggedUser = JsonConvert.DeserializeObject<AppUser>(context.GetRequestHeader(HttpRequestXHeader.User));
            if (loggedUser != null && !string.IsNullOrEmpty(loggedUser.FirstName))
            {
                loggedUser.FirstName = loggedUser.FirstName.ToStringUtf8();
            }

            if (loggedUser != null && !string.IsNullOrEmpty(loggedUser.LastName))
            {
                loggedUser.LastName = loggedUser.LastName.ToStringUtf8();
            }

            context.Items.TryAdd(SessionKeys.AppUser.GetDisplayName(), loggedUser);

            var dataString = context.GetRequestHeader(HttpRequestXHeader.Data);

            if (!string.IsNullOrEmpty(dataString))
            {
                var data = JsonConvert.DeserializeObject <Dictionary <string, string> >(context.GetRequestHeader(HttpRequestXHeader.Data));
                if (data != null)
                {
                    context.Items.TryAdd(SessionKeys.ClientName.GetDisplayName(), data[SessionKeys.ClientName.GetDisplayName()]);
                    context.Items.TryAdd(SessionKeys.DbName.GetDisplayName(), data[SessionKeys.DbName.GetDisplayName()]);
                    context.Items.TryAdd(SessionKeys.SelectedCultureName.GetDisplayName(), data[SessionKeys.SelectedCultureName.GetDisplayName()]);
                    context.Items.TryAdd(SessionKeys.SelectedOrganizationId.GetDisplayName(), data[SessionKeys.SelectedOrganizationId.GetDisplayName()]);
                    string selectedOrganizationName = Encoding.UTF8.GetString(Convert.FromBase64String(data[SessionKeys.SelectedOrganizationName.GetDisplayName()]));
                    context.Items.TryAdd(SessionKeys.SelectedOrganizationName.GetDisplayName(), selectedOrganizationName);

                    var culture = new CultureInfo(data[SessionKeys.SelectedCultureName.ToString()]);
                    CultureInfo.CurrentCulture   = culture;
                    CultureInfo.CurrentUICulture = culture;
                }
            }

            //var dbContext = GeneralContext.ServiceProvider.CreateDBContext<TMSDBContext>();
            //GeneralContext.Container.RegisterInstance<IDbContext>(dbContext);
            //GeneralContext.Container.BuildUp<IDbContext>(dbContext);
            // Call the next delegate/middleware in the pipeline
            await _next(context);
        }
コード例 #9
0
        public static void ConfigureApiAuthentication(this IServiceCollection services, IAuthOptions authOptions)
        {
            AuthenticationBuilder authenticationBuilder;

            if (authOptions.AuthenticationType == "Bearer")
            {
                authenticationBuilder = services
                                        .AddAuthentication(x =>
                {
                    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                    //x.RequireAuthenticatedSignIn = false;
                })
                                        .AddJwtBearer(options =>
                {
                    IAuthOptions authOptions = GeneralContext.GetService <IAuthOptions>();
                    var key = Encoding.ASCII.GetBytes(authOptions.KEY);

                    options.Events = ConfigureJwtBearerEvents();

                    options.RequireHttpsMetadata      = false;
                    options.SaveToken                 = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey         = new SymmetricSecurityKey(key),
                        ValidateIssuer           = false,
                        ValidateAudience         = false,
                        RequireExpirationTime    = false,
                        ValidateLifetime         = true
                    };
                    //options.SecurityTokenValidators.Add(new ApiTokenValidator());
                });
            }
            else
            {
                authenticationBuilder = services.AddAuthentication(ApiAuthSchemes.DefaultAuthScheme);
            }

            authenticationBuilder.AddCookie(ApiAuthSchemes.DefaultAuthScheme, options =>
            {
                options.LoginPath = new Microsoft.AspNetCore.Http.PathString("/AdminApi/Login");
            });
        }
コード例 #10
0
        public async Task InvokeAsync(HttpContext httpContext, IAuthOptions authOptions)
        {
            if (authOptions.AuthenticationType == "Bearer")
            {
                var token = httpContext.GetRequestToken();
                if (!string.IsNullOrEmpty(token))
                {
                    AppUser loggedUser = Util.ReadToken <AppUser>(token, authOptions.KEY);
                    if (loggedUser != null && !Convert.ToBoolean(httpContext?.User?.Identity?.IsAuthenticated))
                    {
                        httpContext.Items.TryAdd("loggedUser", loggedUser);
                        await GeneralContext.HttpContext.SignInAsync(loggedUser);
                    }
                }
            }

            // Call the next delegate/middleware in the pipeline
            await _next(httpContext);
        }
コード例 #11
0
        public async Task <string> SendAsync(object data, string returnUrl)
        {
            var dataString = JsonConvert.SerializeObject(data);
            //var userByteArray = loggedUser.ToByteArrayUtf8();
            //var encryptData = Convert.ToBase64String(userByteArray);
            IAuthOptions authOptions   = GeneralContext.GetService <IAuthOptions>();
            string       encryptedData = Util.EncryptText(dataString, authOptions.KEY);

            var httpRequestMessage = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = _httpClient.BaseAddress,
                Content    = new StringContent(encryptedData)
            }; //GeneralContext.GetSessionData(_appConfig)

            httpRequestMessage.Headers.Add(HttpRequestXHeader.Data.GetDisplayName(), encryptedData);
            httpRequestMessage.Headers.Add(HttpRequestXHeader.ReturnUrl.GetDisplayName(), returnUrl);

            var response = await _httpClient.SendAsync(httpRequestMessage);

            return(response.StatusCode == HttpStatusCode.Redirect
                 ? response.Headers.Location.OriginalString
                 : null);
        }
コード例 #12
0
ファイル: Startup.cs プロジェクト: Hawkeye4040/dotnet-monitor
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IHostApplicationLifetime lifetime,
            IWebHostEnvironment env,
            ExperimentalToolLogger exprLogger,
            IAuthOptions options,
            AddressListenResults listenResults,
            ILogger <Startup> logger)
        {
            exprLogger.LogExperimentMessage();

            // These errors are populated before Startup.Configure is called because
            // the KestrelServer class is configured as a prerequisite of
            // GenericWebHostServer being instantiated. The GenericWebHostServer invokes
            // Startup.Configure as part of its StartAsync method. This method is the
            // first opportunity to log anything through ILogger (a dedicated HostedService
            // could be written for this, but there is no guarantee that service would run
            // after the GenericWebHostServer is instantiated but before it is started).
            foreach (AddressListenResult result in listenResults.Errors)
            {
                logger.UnableToListenToAddress(result.Url, result.Exception);
            }

            // If we end up not listening on any ports, Kestrel defaults to port 5000. Make sure we don't attempt this.
            // Startup.Configure is called before KestrelServer is started
            // by the GenericWebHostServer, so there is no duplication of logging errors
            // and Kestrel does not bind to default ports.
            if (!listenResults.AnyAddresses)
            {
                // This is logged by GenericWebHostServer.StartAsync
                throw new MonitoringException("Unable to bind any urls.");
            }

            lifetime.ApplicationStarted.Register(() => LogBoundAddresses(app.ServerFeatures, listenResults, logger));

            if (options.KeyAuthenticationMode == KeyAuthenticationMode.NoAuth)
            {
                logger.NoAuthentication();
            }
            else
            {
                //Auth is enabled and we are binding on http. Make sure we log a warning.

                string   hostingUrl = Configuration.GetValue <string>(WebHostDefaults.ServerUrlsKey);
                string[] urls       = ConfigurationHelper.SplitValue(hostingUrl);
                foreach (string url in urls)
                {
                    BindingAddress address = null;
                    try
                    {
                        address = BindingAddress.Parse(url);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    if (string.Equals(Uri.UriSchemeHttp, address.Scheme, StringComparison.OrdinalIgnoreCase))
                    {
                        logger.InsecureAuthenticationConfiguration();
                        break;
                    }
                }
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            CorsConfiguration corsConfiguration = new CorsConfiguration();

            Configuration.Bind(nameof(CorsConfiguration), corsConfiguration);
            if (!string.IsNullOrEmpty(corsConfiguration.AllowedOrigins))
            {
                app.UseCors(builder => builder.WithOrigins(corsConfiguration.GetOrigins()).AllowAnyHeader().AllowAnyMethod());
            }

            app.UseResponseCompression();

            //Note this must be after UseRouting but before UseEndpoints
            app.UseMiddleware <Throttling>();

            app.UseEndpoints(builder =>
            {
                builder.MapControllers();
            });
        }
コード例 #13
0
 public static string GetAuthority(this IAuthOptions options)
 => $"https://{options.Domain}";
コード例 #14
0
 internal static string RedirectUri(this IAuthOptions options)
 {
     return($"msal{options.ClientId}://auth");
 }
コード例 #15
0
 public AzureAuthenticationCredentialProvider(IOptions <ApplicationOptions> appOptions, IAuthOptions authOptions)
 {
     _appOptions  = appOptions;
     _authOptions = authOptions;
 }
コード例 #16
0
ファイル: LoginJWT.cs プロジェクト: Stripped/DeployT
 public LoginJWT(IAuthOptions authOptions, IUserRepository userRepository)
 {
     _authOptions    = authOptions;
     _userRepository = userRepository;
 }
コード例 #17
0
ファイル: TokenHelper.cs プロジェクト: catman0745/Blogger
 public TokenHelper(IAuthOptions options, ITimeHelper timeHelper)
 {
     _options    = options;
     _timeHelper = timeHelper;
 }
コード例 #18
0
 public AuthClient(IPublicClientApplication pca, UIParent uiParent, IAuthOptions options)
 {
     _pca      = pca;
     _uiParent = uiParent;
     _options  = options;
 }
コード例 #19
0
 public TokenRequirement(IAuthOptions authOptions)
 {
     AuthOptions = authOptions;
 }
コード例 #20
0
 internal static string GetPolicy(this IAuthOptions options)
 {
     return(string.IsNullOrEmpty(options.Policy) ? "B2C_1_SUSI" : options.Policy);
 }
コード例 #21
0
 public AuthService(IAuthOptions authOptions)
 {
     _authOptions = authOptions;
 }
コード例 #22
0
        public static void ConfigureApiAuthorization(this IServiceCollection services, IAuthOptions authOptions)
        {
            services.AddAuthorization(options =>
            {
                options.AddPolicy(PolicyTypes.ApiAuthPolicy, policy =>
                                  policy.Requirements.Add(new TokenRequirement(authOptions)));

                //options =>
                //{
                //    options.AddPolicy("Over18", policy =>
                //    {
                //        policy.AuthenticationSchemes.Add("CrpmAuthenticationScheme");
                //        policy.RequireAuthenticatedUser();
                //        //policy.Requirements.Add(new MinimumAgeRequirement());
                //    });
                //});
            });
            services.AddSingleton <IAuthorizationHandler, ApiAuthorizationHandler>();
        }
コード例 #23
0
 internal static string GetB2CAuthority(this IAuthOptions options)
 {
     return($"https://login.microsoftonline.com/tfp/{options.Tenant.GetTenantName()}/{options.GetPolicy()}");
 }
コード例 #24
0
 public UserDefinedConfiguration(IAuthOptions options)
 {
     _options = options;
 }
コード例 #25
0
 public AccountController(IAuthOptions authOptions, ILoginJWT loginJWT)
 {
     _authOptions = authOptions;
     _loginJWT    = loginJWT;
 }