Пример #1
0
        public async Task <IQueryable <WapSubscription> > subscriptions(string userId)
        {
            //supress certificate error.needs to removed when trusted certs installed in the environment
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); });

            AdminManagementClient adminClient;
            var token = TokenIssuer.GetWindowsAuthToken(windowsAuthSiteEndpoint, null, null, null, false);

            adminClient = new AdminManagementClient(new Uri(adminserviceEndpoint), token);
            Query query = new Query();

            var result = await adminClient.ListUserSubscriptionsAsync(userId, query);

            var subscriptionlist = result.items.Select(x => new WapSubscription
            {
                AdminEmailId      = x.AccountAdminLiveEmailId,
                CoAdminNames      = x.CoAdminNames,
                OfferFriendlyName = x.OfferFriendlyName,
                PlanId            = x.PlanId,
                SubscriptionID    = x.SubscriptionID,
                SubscriptionName  = x.SubscriptionName
            }).AsQueryable();

            return(subscriptionlist);
        }
 /// <summary>
 /// Factory method for creating SWT tokens.
 /// </summary>
 /// <param name="issuer">The entity issuing the token.</param>
 /// <param name="audience">The entity receiving the token.</param>
 /// <param name="expiresOnUtc">The expiry time for the token in UTC.</param>
 /// <param name="signingKey">The token signing key.</param>
 /// <returns>
 /// An instance of SimpleWebToken class.
 /// </returns>
 public static SimpleWebToken CreateToken(
     TokenIssuer issuer,
     TokenAudience audience,
     DateTime expiresOnUtc,
     byte[] signingKey)
 {
     return(CreateToken(issuer, audience, expiresOnUtc, null, signingKey));
 }
Пример #3
0
        public override async Task Service(HttpContext context)
        {
            // get all needed variables
            string clientId     = context.Request.Form["clientId"];
            string clientSecret = context.Request.Form["clientSecret"];
            string token        = context.Request.Form["token"];
            string scope        = context.Request.Form["scope"];

            // optionally the call can include a service name which we will assert in the claims
            string serviceName = context.Request.Form["serviceName"];

            // get an access token and verify it
            Tokens tokens = null;

            if (!string.IsNullOrEmpty(token))
            {
                tokens = await GetAccessTokenFromClientCertificate(clientId, token, scope + "/.default");
            }
            else if (!string.IsNullOrEmpty(clientSecret))
            {
                tokens = await GetAccessTokenFromClientSecret(clientId, clientSecret, scope + "/.default");
            }
            else
            {
                throw new Exception("clientSecret or token must be supplied");
            }
            var accessToken = await VerifyTokenFromAAD(tokens.access_token, scope);

            // populate the claims from the id_token
            List <Claim> claims = new List <Claim>();
            var          oid    = accessToken.Payload.Claims.FirstOrDefault(c => c.Type == "oid");

            if (oid != null)
            {
                claims.Add(new Claim("oid", oid.Value));
            }

            // add the service details
            if (!string.IsNullOrEmpty(serviceName))
            {
                claims.Add(new Claim("name", serviceName));
            }
            claims.Add(new Claim("role", CasConfig.RoleForService));

            // attempt to propogate roles
            var roles = accessToken.Payload.Claims.Where(c => c.Type == "roles");

            foreach (var role in roles)
            {
                claims.Add(new Claim("role", role.Value));
            }

            // return the newly issued token
            string jwt = await TokenIssuer.IssueToken(claims);

            await context.Response.WriteAsync(jwt);
        }
        /// <summary>
        /// Checks whether the token signature is valid using the specified token issuer's keys.
        /// </summary>
        /// <param name="token">the token whose signature should be validated.</param>
        /// <param name="tokenIssuer">The token issuer who keys are to be used for validation.</param>
        /// <returns>
        /// True if the signature could be validated with the specified issuer's keys.
        /// </returns>
        private bool IsSignatureValidForIssuer(SimpleWebToken token, TokenIssuer tokenIssuer)
        {
            if (!this.tokenSigningKeysForIssuer.ContainsKey(tokenIssuer))
            {
                return(false);
            }

            var keys = this.tokenSigningKeysForIssuer[tokenIssuer];

            return(this.ValidateTokenSignature(token, keys.Item1, keys.Item2));
        }
Пример #5
0
        public HttpResponseMessage Login(string username, string password)
        {
            var ipaddress = HttpContext.Current.Request.UserHostAddress;

            if (CheckCredentails(username, password))
            {
                TokenIssuer token     = new TokenIssuer();
                string      jwt_token = token.GenerateJWT(username, ipaddress);
                Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", jwt_token);
                return(Request.CreateResponse(HttpStatusCode.OK, jwt_token));
            }
            return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("Invalid Credentails")));
        }
        /// <summary>
        /// Gets the role claims for the current principal.
        /// </summary>
        /// <param name="issuer"></param>
        /// <param name="audience"></param>
        private IEnumerable <Claim> GetRoleClaims(TokenIssuer issuer, TokenAudience audience)
        {
            IDictionary <TokenIssuer, IList <string> > issuerToRolesMapping;

            if (this.audienceIssuerRolesMapping.TryGetValue(audience, out issuerToRolesMapping))
            {
                IList <string> roles;
                if (issuerToRolesMapping.TryGetValue(issuer, out roles))
                {
                    IList <Claim> roleClaims = roles.Select(role => new Claim(HolMonClaimTypes.Role, role)).ToList();
                    return(roleClaims);
                }
            }

            return(new[] { new Claim(HolMonClaimTypes.Role, HolMonRoles.AnonymousAccessRole) });
        }
Пример #7
0
        public void GivenUsername_TokenIssuerCreatesToken_WhenIssueTokenIsCalled()
        {
            //Arrange
            var username = "******";
            var sut      = new TokenIssuer();

            //Act
            var token         = sut.IssueToken(username);
            var reader        = new JwtSecurityTokenHandler();
            var securitytoken = reader.ReadJwtToken(token);

            //Assert
            Assert.AreEqual(securitytoken.Claims.Where(c => c.Type == "aud").FirstOrDefault().Value, TokenIssuer.audience);
            Assert.AreEqual(securitytoken.Claims.Where(c => c.Type == "iss").FirstOrDefault().Value, TokenIssuer.issuer);
            Assert.AreEqual(securitytoken.Claims.Where(c => c.Type == "unique_name").FirstOrDefault().Value, username);
        }
Пример #8
0
        protected async Task WriteTokenCookies(HttpContext context, List <Claim> claims)
        {
            var domain = CasConfig.BaseDomain(context.Request);

            // write the XSRF-TOKEN cookie (if it will be verified)
            if (CasConfig.VerifyXsrfInHeader || CasConfig.VerifyXsrfInCookie)
            {
                string xsrf   = this.GenerateSafeRandomString(16);
                string signed = xsrf;
                if (!CasConfig.RequireHttpOnlyOnUserCookie)
                {
                    // if the source claim is going to be in a cookie that is readable by JavaScript the XSRF must be signed
                    signed = await TokenIssuer.IssueXsrfToken(xsrf);
                }
                context.Response.Cookies.Append("XSRF-TOKEN", signed, new CookieOptions()
                {
                    HttpOnly = CasConfig.RequireHttpOnlyOnXsrfCookie,
                    Secure   = CasConfig.RequireSecureForCookies,
                    Domain   = domain,
                    SameSite = CasConfig.SameSite,
                    Path     = "/"
                });
                Logger.LogInformation($"wrote XSRF-TOKEN cookie on domain \"{domain}\".");
                claims.Add(new Claim("xsrf", xsrf));
            }

            // write the user cookie
            string jwt = await TokenIssuer.IssueToken(claims);

            Console.WriteLine("jwt....................................jwt");
            Console.WriteLine(jwt);
            Console.WriteLine("jwt....................................jwt");
            var userCookie = CasConfig.UserCookieName;

            context.Response.Cookies.Append(userCookie, jwt, new CookieOptions()
            {
                HttpOnly = CasConfig.RequireHttpOnlyOnUserCookie,
                Secure   = CasConfig.RequireSecureForCookies,
                Domain   = domain,
                SameSite = CasConfig.SameSite,
                Path     = "/"
            });
            Logger.LogInformation($"wrote session cookie as \"{userCookie}\" on domain \"{domain}\".");

            // revoke the authflow cookie
            context.Response.Cookies.Delete("authflow");
        }
Пример #9
0
        //*********************************************************************
        ///
        /// <summary>
        /// This method is used to retrieve WAPadmin based on subscriptionId
        /// From WAPUI it is possible to pass WAPAdmin but from external UIs(who consumes this API) its not possible,so added this method
        /// </summary>
        /// <param name="vMId"></param>
        ///
        //*********************************************************************


        private async Task <string> GetWapAdmin(string wapSubscriptionId)
        {
            //*** TODO * Markw * Getting accessdenied on this call
            return(wapSubscriptionId);

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); });

            AdminManagementClient adminClient;
            var token = TokenIssuer.GetWindowsAuthToken(windowsAuthSiteEndpoint, null, null, null, false);

            adminClient = new AdminManagementClient(new Uri(adminserviceEndpoint), token);
            Query query = new Query();

            var result = await adminClient.GetSubscriptionAsync(wapSubscriptionId);

            return(result.AccountAdminLiveEmailId);
        }
        private async Task <string> __getJwtTokenForUser(ApplicationUser user)
        {
            using var scope = _provider.CreateScope();
            _logger.LogDebug($"Finding user");
            var userManager = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();
            var jwtFactory  = scope.ServiceProvider.GetRequiredService <IJwtFactory>();
            var roles       = await userManager.GetRolesAsync(user);

            var jwt = await TokenIssuer.GenerateRawJwt(
                jwtFactory.GenerateClaimsIdentity(user.UserName, user.Id),
                jwtFactory,
                user.UserName,
                roles.ToArray <string>(),
                _jwtOptions,
                new JsonSerializerSettings { Formatting = Formatting.Indented });

            return(jwt);
        }
Пример #11
0
        public override async Task <string> Reissue(string token)
        {
            // make sure the token is eligible
            var jwt = await TokenIssuer.IsTokenExpiredButEligibleForRenewal(token);

            // strip inappropriate claims
            var filter = new string[] { "iss", "aud", "exp" };
            var claims = jwt.Claims.Where(c => !filter.Contains(c.Type)).ToList();

            // make sure the user is eligible
            var oid = claims.FirstOrDefault(claim => claim.Type == "oid");

            if (oid.Value == null)
            {
                throw new CasHttpException(403, "oid is not specified in the token");
            }
            if (CasConfig.RequireUserEnabledOnReissue)
            {
                bool enabled = await IsUserEnabled((string)oid.Value);

                if (!enabled)
                {
                    throw new CasHttpException(403, "user is not enabled");
                }
            }

            // strip any existing -role claims
            claims.RemoveAll(c => c.Type.EndsWith("-role"));

            // populate all application roles from the graph
            var assignments = await GetRoleAssignments(oid.Value);

            foreach (var assignment in assignments)
            {
                foreach (var role in assignment.Roles)
                {
                    claims.Add(new Claim(assignment.AppId + "-role", role));
                }
            }

            // reissue the token
            return(await TokenIssuer.IssueToken(claims));
        }
Пример #12
0
        public async Task <ActionResult> CheckCredentialsAsync([FromBody] UserModel user)
        {
            if (user == null || user.UserName == null || user.Password == null)
            {
                return(BadRequest("Empty User"));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid model object"));
            }

            var _user = await _repository.User.GetUserByNameAsync(user.UserName);


            if (_user == null)
            {
                return(Unauthorized("User not found"));
            }

            using (var deriveBytes = new Rfc2898DeriveBytes(user.Password, _user.Salt))
            {
                byte[] newKey = deriveBytes.GetBytes(32);

                if (!newKey.SequenceEqual(_user.PasswordSalted))
                {
                    return(Unauthorized("Invalid credentials!"));
                }
            }

            var SecurityToken = new TokenIssuer(_configuration).SecurityToken(_user);

            return(Ok((new
            {
                token = new JwtSecurityTokenHandler().WriteToken(SecurityToken),
                userid = _user.Id.ToString(),
                username = _user.UserName,
                expiration = SecurityToken.ValidTo
            })));
        }
Пример #13
0
        public override async Task <Guid> ExecuteAsync(CreateNewTokenCommand command)
        {
            Logger.InitiateCreateNewToken(command.PartnerId, command.TokenType);

            TokenIssuer tokenIssuer = await UnitOfWork.GetByIdOrThrowAsync <TokenIssuer>(command.PartnerId);

            Token tokenPrototype = tokenIssuer.PrototypeTokens.SingleOrDefault(p => p.TokenType == command.TokenType.ToLowerInvariant());

            if (tokenPrototype == null)
            {
                throw new EntityNotFoundException(typeof(Token), nameof(ExecuteAsync), "Issuer: " + tokenIssuer.Id + "TokenType: " + command.TokenType);
            }

            Token newToken = tokenPrototype.CreateFromPrototype();

            newToken.PartnerId = tokenIssuer.Id;
            await UnitOfWork.InsertAsync(newToken);

            Logger.CreateNewTokenSuccessful(command.PartnerId, command.TokenType, newToken.Id);

            return(newToken.Id);
        }
Пример #14
0
        private async Task <(string, JwtRefreshTokenModel)> _getTokenAndRefresh(ClaimsIdentity identity, string userName,
                                                                                string[] roles, ApplicationUser user)
        {
            var jwt = await TokenIssuer.GenerateJwt(
                identity,
                _jwtFactory,
                userName,
                roles,
                _jwtOptions,
                new JsonSerializerSettings { Formatting = Formatting.Indented }
                );

            var refresh = TokenIssuer.GenerateRefreshToken(128);

            user.AddRefreshToken(
                refresh,
                _contextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            await _unitOfWork.CompleteAsync();

            return(jwt.Token, new JwtRefreshTokenModel(refresh, jwt));
        }
        public ActionResult <TokenIssuer> GetToken([FromBody] LogInViewModel model)
        {
            Console.WriteLine($"LogIn\n\temail: {model.Email}\n\tpass:{model.Password}");
            UInt64 exp   = 1735689600;
            var    aud   = "https://lacmus.io";
            var    iss   = "https://lacmus";
            var    sub   = "1234567890qwertyuio";
            var    jti   = "mnb23vcsrt756yuiomnbvcx98ertyuiop";
            var    roles = new List <string>(new [] { "user", "admin" });

            var tokenIssuer = new TokenIssuer();

            tokenIssuer.AccessToken       = new AccessToken();
            tokenIssuer.Exp               = exp;
            tokenIssuer.Id                = sub;
            tokenIssuer.AccessToken.Aud   = aud;
            tokenIssuer.AccessToken.Iss   = iss;
            tokenIssuer.AccessToken.Sub   = sub;
            tokenIssuer.AccessToken.Jti   = jti;
            tokenIssuer.AccessToken.Roles = roles;
            tokenIssuer.AccessToken.Exp   = exp;
            return(tokenIssuer);
        }
Пример #16
0
        public async Task <IActionResult> AuthorizeDevice(string deviceSerial,
                                                          bool isDesktop, int counterNo)
        {
            //const string tokenIssuerUri =
            //    "http://localhost:62710/";

            //const string tokenIssuerUri =
            //    "http://192.168.2.6/queue/";

            const string tokenIssuerUri =
                "http://192.168.1.110/queue/";

            var tokenIssuer = new TokenIssuer();

            var token = tokenIssuer.GenerateToken(
                deviceSerial, tokenIssuerUri);

            // Create a new Device if the serial is unique
            await _devService.CreateDevice(
                deviceSerial, isDesktop, counterNo);

            return(Ok(token));
        }
        public ActionResult <TokenIssuer> RefreshToken([FromBody] RefreshToken model)
        {
            string        sub;
            string        jti;
            List <string> roles;

            try
            {
                var token = Jose.JWT.Decode <AccessToken>(model.Token, Convert.FromBase64String("a2V5"));
                sub   = token.Sub;
                jti   = token.Jti;
                roles = token.Roles;
                Console.WriteLine("Token is valid!");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Invalid token: {e}");
                return(Unauthorized());
            }

            UInt64 exp = 1735689600;
            var    aud = "https://lacmus.io";
            var    iss = "https://lacmus";

            var tokenIssuer = new TokenIssuer();

            tokenIssuer.AccessToken       = new AccessToken();
            tokenIssuer.Exp               = exp;
            tokenIssuer.Id                = sub;
            tokenIssuer.AccessToken.Aud   = aud;
            tokenIssuer.AccessToken.Iss   = iss;
            tokenIssuer.AccessToken.Sub   = sub;
            tokenIssuer.AccessToken.Jti   = jti;
            tokenIssuer.AccessToken.Roles = roles;
            tokenIssuer.AccessToken.Exp   = exp;
            return(tokenIssuer);
        }
        /// <summary>
        /// Factory method for creating SWT tokens. Use this overload when there is a requirement
        /// to encode additional claims into the token.
        /// </summary>
        /// <param name="issuer">The entity issuing the token.</param>
        /// <param name="audience">The entity receiving the token.</param>
        /// <param name="expiresOnUtc">The expiry time for the token in UTC.</param>
        /// <param name="additionalClaims">
        /// Any additional claims to be included as part of the token.
        /// </param>
        /// <param name="signingKey">The token signing key.</param>
        /// <returns>
        /// An instance of SimpleWebToken class.
        /// </returns>
        public static SimpleWebToken CreateToken(
            TokenIssuer issuer,
            TokenAudience audience,
            DateTime expiresOnUtc,
            IEnumerable <Claim> additionalClaims,
            byte[] signingKey)
        {
            if (issuer == TokenIssuer.Unknown)
            {
                throw new ArgumentException(
                          "{0} is not not allowed as token issuer.".FormatInvariant(issuer.ToString()));
            }

            if (audience == TokenAudience.Unknown)
            {
                throw new ArgumentException(
                          "{0} is not allowed as token audience.".FormatInvariant(audience.ToString()));
            }

            if (signingKey == null || signingKey.Length == 0)
            {
                throw new ArgumentException("The signing key is not valid.");
            }

            var claims = new List <Claim>();

            if (additionalClaims != null)
            {
                claims.AddRange(additionalClaims);
            }

            var token = SimpleWebToken.Create(issuer.ToString(), audience.ToString(), expiresOnUtc, claims);

            token.SignToken(signingKey);
            return(token);
        }
Пример #19
0
        public Tuple <ClsReturnValues, string, List <ClsUserDisplay> > authenticateUser(string UserName, string Password, string DeviceType, string DeviceName, string Browser)
        {
            string encryptedPassword     = Security.Encrypt(Password);
            string token                 = "";
            List <ClsUserDisplay> ud     = new List <ClsUserDisplay>();
            ClsReturnValues       result = new ClsReturnValues();
            ClsUsers userGroup           = new ClsUsers();

            using (tdoEntities db = new tdoEntities())
            {
                result    = db.uspUserAuthentication(UserName, encryptedPassword, DeviceType, DeviceName, Browser).FirstOrDefault();
                userGroup = db.uspGetUsers().Where(p => p.userID == result.ID).FirstOrDefault();

                if (result.IsSuccess == true)
                {
                    ud = db.uspGetUserDisplay(result.ID).ToList <ClsUserDisplay>();
                    // Token issuer
                    TokenIssuer issuer = new TokenIssuer();
                    // A client of the relying party app gets the token
                    token = issuer.GetToken(result, ud.First().userGroupID);
                }
            }
            return(new Tuple <ClsReturnValues, string, List <ClsUserDisplay> >(result, token, ud));
        }
        private async Task <JwtRefreshTokenModel> _processUserDetails(FacebookUserData userInfo)
        {
            // 4. ready to create the local user account (if necessary) and jwt
            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user is null)
            {
                var appUser = new ApplicationUser {
                    FirstName  = userInfo.FirstName,
                    LastName   = userInfo.LastName,
                    FacebookId = userInfo.Id,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    PictureUrl = userInfo.Picture.Data.Url
                };
                var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                if (!result.Succeeded)
                {
                    throw new InvalidOperationException(
                              ModelState.ToString()
                              );
                }
            }
            else
            {
                user.PictureUrl = userInfo.Picture.Data.Url;
                var result = await _userManager.UpdateAsync(user);

                if (!result.Succeeded)
                {
                    throw new InvalidOperationException(
                              ModelState.ToString()
                              );
                }
            }

            // generate the jwt for the local user...
            var localUser = await _userManager.FindByNameAsync(userInfo.Email);

            if (localUser is null)
            {
                throw new InvalidOperationException(
                          ModelState.ToString()
                          );
            }
            var roles = await _userManager.GetRolesAsync(localUser);

            var jwt = await TokenIssuer.GenerateJwt(
                _jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id),
                _jwtFactory,
                localUser.UserName,
                roles.ToArray <string>(),
                _jwtOptions,
                new JsonSerializerSettings { Formatting = Formatting.Indented });

            var refresh = TokenIssuer.GenerateRefreshToken(128);

            user.AddRefreshToken(
                refresh,
                _contextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            await _unitOfWork.CompleteAsync();

            return(new JwtRefreshTokenModel(refresh, jwt));
        }
Пример #21
0
        //private async Task<AuthenticationHeaderValue> GetAuthenticationHeaderValue(Uri baseUri, System.Threading.CancellationToken cancellationToken)
        //{

        //    SignInResponseMessage rm = await GetSignInResponseMessage(baseUri, cancellationToken);

        //    string xml = FederatedAuthentication.WSFederationAuthenticationModule.GetXmlTokenFromMessage(rm);

        //    var toEncode = Encoding.UTF8.GetBytes(xml);
        //    var encoded = Convert.ToBase64String(toEncode);

        //    return new AuthenticationHeaderValue("SAML", encoded);
        //}

        //private static string GetIdentityToken()
        //{
        //    var factory = new WSTrustChannelFactory(
        //        new WindowsWSTrustBinding(SecurityMode.Transport),new EndpointAddress()
        //        _idpEndpoint);
        //    factory.TrustVersion = TrustVersion.WSTrust13;

        //    var rst = new RequestSecurityToken
        //    {
        //        RequestType = RequestTypes.Issue,
        //        KeyType = KeyTypes.Bearer,
        //        AppliesTo = new EndpointAddress(Constants.Realm)
        //    };

        //    var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
        //    return token.TokenXml.OuterXml;
        //}

        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            TokenIssuer ti    = new TokenIssuer();
            var         token = ti.Issue("cs", "https://training01.inner.relational.gr:444/", "testUser", "test Id");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
            return(await base.SendAsync(request, cancellationToken));

            /*
             *
             * SignInRequestMessage signInRequestMessage = GetSignInRequestMessage();
             *
             * using (var handler = new HttpClientHandler { Credentials = credentials })
             * {
             * using (var client = new HttpClient(handler))
             * {
             *
             *    var response = await client.PostAsync(signInRequestMessage.RequestUrl, new StringContent("", Encoding.UTF8), cancellationToken);
             *
             *    if (response.IsSuccessStatusCode)
             *    {
             *        NameValueCollection data = await response.Content.ReadAsFormDataAsync();
             *
             *        SignInResponseMessage signInResponseMessage = (SignInResponseMessage) WSFederationMessage.CreateFromNameValueCollection(request.RequestUri, data);
             *
             *        var xml = FederatedAuthentication.WSFederationAuthenticationModule.GetXmlTokenFromMessage(signInResponseMessage);
             *        //XmlDocument doc = new XmlDocument();
             *        //doc.LoadXml(xml);
             *        //var token = Encoding.UTF8.GetString(Convert.FromBase64String(doc.InnerText));
             *        //var token = Encoding.UTF8.GetString(Convert.FromBase64String(xml));
             *
             *        var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(xml));
             *
             *        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
             *
             *
             *    }
             *    else
             *    {
             *        if (response.StatusCode == HttpStatusCode.Unauthorized)
             *            return response;
             *
             *        throw new Exception(await response.Content.ReadAsStringAsync());
             *    }
             * }
             *
             * }
             *
             *
             * var resp = await base.SendAsync(request, cancellationToken);
             *
             *
             * return resp;
             *
             */

            //SecurityToken securityToken = FederatedAuthentication.WSFederationAuthenticationModule.GetSecurityToken(signInResponseMessage);



            //string xml = securityToken.ToTokenXmlString();
            ////string xml = FederatedAuthentication.WSFederationAuthenticationModule.GetXmlTokenFromMessage(signInResponseMessage);
            //var toEncode = Encoding.UTF8.GetBytes(xml);

            //var encoded = Convert.ToBase64String(toEncode);

            //SessionSecurityToken sst =  FederatedAuthentication.SessionAuthenticationModule.CreateSessionSecurityToken( GetPrincipal(userName,password),"",DateTime.UtcNow,DateTime.UtcNow.AddDays(1),true);
            //FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sst);
            //var cs = System.Web.HttpContext.Current.Request.Cookies.Get(1);

            //cookies.Add(request.RequestUri, new Cookie(cs.Name, cs.Value, cs.Path, cs.Domain) { Secure= cs.Secure, HttpOnly = cs.HttpOnly, Expires = cs.Expires });

            //NameValueCollection nvc = WSFederationMessage.ParseQueryString(new Uri(signInResponseMessage.WriteQueryString()));


            //    using (var client = new HttpClient())
            //    {
            //        var authResp = await client.PostAsync(request.RequestUri, new FormUrlEncodedContent(nvc.AllKeys.Select(f => new KeyValuePair<string, string>(f, nvc[f]))));
            //        IEnumerable<Cookie> responseCookies = cookies.GetCookies(request.RequestUri).Cast<Cookie>();
            //    }



            //request.RequestUri = new Uri( signInResponseMessage.WriteQueryString());

            //NameValueCollection nvc = WSFederationMessage.ParseQueryString(new Uri(signInResponseMessage.WriteQueryString()));

            //foreach (var k in nvc.AllKeys) {
            //    request.Headers.Add(k, Convert.ToBase64String(Encoding.UTF8.GetBytes(nvc[k])));
            //}

            //var xml = FederatedAuthentication.WSFederationAuthenticationModule.GetXmlTokenFromMessage(signInResponseMessage);

            //var toEncode = Encoding.UTF8.GetBytes(xml);

            //var encoded = Convert.ToBase64String(toEncode);
            //request.Headers.Authorization = new AuthenticationHeaderValue("SAML", encoded);

            //XmlDocument doc = new XmlDocument();
            //doc.LoadXml(xml);


            //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", doc.InnerText);
            //request.RequestUri = new Uri(signInResponseMessage.WriteQueryString());



            //SecurityToken securityToken = FederatedAuthentication.WSFederationAuthenticationModule.GetSecurityToken(signInResponseMessage);
            //string xml = securityToken.ToTokenXmlString();
            ////string xml = FederatedAuthentication.WSFederationAuthenticationModule.GetXmlTokenFromMessage(signInResponseMessage);
            //var toEncode = Encoding.UTF8.GetBytes(xml);

            //var encoded = Convert.ToBase64String(toEncode);
            //request.Headers.Authorization = new AuthenticationHeaderValue("SAML", encoded);
            //SessionSecurityToken sessionSecurityToken = FederatedAuthentication.SessionAuthenticationModule.CreateSessionSecurityToken(GetPrincipal(userName,password),"",DateTime.UtcNow,DateTime.UtcNow.AddDays(1),false);
            //FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionSecurityToken);


            //request.RequestUri = new Uri( signInResponseMessage.WriteQueryString());

            //using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
            //using (var client = new HttpClient(handler))
            //{
            //    string xml = FederatedAuthentication.WSFederationAuthenticationModule.GetXmlTokenFromMessage(signInResponseMessage);

            //    var toEncode = Encoding.UTF8.GetBytes(xml);
            //    var encoded = Convert.ToBase64String(toEncode);


            //    cookieContainer.Add(request.RequestUri, new Cookie("CookieName", encoded));

            //    return await client.SendAsync(request, cancellationToken);
            //}

            //request.Headers.Authorization =  await  GetAuthenticationHeaderValue(request.RequestUri, cancellationToken);
            //FederatedAuthentication.WSFederationAuthenticationModule.GetSecurityToken()



            //SecurityToken securityToken = FederatedAuthentication.WSFederationAuthenticationModule.GetSecurityToken(signInResponseMessage);
            //ClaimsPrincipal principal = GetPrincipal(userName, password);
            //SessionSecurityToken st = FederatedAuthentication.SessionAuthenticationModule.CreateSessionSecurityToken(principal, "", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), false);
            //FederatedAuthentication.SessionAuthenticationModule.AuthenticateSessionSecurityToken(st,false);
            //FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(st);
            //FederatedAuthentication.WSFederationAuthenticationModule.



            //

            //var c = request.Headers.GetCookies(cookieName).FirstOrDefault();

            //var c = new CookieHeaderValue(cookieName, actualToken);
            //c.Expires = DateTime.Now.AddDays(1);
            //c.Domain = request.RequestUri.Host;
            //c.Path = "/";
            //c.Secure = true;
            //c.HttpOnly = true;

            //request.Headers.AddCookies();

            //response.Headers.Location = uri.Uri;
        }
Пример #22
0
        public Tuple<ClsReturnValues, string, List<ClsUserDisplay>> authenticateUser(string UserName, string Password, string DeviceType, string DeviceName, string Browser)
        {
            string encryptedPassword = Security.Encrypt(Password);
            string token = "";
            List<ClsUserDisplay> ud = new List<ClsUserDisplay>();
            ClsReturnValues result = new ClsReturnValues();
            ClsUsers userGroup = new ClsUsers();
            using (tdoEntities db = new tdoEntities())
            {
                result = db.uspUserAuthentication(UserName, encryptedPassword, DeviceType, DeviceName, Browser).FirstOrDefault();
                userGroup = db.uspGetUsers().Where(p => p.userID == result.ID).FirstOrDefault();

                if (result.IsSuccess == true)
                {

                    ud = db.uspGetUserDisplay(result.ID).ToList<ClsUserDisplay>();
                    // Token issuer
                    TokenIssuer issuer = new TokenIssuer();
                    // A client of the relying party app gets the token
                    token = issuer.GetToken(result, ud.First().userGroupID);

                }

            }
            return new Tuple<ClsReturnValues, string, List<ClsUserDisplay>>(result, token, ud);
        }
Пример #23
0
 public Auth(TokenIssuer tokenIssuer, IPasswordProvider passwordProvider, IMapper mapper)
 {
     _tokenIssuer      = tokenIssuer;
     _passwordProvider = passwordProvider;
     _mapper           = mapper;
 }