Example #1
0
        //POST : /api/ApplicationUser/Login
        public async Task <IActionResult> Login(UserLoginDto dto)
        {
            var user = await _userManager.FindByNameAsync(dto.UserName);

            if (user != null)
            {
                if (await _userManager.CheckPasswordAsync(user, dto.Password))
                {
                    var userTokenHandler = new UserTokenHandler(user, _userManager, _appSettings);
                    var token            = await userTokenHandler.CreateUserToken();

                    return(Ok(new { token }));
                }
                else
                {
                    string error = "Password is incorrect.";
                    _logger.LogWarning($"Login attempt by user: {dto.UserName} but {error}");
                    return(BadRequest(new { Message = error }));
                }
            }
            else
            {
                string error = "Username does not exist.";
                _logger.LogWarning($"Login attempt by user: {dto.UserName} but {error}");
                return(BadRequest(new { Message = error }));
            }
        }
        public string GetAdminToken(string userId)
        {
            var dic = new Dictionary <string, string>();

            dic.Add("LI", userId);
            dic.Add("IA", "IA");
            return(UserTokenHandler.GetUserToken(dic));
        }
Example #3
0
        public async Task AddUserTokenAsync(UserTokenHandler userToken)
        {
            if (!_siteSetting.JwtSettings.AllowMultipleLoginsFromTheSameUser)
            {
                await InvalidateUserTokensAsync(userToken.UserId);
            }
            await DeleteTokensWithSameRefreshTokenSourceAsync(userToken.RefreshTokenIdHashSource);

            await _repository.AddAsync(userToken, CancellationToken.None);
        }
 public static bool CheckIsAdmin(string userToken)
 {
     try
     {
         return(UserTokenHandler.IsAdmin(userToken));
     }
     catch (Exception ex)
     {
         throw new AuthException("用户身份验证失败,请检查是否已登录", ex);
     }
 }
 /// <summary>
 /// 验证用户身份及权限,并返回用户名称
 /// </summary>
 public static void ValidateAuthentication(string userToken, string needRight, string functionId, out string userId)
 {
     try
     {
         var rlt = UserTokenHandler.ValidateAuthentication(userToken, needRight, functionId, "LI");
         if (!rlt.ContainsKey("LI"))
         {
             throw new AuthException("UserToken不完整,缺少UserId信息");
         }
         userId = rlt["LI"];
     }
     catch (Exception ex)
     {
         throw new AuthException("用户身份验证失败,请检查是否已登录", ex);
     }
 }
Example #6
0
        public async Task AddUserTokenAsync(User user, string refreshTokenSerial, string accessToken, string refreshTokenSourceSerial)
        {
            var now = DateTimeOffset.UtcNow;

            var token = new UserTokenHandler
            {
                UserId = user.Id,
                // Refresh token handles should be treated as secrets and should be stored hashed
                RefreshTokenIdHash       = _securityService.GetSha256Hash(refreshTokenSerial),
                RefreshTokenIdHashSource = string.IsNullOrWhiteSpace(refreshTokenSourceSerial) ?
                                           null : _securityService.GetSha256Hash(refreshTokenSourceSerial),
                AccessTokenHash             = _securityService.GetSha256Hash(accessToken),
                RefreshTokenExpiresDateTime = now.AddMinutes(_siteSetting.JwtSettings.RefreshTokenExpirationMinutes),
                AccessTokenExpiresDateTime  = now.AddMinutes(_siteSetting.JwtSettings.ExpirationMinutes)
            };

            await AddUserTokenAsync(token);
        }
        public string GetUserToken(string userId, IList <AccessControlItem> acl)
        {
            var dic = new Dictionary <string, string>(acl.Count);

            foreach (var item in acl)
            {
                if (item.Status != EnableStatus.Enable)
                {
                    throw new AuthException("被禁止的权限控制项不能出现在此");
                }
                if (!dic.ContainsKey(item.FunctionId))
                {
                    dic.Add(item.FunctionId, item.Mode);
                }
                else
                {
                    dic[item.FunctionId] = MergeFunctionMode(dic[item.FunctionId], item.Mode);
                }
            }
            dic.Add("LI", userId);
            return(UserTokenHandler.GetUserToken(dic));
        }
 public MainClientExec(HttpRequestExecutor requestExecutor, HttpClientConnectionManager
                       connManager, ConnectionReuseStrategy reuseStrategy, ConnectionKeepAliveStrategy
                       keepAliveStrategy, AuthenticationStrategy targetAuthStrategy, AuthenticationStrategy
                       proxyAuthStrategy, UserTokenHandler userTokenHandler)
 {
     Args.NotNull(requestExecutor, "HTTP request executor");
     Args.NotNull(connManager, "Client connection manager");
     Args.NotNull(reuseStrategy, "Connection reuse strategy");
     Args.NotNull(keepAliveStrategy, "Connection keep alive strategy");
     Args.NotNull(targetAuthStrategy, "Target authentication strategy");
     Args.NotNull(proxyAuthStrategy, "Proxy authentication strategy");
     Args.NotNull(userTokenHandler, "User token handler");
     this.authenticator      = new HttpAuthenticator();
     this.proxyHttpProcessor = new ImmutableHttpProcessor(new RequestTargetHost(), new
                                                          RequestClientConnControl());
     this.routeDirector      = new BasicRouteDirector();
     this.requestExecutor    = requestExecutor;
     this.connManager        = connManager;
     this.reuseStrategy      = reuseStrategy;
     this.keepAliveStrategy  = keepAliveStrategy;
     this.targetAuthStrategy = targetAuthStrategy;
     this.proxyAuthStrategy  = proxyAuthStrategy;
     this.userTokenHandler   = userTokenHandler;
 }
Example #9
0
        public virtual CloseableHttpClient Build()
        {
            // Create main request executor
            HttpRequestExecutor requestExec = this.requestExec;

            if (requestExec == null)
            {
                requestExec = new HttpRequestExecutor();
            }
            HttpClientConnectionManager connManager = this.connManager;

            if (connManager == null)
            {
                LayeredConnectionSocketFactory sslSocketFactory = this.sslSocketFactory;
                if (sslSocketFactory == null)
                {
                    string[] supportedProtocols = systemProperties ? Split(Runtime.GetProperty("https.protocols"
                                                                                               )) : null;
                    string[] supportedCipherSuites = systemProperties ? Split(Runtime.GetProperty("https.cipherSuites"
                                                                                                  )) : null;
                    X509HostnameVerifier hostnameVerifier = this.hostnameVerifier;
                    if (hostnameVerifier == null)
                    {
                        hostnameVerifier = SSLConnectionSocketFactory.BrowserCompatibleHostnameVerifier;
                    }
                    if (sslcontext != null)
                    {
                        sslSocketFactory = new SSLConnectionSocketFactory(sslcontext, supportedProtocols,
                                                                          supportedCipherSuites, hostnameVerifier);
                    }
                    else
                    {
                        if (systemProperties)
                        {
                            sslSocketFactory = new SSLConnectionSocketFactory((SSLSocketFactory)SSLSocketFactory
                                                                              .GetDefault(), supportedProtocols, supportedCipherSuites, hostnameVerifier);
                        }
                        else
                        {
                            sslSocketFactory = new SSLConnectionSocketFactory(SSLContexts.CreateDefault(), hostnameVerifier
                                                                              );
                        }
                    }
                }
                PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager
                                                                    (RegistryBuilder.Create <ConnectionSocketFactory>().Register("http", PlainConnectionSocketFactory
                                                                                                                                 .GetSocketFactory()).Register("https", sslSocketFactory).Build());
                if (defaultSocketConfig != null)
                {
                    poolingmgr.SetDefaultSocketConfig(defaultSocketConfig);
                }
                if (defaultConnectionConfig != null)
                {
                    poolingmgr.SetDefaultConnectionConfig(defaultConnectionConfig);
                }
                if (systemProperties)
                {
                    string s = Runtime.GetProperty("http.keepAlive", "true");
                    if (Sharpen.Runtime.EqualsIgnoreCase("true", s))
                    {
                        s = Runtime.GetProperty("http.maxConnections", "5");
                        int max = System.Convert.ToInt32(s);
                        poolingmgr.SetDefaultMaxPerRoute(max);
                        poolingmgr.SetMaxTotal(2 * max);
                    }
                }
                if (maxConnTotal > 0)
                {
                    poolingmgr.SetMaxTotal(maxConnTotal);
                }
                if (maxConnPerRoute > 0)
                {
                    poolingmgr.SetDefaultMaxPerRoute(maxConnPerRoute);
                }
                connManager = poolingmgr;
            }
            ConnectionReuseStrategy reuseStrategy = this.reuseStrategy;

            if (reuseStrategy == null)
            {
                if (systemProperties)
                {
                    string s = Runtime.GetProperty("http.keepAlive", "true");
                    if (Sharpen.Runtime.EqualsIgnoreCase("true", s))
                    {
                        reuseStrategy = DefaultConnectionReuseStrategy.Instance;
                    }
                    else
                    {
                        reuseStrategy = NoConnectionReuseStrategy.Instance;
                    }
                }
                else
                {
                    reuseStrategy = DefaultConnectionReuseStrategy.Instance;
                }
            }
            ConnectionKeepAliveStrategy keepAliveStrategy = this.keepAliveStrategy;

            if (keepAliveStrategy == null)
            {
                keepAliveStrategy = DefaultConnectionKeepAliveStrategy.Instance;
            }
            AuthenticationStrategy targetAuthStrategy = this.targetAuthStrategy;

            if (targetAuthStrategy == null)
            {
                targetAuthStrategy = TargetAuthenticationStrategy.Instance;
            }
            AuthenticationStrategy proxyAuthStrategy = this.proxyAuthStrategy;

            if (proxyAuthStrategy == null)
            {
                proxyAuthStrategy = ProxyAuthenticationStrategy.Instance;
            }
            UserTokenHandler userTokenHandler = this.userTokenHandler;

            if (userTokenHandler == null)
            {
                if (!connectionStateDisabled)
                {
                    userTokenHandler = DefaultUserTokenHandler.Instance;
                }
                else
                {
                    userTokenHandler = NoopUserTokenHandler.Instance;
                }
            }
            ClientExecChain execChain = new MainClientExec(requestExec, connManager, reuseStrategy
                                                           , keepAliveStrategy, targetAuthStrategy, proxyAuthStrategy, userTokenHandler);

            execChain = DecorateMainExec(execChain);
            HttpProcessor httpprocessor = this.httpprocessor;

            if (httpprocessor == null)
            {
                string userAgent = this.userAgent;
                if (userAgent == null)
                {
                    if (systemProperties)
                    {
                        userAgent = Runtime.GetProperty("http.agent");
                    }
                    if (userAgent == null)
                    {
                        userAgent = DefaultUserAgent;
                    }
                }
                HttpProcessorBuilder b = HttpProcessorBuilder.Create();
                if (requestFirst != null)
                {
                    foreach (IHttpRequestInterceptor i in requestFirst)
                    {
                        b.AddFirst(i);
                    }
                }
                if (responseFirst != null)
                {
                    foreach (HttpResponseInterceptor i in responseFirst)
                    {
                        b.AddFirst(i);
                    }
                }
                b.AddAll(new RequestDefaultHeaders(defaultHeaders), new RequestContent(), new RequestTargetHost
                             (), new RequestClientConnControl(), new RequestUserAgent(userAgent), new RequestExpectContinue
                             ());
                if (!cookieManagementDisabled)
                {
                    b.Add(new RequestAddCookies());
                }
                if (!contentCompressionDisabled)
                {
                    b.Add(new RequestAcceptEncoding());
                }
                if (!authCachingDisabled)
                {
                    b.Add(new RequestAuthCache());
                }
                if (!cookieManagementDisabled)
                {
                    b.Add(new ResponseProcessCookies());
                }
                if (!contentCompressionDisabled)
                {
                    b.Add(new ResponseContentEncoding());
                }
                if (requestLast != null)
                {
                    foreach (IHttpRequestInterceptor i in requestLast)
                    {
                        b.AddLast(i);
                    }
                }
                if (responseLast != null)
                {
                    foreach (HttpResponseInterceptor i in responseLast)
                    {
                        b.AddLast(i);
                    }
                }
                httpprocessor = b.Build();
            }
            execChain = new ProtocolExec(execChain, httpprocessor);
            execChain = DecorateProtocolExec(execChain);
            // Add request retry executor, if not disabled
            if (!automaticRetriesDisabled)
            {
                HttpRequestRetryHandler retryHandler = this.retryHandler;
                if (retryHandler == null)
                {
                    retryHandler = DefaultHttpRequestRetryHandler.Instance;
                }
                execChain = new RetryExec(execChain, retryHandler);
            }
            HttpRoutePlanner routePlanner = this.routePlanner;

            if (routePlanner == null)
            {
                SchemePortResolver schemePortResolver = this.schemePortResolver;
                if (schemePortResolver == null)
                {
                    schemePortResolver = DefaultSchemePortResolver.Instance;
                }
                if (proxy != null)
                {
                    routePlanner = new DefaultProxyRoutePlanner(proxy, schemePortResolver);
                }
                else
                {
                    if (systemProperties)
                    {
                        routePlanner = new SystemDefaultRoutePlanner(schemePortResolver, ProxySelector.GetDefault
                                                                         ());
                    }
                    else
                    {
                        routePlanner = new DefaultRoutePlanner(schemePortResolver);
                    }
                }
            }
            // Add redirect executor, if not disabled
            if (!redirectHandlingDisabled)
            {
                RedirectStrategy redirectStrategy = this.redirectStrategy;
                if (redirectStrategy == null)
                {
                    redirectStrategy = DefaultRedirectStrategy.Instance;
                }
                execChain = new RedirectExec(execChain, routePlanner, redirectStrategy);
            }
            // Optionally, add service unavailable retry executor
            ServiceUnavailableRetryStrategy serviceUnavailStrategy = this.serviceUnavailStrategy;

            if (serviceUnavailStrategy != null)
            {
                execChain = new ServiceUnavailableRetryExec(execChain, serviceUnavailStrategy);
            }
            // Optionally, add connection back-off executor
            BackoffManager            backoffManager            = this.backoffManager;
            ConnectionBackoffStrategy connectionBackoffStrategy = this.connectionBackoffStrategy;

            if (backoffManager != null && connectionBackoffStrategy != null)
            {
                execChain = new BackoffStrategyExec(execChain, connectionBackoffStrategy, backoffManager
                                                    );
            }
            Lookup <AuthSchemeProvider> authSchemeRegistry = this.authSchemeRegistry;

            if (authSchemeRegistry == null)
            {
                authSchemeRegistry = RegistryBuilder.Create <AuthSchemeProvider>().Register(AuthSchemes
                                                                                            .Basic, new BasicSchemeFactory()).Register(AuthSchemes.Digest, new DigestSchemeFactory
                                                                                                                                           ()).Register(AuthSchemes.Ntlm, new NTLMSchemeFactory()).Register(AuthSchemes.Spnego
                                                                                                                                                                                                            , new SPNegoSchemeFactory()).Register(AuthSchemes.Kerberos, new KerberosSchemeFactory
                                                                                                                                                                                                                                                      ()).Build();
            }
            Lookup <CookieSpecProvider> cookieSpecRegistry = this.cookieSpecRegistry;

            if (cookieSpecRegistry == null)
            {
                cookieSpecRegistry = RegistryBuilder.Create <CookieSpecProvider>().Register(CookieSpecs
                                                                                            .BestMatch, new BestMatchSpecFactory()).Register(CookieSpecs.Standard, new RFC2965SpecFactory
                                                                                                                                                 ()).Register(CookieSpecs.BrowserCompatibility, new BrowserCompatSpecFactory()).Register
                                         (CookieSpecs.Netscape, new NetscapeDraftSpecFactory()).Register(CookieSpecs.IgnoreCookies
                                                                                                         , new IgnoreSpecFactory()).Register("rfc2109", new RFC2109SpecFactory()).Register
                                         ("rfc2965", new RFC2965SpecFactory()).Build();
            }
            CookieStore defaultCookieStore = this.cookieStore;

            if (defaultCookieStore == null)
            {
                defaultCookieStore = new BasicCookieStore();
            }
            CredentialsProvider defaultCredentialsProvider = this.credentialsProvider;

            if (defaultCredentialsProvider == null)
            {
                if (systemProperties)
                {
                    defaultCredentialsProvider = new SystemDefaultCredentialsProvider();
                }
                else
                {
                    defaultCredentialsProvider = new BasicCredentialsProvider();
                }
            }
            return(new InternalHttpClient(execChain, connManager, routePlanner, cookieSpecRegistry
                                          , authSchemeRegistry, defaultCookieStore, defaultCredentialsProvider, defaultRequestConfig
                                          != null ? defaultRequestConfig : RequestConfig.Default, closeables != null ? new
                                          AList <IDisposable>(closeables) : null));
        }
Example #10
0
 /// <summary>
 /// Assigns
 /// <see cref="Apache.Http.Client.UserTokenHandler">Apache.Http.Client.UserTokenHandler
 ///     </see>
 /// instance.
 /// <p/>
 /// Please note this value can be overridden by the
 /// <see cref="DisableConnectionState()">DisableConnectionState()</see>
 /// method.
 /// </summary>
 public Apache.Http.Impl.Client.HttpClientBuilder SetUserTokenHandler(UserTokenHandler
                                                                      userTokenHandler)
 {
     this.userTokenHandler = userTokenHandler;
     return(this);
 }