Esempio n. 1
0
        /// <summary>
        /// Validate the issuer. The issuer is considered as valid if it
        /// has the same http scheme and authority as the trusted issuer uri
        /// from the configuration file or default uri, plus it has to have
        /// a tenant Id, and optionally v2.0 but nothing more..
        /// </summary>
        /// <param name="issuer">Issuer to validate (will be tenanted)</param>
        /// <param name="config">Authentication configuration</param>
        /// <returns>The <c>issuer</c> if it's valid</returns>
        private static string ValidateIssuer(string issuer, IAuthConfig config)
        {
            var uri          = new Uri(issuer);
            var authorityUri = new Uri(config?.TrustedIssuer ?? kDefaultIssuerUri);

            if (uri.Scheme != authorityUri.Scheme ||
                uri.Authority != authorityUri.Authority)
            {
                throw new SecurityTokenInvalidIssuerException(
                          "Issuer has wrong authority.");
            }
            var parts = uri.AbsolutePath.Split(new char[] { '/' },
                                               StringSplitOptions.RemoveEmptyEntries);

            if (parts.Length == 0)
            {
                throw new SecurityTokenInvalidIssuerException(
                          "Issuer is not tenanted.");
            }
            if (parts.Length >= 1 && !Guid.TryParse(parts[0], out var tenantId))
            {
                throw new SecurityTokenInvalidIssuerException(
                          "No valid tenant Id for the issuer.");
            }
            if (parts.Length > 1 && parts[2] != "v2.0")
            {
                throw new SecurityTokenInvalidIssuerException(
                          "Only accepted protocol versions are AAD v1.0 or V2.0");
            }
            return(issuer);
        }
Esempio n. 2
0
 public UsersController(IMapper mapper, IHttpContextAccessor httpContextAccessor, IAuthConfig authConfig, IAuthorService authorService)
 {
     _mapper = mapper;
     _httpContextAccessor = httpContextAccessor;
     _authConfig          = authConfig;
     _authorService       = authorService;
 }
Esempio n. 3
0
        /// <summary>
        /// Helper to add jwt bearer authentication
        /// </summary>
        /// <param name="services"></param>
        /// <param name="config"></param>
        /// <param name="inDevelopment"></param>
        public static void AddJwtBearerAuthentication(this IServiceCollection services,
                                                      IAuthConfig config, bool inDevelopment)
        {
            if (config.HttpsRedirectPort > 0)
            {
                services.AddHsts(options => {
                    options.Preload           = true;
                    options.IncludeSubDomains = true;
                    options.MaxAge            = TimeSpan.FromDays(60);
                });
                services.AddHttpsRedirection(options => {
                    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                    options.HttpsPort          = config.HttpsRedirectPort;
                });
            }

            // Allow access to context from within token providers and other client auth
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Add jwt bearer auth
            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => {
                options.Authority = config.GetAuthorityUrl() + "/v2.0";
                options.SaveToken = true;     // Save token to allow request on behalf

                options.TokenValidationParameters = new TokenValidationParameters {
                    ClockSkew        = config.AllowedClockSkew,
                    ValidateIssuer   = true,
                    IssuerValidator  = (iss, t, p) => ValidateIssuer(iss, config),
                    ValidateAudience = !string.IsNullOrEmpty(config.Audience),
                    ValidAudience    = config.Audience
                };
                options.Events = new JwtBearerEvents {
                    OnAuthenticationFailed = ctx => {
                        if (config.AuthRequired)
                        {
                            ctx.NoResult();
                            return(WriteErrorAsync(ctx.Response, inDevelopment ?
                                                   ctx.Exception : null));
                        }
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = ctx => {
                        if (ctx.SecurityToken is JwtSecurityToken accessToken)
                        {
                            if (ctx.Principal.Identity is ClaimsIdentity identity)
                            {
                                identity.AddClaim(new Claim("access_token",
                                                            accessToken.RawData));
                            }
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
        }
Esempio n. 4
0
 public UsersController(
     IMapper mapper,
     IHttpContextAccessor httpContextAccessor,
     IHubContext <UsersHub> userHubContext,
     IAuthConfig authConfig,
     IUserService userService)
 {
     _mapper = mapper;
     _httpContextAccessor = httpContextAccessor;
     _userHubContext      = userHubContext;
     _authConfig          = authConfig;
     _userService         = userService;
 }
 /// <summary>
 /// Add v1 policies to options
 /// </summary>
 /// <param name="config"></param>
 /// <param name="servicesConfig"></param>
 /// <param name="options"></param>
 public static void AddV1Policies(this AuthorizationOptions options,
                                  IAuthConfig config, IServicesConfig servicesConfig)
 {
     options.AddPolicy(Policies.CanRead, policy =>
                       policy.RequireAuthenticatedUser());
     options.AddPolicy(Policies.CanWrite, policy =>
                       policy.RequireAuthenticatedUser()
                       .Require(WriterRights));
     options.AddPolicy(Policies.CanSign, policy =>
                       policy.RequireAuthenticatedUser()
                       .Require(ApproverRights));
     options.AddPolicy(Policies.CanManage, policy =>
                       policy.RequireAuthenticatedUser()
                       .Require(AdminRights));
 }
 public ProjectsController(
     IMapper mapper,
     IHttpContextAccessor httpContextAccessor,
     IHubContext <ProjectsHub> projectHubContext,
     IAuthConfig authConfig,
     IProjectService projectService,
     IUserService userService)
 {
     _mapper = mapper;
     _httpContextAccessor = httpContextAccessor;
     _projectHubContext   = projectHubContext;
     _authConfig          = authConfig;
     _projectService      = projectService;
     _userService         = userService;
 }
        public InternalClient(IConfiguration configuration, IAuthConfig authConfig)
        {
            Config    = configuration ?? TrueDialogConfigSection.GetConfig();
            AccountId = authConfig.AccountId;

            if (AccountId == 0)
            {
                throw new ArgumentException("Account ID is missing.");
            }

            var strategy = GetRetryStrategy();

            RetryPolicy = new RetryPolicy <RestErrorDetectionStrategy>(strategy);

            RestClient = CreateClient(Config, authConfig);
        }
Esempio n. 8
0
        /// <summary>
        /// Url of the token issuing instance.  E.g. the JWT bearer
        /// authentication middleware will use this URI as base
        /// uri to retrieve the public key that can be used to
        /// validate the token's signature.
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public static string GetAuthorityUrl(this IAuthConfig config)
        {
            var instanceUrl = config?.InstanceUrl;

            if (string.IsNullOrEmpty(instanceUrl))
            {
                instanceUrl = "https://login.microsoftonline.com/";
            }
            var tenantId = config?.TenantId;

            if (string.IsNullOrEmpty(tenantId))
            {
                tenantId = "common";
            }
            return(instanceUrl.TrimEnd('/') + "/" + tenantId);
        }
        public void SaveAuthConfig(IAuthConfig c)
        {
            var configSection = (TGFCSpidermanSection)_config.GetSection(SectionName);

            if (configSection == null)
            {
                configSection = new TGFCSpidermanSection();
                configSection.AuthElement.UserName  = c.UserName;
                configSection.AuthElement.AuthToken = c.AuthToken;
                _config.Sections.Add(SectionName, configSection);
            }
            else
            {
                configSection.AuthElement.UserName  = c.UserName;
                configSection.AuthElement.AuthToken = c.AuthToken;
            }

            _config.Save(ConfigurationSaveMode.Modified);
            System.Configuration.ConfigurationManager.RefreshSection(SectionName);
        }
Esempio n. 10
0
        private IRestClient CreateClient(IConfiguration config, IAuthConfig authConfig)
        {
            Assembly     thisAssembly = Assembly.GetCallingAssembly();
            AssemblyName asmName      = thisAssembly.GetName();
            var          version      = asmName.Version.ToString();

            string user = authConfig.UserName;
            string pass = authConfig.Password;

            m_userAuthenticator = new HttpBasicAuthenticator(user, pass);

            string apiKey    = string.IsNullOrEmpty(authConfig.ApiKey) ? user : authConfig.ApiKey;
            string apiSecret = string.IsNullOrEmpty(authConfig.ApiSecret) ? pass : authConfig.ApiSecret;

            m_apiAuthenticator = new HttpBasicAuthenticator(apiKey, apiSecret);

            string userAgent = config.UserAgent;

            if (String.IsNullOrWhiteSpace(userAgent))
            {
                userAgent = String.Format("TrueDialog SDK.NET {0}", version);
            }

            var rval = new RestClient
            {
                Authenticator = m_apiAuthenticator,
                BaseUrl       = new Uri(config.BaseUrl),
                UserAgent     = userAgent,
                Timeout       = (int)config.Timeout.TotalMilliseconds
            };

            rval.ClearHandlers();
            rval.AddHandler("application/json", () => { return(new NewtonsoftSerializer()); });
            rval.AddHandler("text/json", () => { return(new NewtonsoftSerializer()); });

            rval.AddHandler("application/xml", () => { return(new XmlDeserializer()); });
            rval.AddHandler("text/xml", () => { return(new XmlDeserializer()); });

            return(rval);
        }
Esempio n. 11
0
 /// <summary>
 /// Create validator
 /// </summary>
 /// <param name="config"></param>
 /// <param name="logger"></param>
 public JwtTokenValidator(IAuthConfig config, ILogger logger)
 {
     _config       = config ?? throw new ArgumentNullException(nameof(config));
     _logger       = logger ?? throw new ArgumentNullException(nameof(logger));
     _tokenHandler = new JwtSecurityTokenHandler();
 }
 public AuthenticationService(ILoginRepo loginRepo, IAuthConfig authConfig)
 {
     _loginRepo  = loginRepo;
     _authConfig = authConfig;
 }