Inheritance: System.Security.Principal.IPrincipal
Example #1
1
 public static ClaimsPrincipal CreateWithUserId(long authorId)
 {
     var claim = new Claim(ToBeImplementedClaims.IdClaim, authorId.ToString());
     var identity = new ClaimsIdentity(Enumerable.Repeat(claim, 1));
     var claimsprincipal = new ClaimsPrincipal(identity);
     return claimsprincipal;
 }
Example #2
1
        public string PostLogin(FormDataCollection body)
        {
            string username = body.Get("username");
            string password = body.Get("password");

            using(var session = store.OpenSession())
            {
                var profile = session.Load<Profile>("profiles/" + username);
                if(profile.Password == password)
                {
                    var defaultPrincipal = new ClaimsPrincipal(
                        new ClaimsIdentity(new[] {new Claim(MyClaimTypes.ProfileKey, profile.Id)},
                            "Application" // this is important. if it's null or empty, IsAuthenticated will be false
                            ));
                    var principal = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.
                            ClaimsAuthenticationManager.Authenticate(
                                Request.RequestUri.AbsoluteUri, // this, or any other string can be available
                                                                // to your ClaimsAuthenticationManager
                                defaultPrincipal);
                    AuthenticationManager.EstablishSession(principal);
                    return "login ok";
                }
                return "login failed";
            }
        }
Example #3
0
        public IActionResult OwnerPage()
        {
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            var userID       = _userManager.GetUserId(currentUser);
            var user         = _context.Users.Include(x => x.Msp).Include(x => x.Declarations).FirstOrDefault(x => x.Id == userID);
            var declarations = _context.Declarations.Include(x => x.Employee)
                               .ThenInclude(y => y.Msp).Where(x => x.Employee.MspId == user.MspId);
            var mspId = user.MspId;

            if (user == null)
            {
                return(Content("error"));
            }
            OwnerPageViewModel model = new OwnerPageViewModel()
            {
                Owner        = user,
                UserList     = _context.Users.ToList(),
                Declarations = declarations.ToList()
            };

            // var userEmail = User.FindFirst(ClaimTypes.Email).Value;
            // var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
            // var User = await _context.Users.SingleOrDefault()
            // if(user.)

            return(View(model));
        }
Example #4
0
        public async Task <IActionResult> DetailsPost(int id)
        {
            // Security Claims
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;

            // Claims Identity
            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            // add the current User as the Creator of the Rating
            ProductsRatingViewModel.CurrentUserId = claim.Value;

            // Check the State Model Binding
            if (ModelState.IsValid)
            {
                var productFromDb = await _colibriDbContext.ProductsRatings
                                    .Where(p => p.ProductId == id)
                                    .FirstOrDefaultAsync();

                _colibriDbContext.ProductsRatings.Add(productFromDb);

                await _colibriDbContext.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                return(View(ProductsRatingViewModel));
            }
        }
Example #5
0
        public async Task <IActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            // Security Claims
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;

            // Claims Identity
            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            // add the current User as the Creator of the Advertisement
            ProductsRatingViewModel.CurrentUserId = claim.Value;

            // get the Product
            ProductsRatingViewModel.Product = await _colibriDbContext.ProductsRatings
                                              .Where(p => p.Id == id)
                                              .FirstOrDefaultAsync();

            // get the Application User

            // i18n
            ViewData["ProductDetails"] = _localizer["ProductDetailsText"];
            ViewData["UserName"]       = _localizer["UserNameText"];
            ViewData["ProductName"]    = _localizer["ProductNameText"];
            ViewData["Rating"]         = _localizer["RatingText"];
            ViewData["Description"]    = _localizer["DescriptionText"];
            ViewData["ViewDetails"]    = _localizer["ViewDetailsText"];
            ViewData["BackToList"]     = _localizer["BackToListText"];

            return(View(ProductsRatingViewModel));
        }
Example #6
0
        // POST
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                // Security Claims
                System.Security.Claims.ClaimsPrincipal currentUser = this.User;

                // Claims Identity
                var claimsIdentity = (ClaimsIdentity)this.User.Identity;
                var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

                UserSubscribeNotificationsViewModel.ApplicationUserCategoryTypesSubscriber.ApplicationUserId =
                    claim.Value;

                // create a DB Entry
                var result = await _colibriDbContext.ApplicationUserCategoryTypesSubscribers
                             .AddAsync(UserSubscribeNotificationsViewModel
                                       .ApplicationUserCategoryTypesSubscriber);

                if (result != null)
                {
                    await _colibriDbContext.SaveChangesAsync();

                    _logger.LogInformation("User chose the Notification Category Type.");
                }
                return(RedirectToAction("Index", "", new { area = "" }));
            }
            return(Page());
        }
        public void Configuration(IAppBuilder app)
        {
           
            // token validation
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = Constants.IdentityServerUri,
                RequiredScopes = new[] { "apiAccess" }
            });

            // add app local claims per request
            app.UseClaimsTransformation(incoming =>
            {
                // either add claims to incoming, or create new principal
                var appPrincipal = new ClaimsPrincipal(incoming);
                incoming.Identities.First().AddClaim(new Claim("appSpecific", "some_value"));

                return Task.FromResult(appPrincipal);
            });

            app.UseCors(CorsOptions.AllowAll);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            // web api configuration
            app.UseWebApi(config);
        }
Example #8
0
 public ActionResult Authorize()
 {
     var claims = new ClaimsPrincipal(User).Claims.ToArray();
     var identity = new ClaimsIdentity(claims, "Bearer");
     AuthenticationManager.SignIn(identity);
     return new EmptyResult();
 }
Example #9
0
        public static bool is_authorized_to_handle_jurisdiction_id
        (
            System.Security.Claims.ClaimsPrincipal p_claims_principal,
            ResourceRightEnum p_resource_action,
            mmria.common.model.couchdb.user_role_jurisdiction p_user_role_jurisdiction
        )
        {
            bool result = false;

            var jurisdiction_hashset = mmria.server.util.authorization.get_current_jurisdiction_id_set_for(p_claims_principal);

            foreach (var jurisdiction_item in  jurisdiction_hashset)
            {
                var regex = new System.Text.RegularExpressions.Regex("^" + jurisdiction_item.jurisdiction_id);
                if
                (p_user_role_jurisdiction.jurisdiction_id != null &&
                 regex.IsMatch(p_user_role_jurisdiction.jurisdiction_id) &&
                 p_resource_action == jurisdiction_item.ResourceRight

                )
                {
                    result = true;
                    break;
                }
            }


            return(result);
        }
Example #10
0
        public static bool is_authorized_to_handle_jurisdiction_id
        (
            System.Security.Claims.ClaimsPrincipal p_claims_principal,
            mmria.common.model.couchdb.user p_user
        )
        {
            bool result = false;

            var jurisdiction_hashset = mmria.server.util.authorization.get_current_jurisdiction_id_set_for(p_claims_principal);


            string jurisdicion_view_url      = $"{Program.config_couchdb_url}/jurisdiction/_design/sortable/_view/by_user_id?{p_user.name}";
            var    jurisdicion_curl          = new cURL("GET", null, jurisdicion_view_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string jurisdicion_result_string = null;

            try
            {
                jurisdicion_result_string = jurisdicion_curl.execute();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
                return(result);
            }

            var user_role_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.user_role_jurisdiction> >(jurisdicion_result_string);

            foreach (mmria.common.model.couchdb.get_sortable_view_response_item <mmria.common.model.couchdb.user_role_jurisdiction> cvi in user_role_response.rows)
            {
                bool is_jurisdiction_ok = false;
                foreach ((string, ResourceRightEnum)jurisdiction_item in jurisdiction_hashset)
                {
                    var regex = new System.Text.RegularExpressions.Regex("^" + @jurisdiction_item.Item1);
                    if (cvi.value.jurisdiction_id == null)
                    {
                        cvi.value.jurisdiction_id = "/";
                    }

                    if (regex.IsMatch(cvi.value.jurisdiction_id))
                    {
                        return(true);
                    }
                }

/*
 *              foreach(string jurisdiction_id in  jurisdiction_hashset)
 *              {
 *                  var regex = new System.Text.RegularExpressions.Regex("^" + jurisdiction_id);
 *                  if(p_user._role_jurisdiction.jurisdiction_id != null && regex.IsMatch(p_user_role_jurisdiction.jurisdiction_id))
 *                  {
 *                      result = true;
 *                      break;
 *                  }
 *              }
 */
            }


            return(result);
        }
        /// <summary>
        /// Extracts the User details accessing the service as a unique id in the form
        /// of "{authprovider}:{uniqueId}" using ProviderCrednetials for the logged
        /// in user.
        /// </summary>
        /// <param name="principal">The principal accessing the service.</param>
        /// <param name="request">The HttpRequest used to access the service.</param>
        /// <returns>The unique user id.</returns>
        public async Task<string> GetCurrentUserRegistrationReferenceAsync(ClaimsPrincipal principal, HttpRequestMessage request)
        {
            string provider = principal?.FindFirst("http://schemas.microsoft.com/identity/claims/identityprovider").Value;

            ProviderCredentials creds = null;
            if (string.Equals(provider, "facebook", StringComparison.OrdinalIgnoreCase))
            {
                creds = await principal.GetAppServiceIdentityAsync<FacebookCredentials>(request);
            }
            else if (string.Equals(provider, "google", StringComparison.OrdinalIgnoreCase))
            {
                creds = await principal.GetAppServiceIdentityAsync<GoogleCredentials>(request);
            }
            else if (string.Equals(provider, "twitter", StringComparison.OrdinalIgnoreCase))
            {
                creds = await principal.GetAppServiceIdentityAsync<TwitterCredentials>(request);
            }
            else if (string.Equals(provider, "microsoftaccount", StringComparison.OrdinalIgnoreCase))
            {
                creds = await principal.GetAppServiceIdentityAsync<MicrosoftAccountCredentials>(request);
            }

            if (creds == null)
            {
                throw ServiceExceptions.UserNullException();
            }

            // Format user details in the desired form of {authprovider}:{uniqueId}
            string authProvider = creds.Provider;
            string uniqueId = creds.UserClaims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.NameIdentifier))?.Value;
            var uniqueUserName = $"{authProvider}:{uniqueId}";

            return uniqueUserName;
        }
Example #12
0
        public async Task <IActionResult> Index()
        {
            DashboardViewModel _model = new DashboardViewModel();

            using RDATContext context = new RDATContext();
            List <TestingLog> activeLogs = context.TestingLogs.Where(tl => Convert.ToInt32(tl.Reported_Results) < 1).ToList();

            char[] goodResults = { '1', '2', '3' };

            // Get User Roles
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            bool IsAdmin    = currentUser.IsInRole("Admin");
            bool IsReadOnly = currentUser.IsInRole("ReadOnly");

            _model.BadgeTotalActiveDrivers     = context.Drivers.Where(d => d.TerminationDate == null && !d.isDelete).Count();
            _model.BadgeTotalActiveCompanies   = context.Companys.Where(c => c.Status == "1" && c.isDelete != true).Count(); // context.Companys.Where(d => ??).Count();
            _model.BadgeOutstandingDrugTest    = activeLogs.Where(tl => tl.Test_Type == "Drug").Count();
            _model.BadgeOutstandingAlcoholTest = activeLogs.Where(tl => tl.Test_Type == "Alcohol").Count();

            _model.FavoriteCompanies = context.Companys.Where(c => c.isFavorite).OrderByDescending(p => p.Id).ToList();

            _model.FavoriteDrivers = context.Drivers.Where(d => d.isFavorite).OrderByDescending(p => p.Id).ToList();



            return(View(_model));
        }
Example #13
0
        public async Task <IActionResult> Dislike(int id)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Account", "Identity", new { id = "Login" }));
            }
            var memy = db.Memy.SingleOrDefault(s => s.Id_mema == id);

            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            var memyyy = (from a in db.Marking
                          where a.Authorr == currentUser.Identity.Name && a.IdMema == id
                          select a).FirstOrDefault();

            memy.Dislike = memy.Dislike + 1;
            if (id != memy.Id_mema)
            {
                return(NotFound());
            }

            if (ModelState.IsValid && memyyy.IdMema == id && memyyy.CountLike == 0 && memyyy.CountDislike == 0)
            {
                memyyy.CountLike    = 1;
                memyyy.CountDislike = 1;


                db.Update(memy);
                await db.SaveChangesAsync();

                return(RedirectToAction("Show", new { id = id }));
            }
            return(RedirectToAction("Show", new { id = id }));
        }
        public async Task UpdateConsentAsync(Client client, ClaimsPrincipal user, IEnumerable<string> scopes)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (user == null) throw new ArgumentNullException("user");

            if (client.AllowRememberConsent)
            {
                var subject = user.GetSubjectId();
                var clientId = client.ClientId;

                if (scopes != null && scopes.Any())
                {
                    var consent = new Consent
                    {
                        Subject = subject,
                        ClientId = clientId,
                        Scopes = scopes
                    };
                    await _store.UpdateAsync(consent);
                }
                else
                {
                    await _store.RevokeAsync(subject, clientId);
                }
            }
        }
        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += (sender, e) =>
            {
                HttpContext httpContext = ((HttpApplication)sender).Context;

                dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(
                    new HttpContextWrapper(httpContext),
                    rawSignedRequest =>
                    {
                        FacebookConfiguration config = GlobalFacebookConfiguration.Configuration;
                        FacebookClient client = config.ClientProvider.CreateClient();
                        return client.ParseSignedRequest(rawSignedRequest);
                    });

                if (signedRequest != null)
                {
                    string userId = signedRequest.user_id;
                    if (!String.IsNullOrEmpty(userId))
                    {
                        ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) }));
                        Thread.CurrentPrincipal = principal;
                        httpContext.User = principal;
                    }
                }
            };
        }
        public ClaimsPrincipal Validate(string userName, string password)
        {
            var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);
            var credentials = new ClientCredentials();
            credentials.UserName.UserName = userName;
            credentials.UserName.Password = password;

            GenericXmlSecurityToken genericToken;
            genericToken = WSTrustClient.Issue(
                new EndpointAddress(_address),
                new EndpointAddress(_realm),
                binding,
                credentials) as GenericXmlSecurityToken;

            var config = new SecurityTokenHandlerConfiguration();
            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(_realm));

            config.CertificateValidationMode = X509CertificateValidationMode.None;
            config.CertificateValidator = X509CertificateValidator.None;

            var registry = new ConfigurationBasedIssuerNameRegistry();
            registry.AddTrustedIssuer(_issuerThumbprint, _address);
            config.IssuerNameRegistry = registry;

            var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config);

            ClaimsPrincipal principal;
            var token = genericToken.ToSecurityToken();
            principal = new ClaimsPrincipal(handler.ValidateToken(token));

            Tracing.Information("Successfully requested token for user via WS-Trust");
            return FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate("ResourceOwnerPasswordValidation", principal);
        }
 public virtual void Authenticated(ClaimsPrincipal principal, IDictionary<string, string> properties, IDictionary<string, object> description)
 {
     Accepted = true;
     Principal = principal;
     Properties = properties;
     Description = description;
 }
        public virtual IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var userName = principal.Identity.Name;
            var claims = new List<Claim>(from c in principal.Claims select c);

            var nameIdClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
            if (nameIdClaim == null)
            {
                claims.Add(new Claim(ClaimTypes.NameIdentifier, userName));
            }

            // email address
            var membership = Membership.FindUsersByName(userName)[userName];
            if (membership != null)
            {
                string email = membership.Email;
                if (!String.IsNullOrEmpty(email))
                {
                    claims.Add(new Claim(ClaimTypes.Email, email));
                }
            }

            // roles
            GetRolesForToken(userName).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

            // profile claims
            claims.AddRange(GetProfileClaims(userName));

            return claims;
        }
        public void Check_PoliciesCanMutateUsersClaims()
        {
            // Arrange
            var user = new ClaimsPrincipal(
                new ClaimsIdentity(new Claim[0], "Basic")
                );

            var policies = new IAuthorizationPolicy[] {
                new FakePolicy() {
                    ApplyAsyncAction = (context) => {
                        if (!context.Authorized)
                        {
                            context.UserClaims.Add(new Claim("Permission", "CanDeleteComments"));
                            context.Retry = true;
                        }
                    }
                }
            };

            var authorizationService = new DefaultAuthorizationService(policies);

            // Act
            var allowed = authorizationService.Authorize(new Claim("Permission", "CanDeleteComments"), user);

            // Assert
            Assert.True(allowed);
        }
Example #20
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
        {
            loggerfactory.AddConsole(LogLevel.Information);

            app.UseCookieAuthentication(options =>
            {
                options.AutomaticAuthenticate = true;
            });

            app.Run(async context =>
            {
                if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
                {
                    var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bob") }, CookieAuthenticationDefaults.AuthenticationScheme));
                    await context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);

                    context.Response.ContentType = "text/plain";
                    await context.Response.WriteAsync("Hello First timer");
                    return;
                }

                context.Response.ContentType = "text/plain";
                await context.Response.WriteAsync("Hello old timer");
            });
        }
 internal static void GetClaimsPrincipalWithNoSub()
 {
     List<Claim> claims = new List<Claim>();
     ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer", "name", "role"));
     ClaimsPrincipal.Current.AddIdentity(principal.Identity as ClaimsIdentity);
     ClaimsPrincipal.ClaimsPrincipalSelector = () => principal;
 }
        public ClaimsPrincipal ValidateUser(string token)
        {
            try
            {
                var decodedtoken = JsonWebToken.DecodeToObject(token, secretKey) as Dictionary<string, object>;
                if (decodedtoken == null)
                    return null;

                DateTime expiry = DateTime.Parse(decodedtoken["Expires"].ToString());
                if (expiry < DateTime.UtcNow) return null;

                var claims = new List<Claim>();

                if (decodedtoken.ContainsKey("Claims"))
                {
                    foreach (Dictionary<string, object> kvp in ((ArrayList) decodedtoken["Claims"]))
                    {
                        claims.Add(new Claim(kvp["Type"].ToString(), kvp["Value"].ToString()));
                    }
                }

                var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Token"));

                return claimsPrincipal;
            }
            catch (Exception)
            {
                return null;
            }
        }
Example #23
0
        public async Task <IActionResult> UploadFiles(List <IFormFile> files)
        {
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;

            var user = await _userManager.GetUserAsync(User);

            var email   = user.Email;
            var dirName = $"Dir{email}";

            if (files == null || files.Count == 0)
            {
                return(Content("files not selected"));
            }

            foreach (var file in files)
            {
                var path = Path.Combine(
                    Directory.GetCurrentDirectory(), $"wwwroot/upload/{dirName}/",
                    file.GetFilename());

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }

            return(RedirectToAction("Files"));
        }
        public virtual async Task<IEnumerable<Claim>> GetIdentityTokenClaimsAsync(ClaimsPrincipal subject, Client client, IEnumerable<Scope> scopes, bool includeAllIdentityClaims, NameValueCollection request)
        {
            Logger.Debug("Getting claims for identity token");

            List<Claim> outputClaims = new List<Claim>(GetStandardSubjectClaims(subject));
            var additionalClaims = new List<string>();

            // fetch all identity claims that need to go into the id token
            foreach (var scope in scopes)
            {
                if (scope.IsOpenIdScope)
                {
                    foreach (var scopeClaim in scope.Claims)
                    {
                        if (includeAllIdentityClaims || scopeClaim.AlwaysIncludeInIdToken)
                        {
                            additionalClaims.Add(scopeClaim.Name);
                        }
                    }
                }
            }

            if (additionalClaims.Count > 0)
            {
                var claims = await _users.GetProfileDataAsync(subject.GetSubjectId(), additionalClaims);
                if (claims != null)
                {
                    outputClaims.AddRange(claims);
                }
            }

            return outputClaims;
        }
Example #25
0
        public static bool is_authorized_to_handle_jurisdiction_id
        (
            System.Security.Claims.ClaimsPrincipal p_claims_principal,
            ResourceRightEnum p_resoure_right_enum,
            string jurisdiction_id
        )
        {
            bool result = false;

            var jurisdiction_hashset = mmria.server.util.authorization.get_current_jurisdiction_id_set_for(p_claims_principal);


            foreach (var jurisdiction_item in jurisdiction_hashset)
            {
                var regex = new System.Text.RegularExpressions.Regex("^" + @jurisdiction_item.jurisdiction_id);
                if
                (
                    regex.IsMatch(jurisdiction_id) &&
                    p_resoure_right_enum == jurisdiction_item.ResourceRight
                )
                {
                    result = true;
                    break;
                }
            }

            return(result);
        }
Example #26
0
        public bool IsAuthorize()
        {
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            //throw new Exception(currentUser.Identity.IsAuthenticated.ToString());

            return(currentUser.Identity.IsAuthenticated);
        }
        public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
        {
            if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated)
            {
                // Get the claims required to make further Graph API enquiries about the user
                //Claim nameIdClaim = incomingPrincipal.FindFirst(NameIdClaim);
                //if (nameIdClaim == null)
                //{
                //    throw new NotSupportedException("Name claim not available, role authentication is not supported");
                //}
                Claim nameClaim = incomingPrincipal.FindFirst(NameClaim);
                if (nameClaim == null)
                {
                    throw new NotSupportedException("Name claim not available, role authentication is not supported");
                }

                string userName = nameClaim.Value;
                //string currentUserObjectId = objectIdentifierClaim.Value;

                //load up the roles as RoleClaims
                TableUser user = new TableUser(userName);
                Task<IList<string>> t = _userStore.GetRolesAsync(user);
                t.RunSynchronously();
                IList<string> currentRoles = t.Result;
                foreach (string role in currentRoles)
                {
                    ((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, _issuer));
                }
            }
            return base.Authenticate(resourceName, incomingPrincipal);
        }
Example #28
0
        public async Task <ActionResult <IEnumerable <ExcuseDTO> > > PreviousExcuses()
        {
            var emp = new Employee();
            List <ExcuseDTO> lstExecuses = new List <ExcuseDTO>();

            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            var email    = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;
            var lstUsers = _context.Employees.Where(e => e.Email == email).ToList();

            if (lstUsers.Count > 0)
            {
                emp = lstUsers[0];


                lstExecuses = await _context.Excuses.Where(ex => ex.Employee.Email == emp.Email).Select(ex => new ExcuseDTO
                {
                    ID             = ex.ID,
                    Approved       = ex.Approved,
                    Comment        = ex.Comment,
                    Date           = ex.Date,
                    ProfessionName = ex.Employee.Profession.Name,
                    EmployeeName   = ex.Employee.Name,
                    Hours          = ex.Hours,
                    Time           = ex.Time
                }).ToListAsync();
            }
            return(lstExecuses);
        }
        public async Task <IEnumerable <WeatherForecast> > Get(/*, IsActiveContext isActivecontext*/)//string returnUrl = null)
        {
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            // var user = await _userManager.GetUserAsync(User);
            var userName = await _userManager.GetUserAsync(User);// var user = await _userManager.GetUserAsync(User);

            var             currentUserId = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
            ApplicationUser user          = await _userManager.FindByIdAsync(currentUserId);


            //var sub = profileDatacontext.Subject.GetSubjectId();
            //var user = await _userManager.FindByIdAsync(sub);
            //var principal = await _claimsFactory.CreateAsync(user);

            //var claims = principal.Claims.ToList();
            //claims = claims.Where(claim => profileDatacontext.RequestedClaimTypes.Contains(claim.Type)).ToList();
            //claims.Add(new Claim(JwtClaimTypes.GivenName, user.UserName));

            var rng = new Random();

            return(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
                   .ToArray());
        }
        public async Task<bool> RequiresConsentAsync(Client client, ClaimsPrincipal user, IEnumerable<string> scopes)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (user == null) throw new ArgumentNullException("user");

            if (!client.RequireConsent)
            {
                return false;
            }

            // TODO: validate that this is a correct statement
            if (!client.AllowRememberConsent)
            {
                return true;
            }

            if (scopes == null || !scopes.Any())
            {
                return false;
            }
            
            var consent = await _store.LoadAsync(user.GetSubjectId(), client.ClientId);
            if (consent != null && consent.Scopes != null)
            {
                var intersect = scopes.Intersect(consent.Scopes);
                return !(scopes.Count() == intersect.Count());
            }

            return true;
        }
Example #31
0
        public async Task ExecuteResultAsync_InvokesSignInAsyncOnConfiguredScheme()
        {
            // Arrange
            var principal = new ClaimsPrincipal();
            var authProperties = new AuthenticationProperties();
            var authenticationManager = new Mock<AuthenticationManager>();
            authenticationManager
                .Setup(c => c.SignInAsync("Scheme1", principal, authProperties))
                .Returns(TaskCache.CompletedTask)
                .Verifiable();
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(c => c.RequestServices).Returns(CreateServices());
            httpContext.Setup(c => c.Authentication).Returns(authenticationManager.Object);
            var result = new SignInResult("Scheme1", principal, authProperties);
            var routeData = new RouteData();

            var actionContext = new ActionContext(
                httpContext.Object,
                routeData,
                new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            authenticationManager.Verify();
        }
        /// <summary>
        /// Checks authorization for the given operation context based on default policy evaluation.
        /// </summary>
        /// <param name="operationContext">The <see cref="T:System.ServiceModel.OperationContext" /> for the current authorization request.</param>
        /// <returns>
        /// true if access is granted; otherwise, false. The default is true.
        /// </returns>
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            var retVal = base.CheckAccessCore(operationContext);

            SimpleWebToken token = null;

            if (retVal)
            {
                // Extract authorization data.
                var requestMessage = operationContext.RequestContext.RequestMessage;
                var httpDetails = requestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                var requestUri = WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.UriTemplateMatch != null ? WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri : requestMessage.Headers.To;

                token = ReadAuthToken(httpDetails);
                retVal = token != null && IsValidToken(token, requestUri);
            }

            var securityContext = ServiceSecurityContext.Anonymous;
            ClaimsPrincipal principal = new GenericPrincipal(new GenericIdentity(String.Empty), new string[0]);
            var identity = principal.Identity;

            if (retVal)
            {
                var claims = token.Claims.Select(keyValuePair => new Claim(keyValuePair.Key, keyValuePair.Value));
                identity = new ClaimsIdentity(claims, "OAUTH-SWT");
                principal = new ClaimsPrincipal(identity);
                Thread.CurrentPrincipal = principal;
            }
            securityContext.AuthorizationContext.Properties["Principal"] = principal;
            securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { identity };
            operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;

            return retVal;
            //return true;
        }
 public Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName)
 {
     var policy = _options.GetPolicy(policyName);
     return (policy == null)
         ? Task.FromResult(false)
         : this.AuthorizeAsync(user, resource, policy);
 }
Example #34
0
        //[HttpGet("getContactTemplate")]
        //public object GetContactTemplate()
        //{
        //    Contact contact = new Contact();
        //    ContactType[] contactTypes = this.db.ContactTypes.ToArray();
        //    ContactSource[] contactSources = this.db.ContactSources.ToArray();
        //    return new { contact = contact, contactType = contactTypes, contactSource = contactSources };
        //}


        private async ValueTask <ApplicationUser> GetUserAsync()
        {
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            var currentUserId = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;

            return(await _userManager.FindByIdAsync(currentUserId));
        }
 public bool Authorize(ClaimsPrincipal user, object resource, string policyName)
 {
     var policy = _options.GetPolicy(policyName);
     return (policy == null) 
         ? false 
         : this.Authorize(user, resource, policy);
 }
Example #36
0
        public static string getCurrentUserId(System.Security.Claims.ClaimsPrincipal user)
        {
            var claimsIdentity = (ClaimsIdentity)user.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            return(claim.Value);
        }
        public async Task<AuthorizeResponse> CreateCodeFlowResponseAsync(ValidatedAuthorizeRequest request, ClaimsPrincipal subject)
        {
            var code = new AuthorizationCode
            {
                Client = request.Client,
                Subject = subject,

                IsOpenId = request.IsOpenIdRequest,
                RequestedScopes = request.ValidatedScopes.GrantedScopes,
                RedirectUri = request.RedirectUri,

                WasConsentShown = request.WasConsentShown,
                RefreshTokenLifetime = request.Client.RefreshTokenLifetime
            };

            // store id token and access token and return authorization code
            var id = Guid.NewGuid().ToString("N");
            await _authorizationCodes.StoreAsync(id, code);

            return new AuthorizeResponse
            {
                RedirectUri = request.RedirectUri,
                Code = id,
                State = request.State
            };
        }
        public IEnumerable<Claim> GetClaims(ClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var userName = principal.Identity.Name;
            var claims = new List<Claim>(from c in principal.Claims select c);

            // email address
            string email = Membership.FindUsersByName(userName)[userName].Email;
            if (!String.IsNullOrEmpty(email))
            {
                claims.Add(new Claim(ClaimTypes.Email, email));
            }

            // roles
            GetRolesForToken(userName).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

            // profile claims
            if (ProfileManager.Enabled)
            {
                var profile = ProfileBase.Create(userName, true);
                if (profile != null)
                {
                    foreach (SettingsProperty prop in ProfileBase.Properties)
                    {
                        string value = profile.GetPropertyValue(prop.Name).ToString();
                        if (!String.IsNullOrWhiteSpace(value))
                        {
                            claims.Add(new Claim(ProfileClaimPrefix + prop.Name.ToLowerInvariant(), value));
                        }
                    }
                }
            }

            return claims;
        }
        public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType, out TokenResponse response)
        {
            SecurityToken token = null;
            response = new TokenResponse { TokenType = tokenType };

            var result = TryIssueToken(appliesTo, principal, tokenType, out token);
            if (result == false)
            {
                return false;
            }

            var ts = token.ValidTo.Subtract(DateTime.UtcNow);
            response.ExpiresIn = (int)ts.TotalSeconds;

            if (tokenType == TokenTypes.JsonWebToken || tokenType == TokenTypes.SimpleWebToken)
            {
                var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[tokenType];
                response.AccessToken = handler.WriteToken(token);
            }
            else
            {
                var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;
                var sb = new StringBuilder(128);
                handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token);

                response.AccessToken = sb.ToString();
            }

            return result;
        }
        public void Check_ApplyCanMutateCheckedClaims()
        {
            // Arrange
            var user = new ClaimsPrincipal(
                new ClaimsIdentity( new Claim[] { new Claim("Permission", "CanDeleteComments") }, "Basic")
                );

            var policies = new IAuthorizationPolicy[] {
                new FakePolicy() {
                    ApplyAsyncAction = (context) => {
                        // for instance, if user owns the comment
                        if(!context.Claims.Any(claim => claim.Type == "Permission" && claim.Value == "CanDeleteComments"))
                        {
                            context.Claims.Add(new Claim("Permission", "CanDeleteComments"));
                            context.Retry = true;
                        }
                    }
                }
            };

            var authorizationService = new DefaultAuthorizationService(policies);

            // Act
            var allowed = authorizationService.Authorize(Enumerable.Empty<Claim>(), user);

            // Assert
            Assert.True(allowed);
        }
Example #41
0
        /// <summary>
        /// Add an additional ClaimsIdentity to the ClaimsPrincipal in the "server.User" environment key
        /// </summary>
        /// <param name="identity"></param>
        public void AddUserIdentity(IIdentity identity)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }
            var newClaimsPrincipal = new ClaimsPrincipal(identity);

            IPrincipal existingPrincipal = _context.Request.User;
            if (existingPrincipal != null)
            {
                var existingClaimsPrincipal = existingPrincipal as ClaimsPrincipal;
                if (existingClaimsPrincipal == null)
                {
                    IIdentity existingIdentity = existingPrincipal.Identity;
                    if (existingIdentity.IsAuthenticated)
                    {
                        newClaimsPrincipal.AddIdentity(existingIdentity as ClaimsIdentity ?? new ClaimsIdentity(existingIdentity));
                    }
                }
                else
                {
                    foreach (var existingClaimsIdentity in existingClaimsPrincipal.Identities)
                    {
                        if (existingClaimsIdentity.IsAuthenticated)
                        {
                            newClaimsPrincipal.AddIdentity(existingClaimsIdentity);
                        }
                    }
                }
            }
            _context.Request.User = newClaimsPrincipal;
        }
Example #42
0
        private static CommandResult ProcessResponse(IOptions options, Saml2Response samlResponse)
        {
            var principal = new ClaimsPrincipal(samlResponse.GetClaims(options));

            principal = options.SPOptions.SystemIdentityModelIdentityConfiguration
                .ClaimsAuthenticationManager.Authenticate(null, principal);

            var requestState = samlResponse.GetRequestState(options);

            if(requestState == null && options.SPOptions.ReturnUrl == null)
            {
                throw new ConfigurationErrorsException(MissingReturnUrlMessage);
            }

            return new CommandResult()
            {
                HttpStatusCode = HttpStatusCode.SeeOther,
                Location = requestState?.ReturnUrl ?? options.SPOptions.ReturnUrl,
                Principal = principal,
                RelayData =
                    requestState == null
                    ? null
                    : requestState.RelayData
            };
        }
Example #43
0
        public async Task <IActionResult> Details(string id)
        {
            if (id == "")
            {
                return(NotFound());
            }

            // Security Claims
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;

            // Claims Identity
            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            ApplicationUserRatingViewModel.CurrentUserId = claim.Value;

            // get the User
            ApplicationUserRatingViewModel.ApplicationUser = await _colibriDbContext.ApplicationUserRatings
                                                             .Where(p => p.ApplicationUserRatedId == id)
                                                             .FirstOrDefaultAsync();

            // get the Application User

            // i18n
            ViewData["ApplicationUserDetails"] = _localizer["ApplicationUserDetailsText"];
            ViewData["UserName"]    = _localizer["UserNameText"];
            ViewData["RatedUser"]   = _localizer["RatedUserText"];
            ViewData["RatingUser"]  = _localizer["RatingUserText"];
            ViewData["Rating"]      = _localizer["RatingText"];
            ViewData["Description"] = _localizer["DescriptionText"];
            ViewData["ViewDetails"] = _localizer["ViewDetailsText"];
            ViewData["BackToList"]  = _localizer["BackToListText"];

            return(View(ApplicationUserRatingViewModel));
        }
        public async Task<IActionResult> Unauthorized(string returnUrl = null)
        {
            const string Issuer = "https://contoso.com";
            
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, "barry", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim("EmployeeId", "123", ClaimValueTypes.String, Issuer));
            claims.Add(new Claim(ClaimTypes.DateOfBirth, "1970-06-08", ClaimValueTypes.Date));
            claims.Add(new Claim("BadgeNumber", "123456", ClaimValueTypes.String, Issuer));
            //claims.Add(new Claim("TemporaryBadgeExpiry", DateTime.Now.AddDays(1).ToString(), ClaimValueTypes.String, Issuer));
            //claims.Add(new Claim("TemporaryBadgeExpiry", DateTime.Now.AddDays(-1).ToString(), ClaimValueTypes.String, Issuer));
            var userIdentity = new ClaimsIdentity("SuperSecureLogin");
            userIdentity.AddClaims(claims);

            var userPrincipal = new ClaimsPrincipal(userIdentity);

            await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal,
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });

            return RedirectToLocal(returnUrl);
        }
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {  
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction(nameof(HomeController.Index), "Home");
            }

            ViewData["ReturnUrl"] = returnUrl;

            if (!ModelState.IsValid || model.UserName != model.Password) {
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
            }

            var claims = new List<Claim>() {
                new Claim(ClaimTypes.Name, model.UserName),
                new Claim(ClaimTypes.Role, "User"),
                new Claim(ClaimTypes.Country, "USA" ),
                new Claim("Event", "South Florida Code Camp 2016")
            };

            if (model.UserName.Equals("admin", StringComparison.OrdinalIgnoreCase)) {
                claims.Add(new Claim(ClaimTypes.Role, "Administrator"));
            }

            var identity = new ClaimsIdentity(claims, "local", ClaimTypes.Name, ClaimTypes.Role);
            var principal = new ClaimsPrincipal(identity);

            await HttpContext.Authentication.SignInAsync("Cookies", principal);

            return RedirectToLocal(returnUrl);
        }
        ClaimsPrincipal Transform(ClaimsPrincipal incomingPrincipal)
        {
            // todo... this is where we would put in any extra claim information
            incomingPrincipal.Identities.FirstOrDefault().AddClaim(new Claim(ClaimTypes.Role, "Admin"));

            return incomingPrincipal;
        }
        public async Task <IActionResult> ImplicitLanding(string accessToken, string idToken)
        {
            System.Security.Claims.ClaimsPrincipal claimPrincipal = null;

            Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters =
                new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidateIssuerSigningKey = false,
                ValidateAudience         = false,
                ValidateIssuer           = false,
                ValidateLifetime         = false
            };

            System.IdentityModel.Tokens.Jwt.JwtSecurityToken        jwtSecurityToken;
            System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            jwtSecurityToken = handler.ReadJwtToken(idToken);
            List <System.Security.Claims.Claim> claims = jwtSecurityToken.Claims.ToList();

            claims.Add(new Claim("idToken", idToken));
            claims.Add(new Claim("accessToken", accessToken));

            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                //AllowRefresh = <bool>,
                // Refreshing the authentication session should be allowed.

                //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
                // The time at which the authentication ticket expires. A
                // value set here overrides the ExpireTimeSpan option of
                // CookieAuthenticationOptions set with AddCookie.

                //IsPersistent = true,
                // Whether the authentication session is persisted across
                // multiple requests. When used with cookies, controls
                // whether the cookie's lifetime is absolute (matching the
                // lifetime of the authentication ticket) or session-based.

                //IssuedUtc = <DateTimeOffset>,
                // The time at which the authentication ticket was issued.

                //RedirectUri = <string>
                // The full path or absolute URI to be used as an http
                // redirect response value.
            };

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);



            return(View());
        }
Example #48
0
        public async Task <IActionResult> UserLogin([FromBody] LoginInputModel model)
        {
            var users  = _roleService.GetUserNameByEmail(model.Email);
            var result = await _signInManager.PasswordSignInAsync(users, model.Password, model.RememberLogin, lockoutOnFailure : false);

            if (result.Succeeded)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                var userRoles = await _userManager.GetRolesAsync(user);

                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()),
                }.Union(userRoles.Select(m => new Claim(ClaimTypes.Role, m)));

                var token = new JwtSecurityToken
                            (
                    issuer: "Arsalan",
                    audience: "You",
                    claims: claims,
                    expires: DateTime.UtcNow.AddDays(60),
                    notBefore: DateTime.UtcNow,
                    signingCredentials: new SigningCredentials(new SymmetricSecurityKey
                                                                   (Encoding.UTF8.GetBytes("rlyaKithdrYVl6Z80ODU350md")),
                                                               SecurityAlgorithms.HmacSha256)
                            );


                System.Security.Claims.ClaimsPrincipal currentUser = this.User;
                var employeProfile = new UserInfoDto
                {
                    UserName = user.UserName,
                    Id       = user.Id,
                    RoleName = userRoles.Select(i => i).FirstOrDefault()
                };
                return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), employeProfile }));

                // var httpcontext = HttpContext.Request.Method;

                //var info = await _signInManager.GetExternalLoginInfoAsync();
                //var claimsPrincipal = await this._signInManager.CreateUserPrincipalAsync(user);
                //((ClaimsIdentity)claimsPrincipal.Identity).AddClaim(new Claim("accessToken", info.AuthenticationTokens.Single(t => t.Name == "access_token").Value));
                //await HttpContext.Authentication.SignInAsync("Identity.Application", claimsPrincipal);
                //var accessToken = info.AuthenticationTokens.Single(f => f.Name == "access_token").Value;
                //var tokenType = info.AuthenticationTokens.Single(f => f.Name == "token_type").Value;
                //var expiryDate = info.AuthenticationTokens.Single(f => f.Name == "expires_at").Value;

                //HttpContext.GetTokenAsync("token_Name")

                //return Json(GetUserid(), user());
            }
            else
            {
                return(Json("User is not Authenticate"));
            }
        }
 public IActionResult Index()
 {
     if (User.Identity.IsAuthenticated)
     {
         ViewBag.Username = User.Identity.Name;
     }
     System.Security.Claims.ClaimsPrincipal currentUser = this.User;
     return(View());
 }
        public IActionResult GetAllPaging(string startDate, string endDate, string keyword, int page, int pageSize)
        {
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;

            var id = _userManager.GetUserId(User);

            var model = _billService.GetPagingForUser(startDate, endDate, keyword, page, pageSize, id.ToString());

            return(new OkObjectResult(model));
        }
        public async Task <SignInResult> PasswordSignInAsync(string userName, string password, bool isPersistent, bool lockoutOnFailure)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return(SignInResult.Failed);
            }

            if (string.IsNullOrEmpty(password))
            {
                return(SignInResult.Failed);
            }

            var user = await FindByNameAsync(userName);

            if (user == null)
            {
                return(SignInResult.Failed);
            }

            var claims = await GetClaimsAsync(user);

            if (claims == null)
            {
                return(SignInResult.Failed);
            }

            var principal = await CreateUserPrincipalAsync(user);

            if (principal == null)
            {
                return(SignInResult.Failed);
            }

            // Create new list with claims as principal
            var resultU = claims.Union(principal.Claims, new ClaimComparer());

            //var query = from claim in claims
            //             pclaim in principal.Claims on claim.Type equals pclaim.Type
            //            select new { claim.Type, pclaim.V}
            var identity = new ClaimsIdentity(
                resultU,
                //principal.Claims,
                //*************************
                // This should be explored further to see if there is a better type.
                Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme
                );

            principal = new System.Security.Claims.ClaimsPrincipal(identity);
            //This next statement is the heart at reflecting that the user is signed in.
            this.SetAuthenticationState(Task.FromResult(new AuthenticationState(principal)));
            // now the authState is updated
            var authState = await GetAuthenticationStateAsync();

            return(SignInResult.Success);
        }
Example #52
0
        //public async Task<IActionResult> best(string searchName = "PRO")
        //{
        //    System.Security.Claims.ClaimsPrincipal currentUser = this.User;
        //    var claimsIdentity = (ClaimsIdentity)this.User.Identity;
        //    var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
        //    StringBuilder param = new StringBuilder();


        //    param.Append("&searchName=");

        //    if (searchName != null)
        //    {
        //        param.Append(searchName);
        //    }


        //    int count = 0;
        //    var productList = await _db.Products.Include(m => m.Merchants).Include(m => m.Brands).ToListAsync();
        //    var brandlist = await _db.Brands.ToListAsync();


        //    if (searchName != null)
        //    {
        //        productList = await _db.Products.Include(m => m.Merchants).Include(m => m.Brands).Where(a => a.TypeProduct.TypePro.Contains(searchName.ToLower())).ToListAsync();

        //        for (int i = 0; i < productList.Count; i++)
        //        {
        //            ShopVM.Products.Add(productList[i]);
        //            count++;
        //        }
        //    }
        //    for (int i = 0; i < brandlist.Count; i++)
        //    {
        //        ShopVM.Brands.Add(brandlist[i]);
        //    }
        //    HttpContext.Session.Set("ssAmount", count);

        //    return View(ShopVM);
        //}

        public async Task <IActionResult> Index(string searchName = null)
        {
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            var           claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var           claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
            StringBuilder param          = new StringBuilder();


            param.Append("&searchName=");

            if (searchName != null)
            {
                param.Append(searchName);
            }


            int count       = 0;
            var productList = await _db.Products.Include(m => m.Merchants).Include(m => m.Brands).Where(m => m.Available == true).ToListAsync();

            var brandlist = await _db.Brands.ToListAsync();

            var typeProduct = await _db.TypeProducts.ToListAsync();


            if (searchName != null)
            {
                productList = await _db.Products.Include(m => m.Merchants).Include(m => m.Brands).Where(a => a.Name.ToLower().Contains(searchName.ToLower())).ToListAsync();

                for (int i = 0; i < productList.Count; i++)
                {
                    ShopVM.Products.Add(productList[i]);
                    count++;
                }
            }
            else
            {
                for (int i = 0; i < productList.Count; i++)
                {
                    ShopVM.Products.Add(productList[i]);
                    count++;
                }
            }
            for (int i = 0; i < brandlist.Count; i++)
            {
                ShopVM.Brands.Add(brandlist[i]);
            }
            for (int i = 0; i < typeProduct.Count; i++)
            {
                ShopVM.typeProducts.Add(typeProduct[i]);
            }
            HttpContext.Session.Set("ssAmount", count);

            return(View(ShopVM));
            //return RedirectToAction("Index", "ssAmount");
        }
        public async Task <IActionResult> ExxportPDF()
        {
            System.Security.Claims.ClaimsPrincipal currentAdmin = this.User;
            OrderViewModel OrderVM = new OrderViewModel()
            {
                Orders = new List <Models.Order>()
            };

            OrderVM.Orders = _db.Orders.Include(x => x.SalesPerson).ToList();
            return(new ViewAsPdf(OrderVM));
        }
Example #54
0
        public async Task <IActionResult> SetFirstDealerTempData(string MatchId, string FirstDealer)
        {
            MatchB match = new MatchB();

            match       = _context.MatchB.Include(o => o.Games).Include(p => p.North).Include(p => p.South).Include(p => p.East).Include(p => p.West).FirstOrDefault(m => m.Id == MatchId);
            match.Games = new List <GameB>();
            GameB game = new GameB();

            game.Id     = 0;
            game.Dealer = _context.Player.FirstOrDefault(p => p.Id == FirstDealer);
            game.North  = match.North;
            game.South  = match.South;
            game.East   = match.East;
            game.West   = match.West;
            if (game.Dealer.Id == game.North.Id)
            {
                game.NextPlayer = game.East;
            }
            else
            {
                if (game.Dealer.Id == game.East.Id)
                {
                    game.NextPlayer = game.South;
                }
                else
                {
                    if (game.Dealer.Id == game.South.Id)
                    {
                        game.NextPlayer = game.West;
                    }
                    else
                    {
                        game.NextPlayer = game.North;
                    }
                }
            }
            game.Type   = "";
            game.Value  = 0;
            game.Status = "Dealing";
            match       = _context.MatchB.FirstOrDefault(m => m.Id == MatchId);
            match.Games.Add(game);
            match.LastHand       = new HandB();
            match.LastHand.Id    = match.Id;
            match.LastHand.Cards = new List <CardB>();
            _context.SaveChanges();

            System.Security.Claims.ClaimsPrincipal currentUser = this.User;
            string UUID = currentUser.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;

            ViewBag.Dealer = FirstDealer;
            ViewBag.Player = UUID;
            Response.Redirect("/../../MatchesB/Play/" + MatchId);
            return(View("MatchPlay", match));
        }
        public async Task <SignInResult> SignOutAsync()
        {
            var principal = new ClaimsPrincipal();
            var identity  = new ClaimsIdentity();

            principal = new System.Security.Claims.ClaimsPrincipal(identity);

            this.SetAuthenticationState(Task.FromResult(new AuthenticationState(principal)));
            this.NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(principal)));
            var authState = await GetAuthenticationStateAsync();

            return(SignInResult.Success);
        }
        private static void AddRolesToPrincipal(ClaimsPrincipal principal, string[] roles)
        {
            var identity = principal.Identity as ClaimsIdentity;

            var alreadyHasRolesClaim = identity.Claims.Any(c => c.Type == "role");

            if (!alreadyHasRolesClaim && roles.Any())
            {
                identity.AddClaims(roles.Select(r => new Claim("role", r)));
            }

            var newPrincipal = new System.Security.Claims.ClaimsPrincipal(identity);
        }
Example #57
0
        private void SetClaimsIdentity(string userName)
        {
            var claims = new System.Security.Claims.Claim[]
            {
                new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier, userName)
            };

            ClaimsIdentity  id = new System.Security.Claims.ClaimsIdentity(claims, "Forms");
            ClaimsPrincipal cp = new System.Security.Claims.ClaimsPrincipal(id);

            SessionSecurityToken token = new SessionSecurityToken(cp);

            FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(token);
        }
Example #58
0
        protected override Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            Task <AuthenticateResult> rtnTask = Task <AuthenticateResult> .Factory.StartNew(() =>
            {
                NoAuthIdentity noauthIdentity                = new NoAuthIdentity();
                System.Security.Claims.ClaimsIdentity ci     = new System.Security.Claims.ClaimsIdentity();
                System.Security.Principal.GenericIdentity gi = new System.Security.Principal.GenericIdentity("NoUser");
                System.Security.Claims.ClaimsPrincipal p     = new System.Security.Claims.ClaimsPrincipal(noauthIdentity);
                AuthenticationTicket ticket = new AuthenticationTicket(p, "NoAuthScheme");
                return(AuthenticateResult.Success(ticket));
            });

            return(rtnTask);
        }
Example #59
0
        public ActionResult <DataResult <SubscribeResponse> > Subscribe([FromBody] SubscribeRequest subscribeReq)
        {
            var response = new DataResult <SubscribeResponse>(null)
            {
                Code = ResponseCode.BadRequest, Message = "unsuccessful"
            };

            if (ModelState.IsValid)
            {
                System.Security.Claims.ClaimsPrincipal currentUser = this.User;
                var userId = currentUser.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier)
                             .Select(c => c.Value).SingleOrDefault();

                #region checkSubscriptionExist
                var currentUserSubscription = _userSubscriptionDataRepo.GetBy(x => x.BookId == subscribeReq.BookId && x.UserId == userId)?.FirstOrDefault();
                if (currentUserSubscription != null)
                {
                    response.Code    = ResponseCode.OK;
                    response.Message = "subscription has already exsist";
                    response.Result  = new SubscribeResponse {
                        UserSubscriptionId = currentUserSubscription.Id
                    };
                    return(response);
                }
                #endregion

                #region InsertSubscription

                var newUserSubscription = new UserSubscription
                {
                    BookId   = subscribeReq.BookId,
                    UserId   = userId,
                    IsActive = true
                };

                var result = _userSubscriptionDataRepo.Insert(newUserSubscription);
                if (result.Code == ResponseCode.OK)
                {
                    response.Code    = ResponseCode.OK;
                    response.Message = "subscription was created";
                    response.Result  = new SubscribeResponse {
                        UserSubscriptionId = newUserSubscription.Id
                    };
                }

                #endregion
            }

            return(response);
        }
Example #60
0
        protected Task <IPrincipal> AuthenticateJwtToken(string token)
        {
            List <System.Security.Claims.Claim> userClaims;

            if (ValidateToken(token, out userClaims))
            {
                var        identity = new System.Security.Claims.ClaimsIdentity(userClaims, "Jwt");
                IPrincipal user     = new System.Security.Claims.ClaimsPrincipal(identity);

                return(Task.FromResult(user));
            }

            return(Task.FromResult <IPrincipal>(null));
        }