Inheritance: System.Security.Principal.IIdentity
コード例 #1
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
            var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
            var userManager = Startup.UserManagerFactory();
            var user = await userManager.FindAsync(context.UserName, context.Password);
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            identity.AddClaim(new Claim("id", user.StaffId.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            var listOfRoles = await userManager.GetRolesAsync(user.Id);
            if (listOfRoles.Contains("admin"))
            {
                identity.AddClaim(new Claim("role", "admin"));
            }
            else
            {
                identity.AddClaim(new Claim("role", "user"));
            }
            context.Validated(identity);


            var ctx = HttpContext.Current.GetOwinContext();
            var authManager = ctx.Authentication;
            authManager.SignIn(identity);
        }
コード例 #2
0
ファイル: AccountController.cs プロジェクト: jerlinjames/repo
 public ActionResult Authorize()
 {
     var claims = new ClaimsPrincipal(User).Claims.ToArray();
     var identity = new ClaimsIdentity(claims, "Bearer");
     AuthenticationManager.SignIn(identity);
     return new EmptyResult();
 }
コード例 #3
0
        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var cert = request.GetClientCertificate();
            if (cert == null) return await base.SendAsync(request, cancellationToken);
            try
            {
                _validator.Validate(cert);
            }
            catch (SecurityTokenValidationException)
            {
                return new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }
            var issuer = _issuerMapper(cert);
            if (issuer == null)
            {
                return new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }

            var claims = ExtractClaims(cert, issuer);
            var identity = new ClaimsIdentity(new ClaimsIdentity(claims, X509AuthnMethod));
            AddIdentityToCurrentPrincipal(identity, request);

            return await base.SendAsync(request, cancellationToken);
        }
        private void ValidateResponseAndSignIn(TokenResponse response)
        {
            if (!string.IsNullOrWhiteSpace(response.IdentityToken))
            {
                var tokenClaims = ValidateToken(response.IdentityToken);
                var claims = new List<Claim>(from c in tokenClaims
                                             where c.Type != "iss" &&
                                                   c.Type != "aud" &&
                                                   c.Type != "nbf" &&
                                                   c.Type != "exp" &&
                                                   c.Type != "iat" &&
                                                   c.Type != "amr" &&
                                                   c.Type != "idp"
                                             select c);


                if (!string.IsNullOrWhiteSpace(response.AccessToken))
                {
                    claims.Add(new Claim("access_token", response.AccessToken));
                    claims.Add(new Claim("expires_at", (DateTime.UtcNow.ToEpochTime() + response.ExpiresIn).ToDateTimeFromEpoch().ToString()));
                }

                if (!string.IsNullOrWhiteSpace(response.RefreshToken))
                {
                    claims.Add(new Claim("refresh_token", response.RefreshToken));
                }

                var id = new ClaimsIdentity(claims, "Cookies");
                Request.GetOwinContext().Authentication.SignIn(id);
            }
        }
コード例 #5
0
        public async static Task<IEnumerable<Claim>> GetClaims(ClaimsIdentity user)
        {
            List<Claim> claims = new List<Claim>();
            using (edisDbEntities db = new edisDbEntities())
            {
                if (user.HasClaim(c => c.Type == ClaimTypes.Role && c.Value == AuthorizationRoles.Role_Client))
                {

                    var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                    var userProfile = await userManager.FindByNameAsync(user.Name);

                    var client = db.Clients.FirstOrDefault(c => c.ClientUserID == userProfile.Id);
                    if (client != null)
                    {
                        var clientGroup = db.ClientGroups.FirstOrDefault(c => c.ClientGroupID == client.ClientGroupID);
                        if (clientGroup != null && clientGroup.MainClientID == client.ClientUserID)
                        {
                            claims.Add(CreateClaim(ClaimType_ClientGroupLeader, ClaimValue_ClientGroupLeader_Leader));
                        }
                        else
                        {
                            claims.Add(CreateClaim(ClaimType_ClientGroupLeader, ClaimValue_ClientGroupLeader_Member));
                        }
                    }
                }
            }
            return claims;
        }
コード例 #6
0
        private string IssueJwtToken(System.IdentityModel.Tokens.Jwt.JwtSecurityToken aadToken)
        {
            var msKey = GetTokenSignKey();

            var msSigningCredentials = new Microsoft.IdentityModel.Tokens
                                       .SigningCredentials(msKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            var claimsIdentity = new System.Security.Claims.ClaimsIdentity(new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, "*****@*****.**"),
                new Claim(ClaimTypes.Role, "admin"),
            }, "MassRover.Authentication");

            var msSecurityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
            {
                Audience           = "massrover.client",
                Issuer             = "massrover.authservice",
                Subject            = claimsIdentity,
                Expires            = DateTime.UtcNow.AddHours(8),
                SigningCredentials = msSigningCredentials
            };

            var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            var plainToken = tokenHandler.CreateToken(msSecurityTokenDescriptor);

            var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);

            return(signedAndEncodedToken);
        }
コード例 #7
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new OAuthAuthorizationServerProvider
                {
                    OnValidateClientAuthentication = async c=>c.Validated(),
                    OnGrantResourceOwnerCredentials = async c =>
                    {
                        using (var repo = new AuthRepository())
                        {
                            var user = await repo.FindUser(c.UserName, c.Password);
                            if (user == null)
                            {
                                c.Rejected();
                                throw new ApiException("User not existed or wrong password.");
                            }
                        }
                        var identity = new ClaimsIdentity(c.Options.AuthenticationType);
                        identity.AddClaims(new[] {new Claim(ClaimTypes.Name, c.UserName), new Claim(ClaimTypes.Role, "user")});
                        if (string.Equals(c.UserName, AppConfig.Manager, StringComparison.InvariantCultureIgnoreCase))
                            identity.AddClaims(new[] {new Claim(ClaimTypes.Name, c.UserName), new Claim(ClaimTypes.Role, "manager")});
                        c.Validated(identity);
                    }
                },
            });
        }
コード例 #8
0
        /// <summary>
        /// Returns a ClaimsPrincipal object with the NameIdentifier and Name claims, if the request can be
        /// successfully authenticated based on query string parameter bewit or HTTP Authorization header (hawk scheme).
        /// </summary>
        public async Task<ClaimsPrincipal> AuthenticateAsync()
        {
            string bewit;
            bool isBewit = Bewit.TryGetBewit(this.request, out bewit);

            var authentication = isBewit ?
                                        Bewit.AuthenticateAsync(bewit, now, request, credentialsFunc) :
                                            HawkSchemeHeader.AuthenticateAsync(now, request, credentialsFunc);

            this.result = await authentication;

            if (result.IsAuthentic)
            {
                // At this point, authentication is successful but make sure the request parts match what is in the
                // application specific data 'ext' parameter by invoking the callback passing in the request object and 'ext'.
                // The application specific data is considered verified, if the callback is not set or it returns true.
                bool isAppSpecificDataVerified = this.verificationCallback == null ||
                                                    this.verificationCallback(request, result.ApplicationSpecificData);
                
                if (isAppSpecificDataVerified)
                {
                    // Set the flag so that Server-Authorization header is not sent for bewit requests.
                    this.isBewitRequest = isBewit;

                    var idClaim = new Claim(ClaimTypes.NameIdentifier, result.Credential.Id);
                    var nameClaim = new Claim(ClaimTypes.Name, result.Credential.User);
                    
                    var identity = new ClaimsIdentity(new[] { idClaim, nameClaim }, HawkConstants.Scheme);

                    return new ClaimsPrincipal(identity);
                }
            }
            
            return null;
        }
コード例 #9
0
        public string Authenticate(string Email, string Password)
        {
            AuthenticateService service = new AuthenticateService(_container);

            if (!string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Password))
            {
                var user = service.Authenticate(Email, Password);
                if (user != null)
                {
                    var authentication = Request.GetOwinContext().Authentication;
                    var identity = new ClaimsIdentity("Bearer");
                    identity.AddClaim(new Claim("name", user.Name));
                    identity.AddClaim(new Claim("email", user.Email));
                    identity.AddClaim(new Claim("userid", user.Id.ToString()));
                    identity.AddClaim(new Claim("usertype", user.UserType.ToString()));
                    identity.AddClaim(new Claim("companyid", user.Company.Id.ToString()));
                    identity.AddClaim(new Claim("companyname", user.Company.Name));

                    AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc = currentUtc;
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
                    var token = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);

                    authentication.SignIn(identity);

                    return token;
                }
            }

            return "false";
        }
コード例 #10
0
        public override async System.Threading.Tasks.Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            if(context.GrantType.ToLower() == "facebook")
            {
                var fbClient = new FacebookClient(context.Parameters.Get("accesstoken"));
                dynamic mainDataResponse = await fbClient.GetTaskAsync("me", new { fields = "first_name, last_name, picture" });
                dynamic friendListResponse = await fbClient.GetTaskAsync("me/friends");
                var friendsResult = (IDictionary<string, object>)friendListResponse;
                var friendsData = (IEnumerable<object>)friendsResult["data"];
                var friendsIdList = new List<string>();
                foreach (var item in friendsData)
                {
                    var friend = (IDictionary<string, object>)item;
                    friendsIdList.Add((string)friend["id"]);
                }
                User user = await CreateOrUpdateUser(mainDataResponse.id, mainDataResponse.first_name, mainDataResponse.last_name, mainDataResponse.picture.data.url, friendsIdList);
                
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(_fbIdKey, mainDataResponse.id));
                identity.AddClaim(new Claim(_idKey, user.Id.ToString()));

                await base.GrantCustomExtension(context);
                context.Validated(identity);
            }
            return;
        }
コード例 #11
0
        public ActionResult Login(LoginViewModel model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.account)) { throw new ArgumentNullException("account"); }
                if (string.IsNullOrEmpty(model.password)) { throw new ArgumentNullException("password"); }
                //声明
                Claim[] claims =
                {
                new Claim(ClaimTypes.Name,model.account),
                new Claim(ClaimTypes.NameIdentifier,model.account),
                new Claim(ClaimTypes.Role,"normal"),
                };

                //注意: DefaultAuthenticationTypes.ApplicationCookie否则会导致Cookie无法写入
                System.Security.Claims.ClaimsIdentity claimsIdentity = new System.Security.Claims.ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties()
                {
                    RedirectUri = "http://www.baidu.com/",
                    IsPersistent = true

                }, claimsIdentity);

                return Redirect("/home/");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex);
            }
            return View(model);
        }
コード例 #12
0
        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);
        }
コード例 #13
0
 /// <summary>
 ///  验证用户名与密码 [Resource Owner Password Credentials Grant[username与password]|grant_type=password&username=irving&password=654321]
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
     //validate user credentials (验证用户名与密码)  should be stored securely (salted, hashed, iterated) 
     var userValid = await _accountService.ValidateUserNameAuthorizationPwdAsync(context.UserName, context.Password);
     if (!userValid)
     {
         //context.Rejected();
         context.SetError(AbpConstants.AccessDenied, AbpConstants.AccessDeniedErrorDescription);
         return;
     }
     var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
     claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     var ticket = new AuthenticationTicket(claimsIdentity, new AuthenticationProperties());
     context.Validated(ticket);
     /*
     //create identity
     var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
     claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     claimsIdentity.AddClaim(new Claim("sub", context.UserName));
     claimsIdentity.AddClaim(new Claim("role", "user"));
     // create metadata to pass on to refresh token provider
     var props = new AuthenticationProperties(new Dictionary<string, string>
                     {
                         {"as:client_id", context.ClientId }
                     });
     var ticket = new AuthenticationTicket(claimsIdentity, props);
     context.Validated(ticket);
     */
 }
コード例 #14
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (var projectContext = new ProjectContext())
            {
                using (var unitOfWork = new UnitOfWork(projectContext))
                {
                    IdentityUser user = await unitOfWork.Users.FindUser(context.UserName, context.Password);

                    if (user == null)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }
                }
            }


            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
コード例 #15
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            // Dummy check here, you need to do your DB checks against membership system http://bit.ly/SPAAuthCode
            if (context.UserName != context.Password)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                //return;
                return Task.FromResult<object>(null);
            }

            var identity = new ClaimsIdentity("JWT");

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Manager"));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));

            var props =
                new AuthenticationProperties(
                    new Dictionary<string, string>
                        {
                            {
                                "audience",
                                context.ClientId ?? string.Empty
                            }
                        });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
            return Task.FromResult<object>(null);
        }
コード例 #16
0
        /// <summary>
        /// Verifies role against user's groups in Azure AD
        /// </summary>
        /// <param name="role"></param>
        /// <param name="claimsIdentity"></param>
        /// <returns></returns>
        public static async Task <bool> CheckInRole(string role, System.Security.Claims.ClaimsIdentity claimsIdentity)
        {
            ObjectCache cache = MemoryCache.Default;

            try
            {
                if (HttpContext.Current.Request.IsAuthenticated)
                {
                    //use LazyCache to cache the groups
                    var cacheKey = GetCacheKey(claimsIdentity);
                    var groups   = cache.AddOrGetExisting(cacheKey, await UserInfoHelper.GetAllGroups(claimsIdentity), _CacheItemPolicy) as List <string>;

                    //locate AD group tied to role
                    if (groups.Count > 0)
                    {
                        return(groups.Contains(ConfigurationManager.AppSettings[role]));
                    }
                }
            }
            catch (Exception)
            {
                //TODO: Handle exception
            }

            return(false);
        }
コード例 #17
0
        public async Task<ActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var blogContext = new BlogContext();
            var user = await blogContext.Users.Find(x => x.Email == model.Email).SingleOrDefaultAsync();
            if (user == null)
            {
                ModelState.AddModelError("Email", "Email address has not been registered.");
                return View(model);
            }

            var identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Name, user.Name),
                    new Claim(ClaimTypes.Email, user.Email)
                }, "ApplicationCookie");

            var context = Request.GetOwinContext();
            var authManager = context.Authentication;

            authManager.SignIn(identity);

            return Redirect(GetRedirectUrl(model.ReturnUrl));
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var  allowedOrigin = "*";
            ApplicationUser appUser = null;

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            using (AuthRepository _repo = new AuthRepository())
            {
                 appUser = await _repo.FindUser(context.UserName, context.Password);

                if (appUser == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
            identity.AddClaim(new Claim("PSK", appUser.PSK));

            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    { 
                        "userName", context.UserName
                    }
                });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }
コード例 #19
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var repo = new AuthRepository())
            {
                var user = await repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim("id", user.Id));
                
                var isAdmin = repo.HasRole(user, "Administrator");
                identity.AddClaim(new Claim("is_admin", isAdmin.ToString()));

                identity.AddClaim(isAdmin
                    ? new Claim(ClaimTypes.Role, "Administrator")
                    : new Claim(ClaimTypes.Role, "DashboardUser"));


                context.Validated(identity);
            }
        }
コード例 #20
0
ファイル: ApplicationUser.cs プロジェクト: Tmaturano/PetSuite
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, ClaimsIdentity ext = null)
        {
            // Observe que o authenticationType precisa ser o mesmo que foi definido em CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            var claims = new List<Claim>();

            if (!string.IsNullOrEmpty(CurrentClientId))
            {
                claims.Add(new Claim("AspNet.Identity.ClientId", CurrentClientId));
            }

            //  Adicione novos Claims aqui //

            // Adicionando Claims externos capturados no login, que o facebook, twitter, etc enviam para essa aplicação.
            //No momento que o usuário loga, coneguimos pegar mais informações para cadastrar no Bd local.
            if (ext != null)
            {
                await SetExternalProperties(userIdentity, ext); 
            }

            // Gerenciamento de Claims para informaçoes do usuario
            //claims.Add(new Claim("AdmRoles", "True"));

            userIdentity.AddClaims(claims);

            return userIdentity;
        }
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var data = new Data();
            var users = data.users();

            if (users.Any(p => p.user == model.UserName && p.password == model.Password))
            {
                var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName),}, DefaultAuthenticationTypes.ApplicationCookie);

                Authentication.SignIn(new AuthenticationProperties
                {
                    IsPersistent = model.RememberMe
                }, identity);
                
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
            }
        }
コード例 #22
0
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
     try
     {
         using (var userManager = new UserManager<User>(new UserStore<User>(new ElearningDbContext())))
         {
             var user = await userManager.FindAsync(context.UserName, context.Password);
             if (user == null)
             {
                 context.SetError("invaild_grant", "The user name or password is incorrect");
                 return;
             }
         }
     }
     catch (Exception ex)
     {
         var a = ex;
         throw;
     }
     var identity = new ClaimsIdentity("JWT");
     identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     identity.AddClaim(new Claim("sub", context.UserName));
     identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
     var properties = new AuthenticationProperties(new Dictionary<string, string>
     {
         {
             "audience", context.ClientId ?? string.Empty
         }
     });
     var ticket = new AuthenticationTicket(identity, properties);
     context.Validated(ticket);
 }
コード例 #23
0
        public async Task <IActionResult> VerifyLoginToken([FromBody] VerifyLoginTokenModel model)
        {
            var result = await _db.VerifyLoginToken(model.TokenID, model.Token);

            if (result.Success)
            {
                var identity = new System.Security.Claims.ClaimsIdentity("LoginToken");

                identity.AddClaim(new Claim(ClaimTypes.Name, result.PersonID));
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, result.PersonID));
                identity.AddClaim(new Claim(ClaimTypes.Email, result.EmailAddress));

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

                await this.HttpContext.Authentication.SignInAsync(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme, principal, new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties()
                {
                    IsPersistent = false,
                    AllowRefresh = true,
                    IssuedUtc    = DateTimeOffset.Now,
                    ExpiresUtc   = DateTimeOffset.Now.AddMinutes(90)
                });

                return(this.Ok(new
                {
                    PersonID = result.PersonID,
                    EmailAddress = result.EmailAddress
                }));
            }

            return(this.BadRequest());
        }
コード例 #24
0
ファイル: CustomOAuthProvider.cs プロジェクト: jilnesta/ChatR
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var user = await _userAccountManager.Authenticate(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.Name),
                new Claim(ClaimTypes.Name, user.Email),
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", user.Email),
                new Claim("urn:Custom:UserType", "AnonymousUser")
            };

            System.Security.Claims.ClaimsIdentity oAuthIdentity = new System.Security.Claims.ClaimsIdentity(claims, "JWT"); // await user.GenerateUserIdentityAsync(userManager, "JWT");

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);
        }
コード例 #25
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Try get the useraccount by provided username
            var userAccount = _uow.UserAccountRepository.Get(context.UserName);

            // If the useraccount was not found, reject the token request
            if (userAccount == null)
            {
                context.Rejected();
                return;
            }

            // If password is invalid, reject the token request
            if (!PasswordHelper.Verify(userAccount.Password, userAccount.Salt, context.Password))
            {
                context.Rejected();
                return;
            }

            // Create identity which will be included in the token
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            // All claims added here will be written to the token. Thus claims should
            // be added with moderation
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "administrator"));
            
            // Validate the reqeust and return a token 
            context.Validated(identity);
        }
コード例 #26
0
        internal static IEnumerable<string> GetUniqueIdentifierParameters(ClaimsIdentity claimsIdentity)
        {
            var nameIdentifierClaim = claimsIdentity.FindFirst(claim =>
                                                            String.Equals(ClaimTypes.NameIdentifier,
                                                                        claim.Type, StringComparison.Ordinal));
            if (nameIdentifierClaim != null && !string.IsNullOrEmpty(nameIdentifierClaim.Value))
            {
                return new string[]
                {
                    ClaimTypes.NameIdentifier,
                    nameIdentifierClaim.Value
                };
            }

            // We Do not understand this claimsIdentity, fallback on serializing the entire claims Identity.
            var claims = claimsIdentity.Claims.ToList();
            claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal));
            var identifierParameters = new List<string>();
            foreach (var claim in claims)
            {
                identifierParameters.Add(claim.Type);
                identifierParameters.Add(claim.Value);
            }

            return identifierParameters;
        }
コード例 #27
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var user = userRepository.Get(w => w.UserName == context.UserName && w.Password == context.Password);
            
            //var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            ClaimsIdentity cookiesIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            if (user.Roles.Count() > 0)
            {
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, user.Roles.FirstOrDefault().Name));
            }

            //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
            //   OAuthDefaults.AuthenticationType);
            //ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
            //    CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
コード例 #28
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            List<string> roles = new List<string>();
            IdentityUser user = new IdentityUser();

            using (AuthRepository _repo = new AuthRepository())
            {
                user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "Потребителското име или паролата не са верни.");
                    return;
                }
                else
                {
                    roles = await _repo.GetRolesForUser(user.Id);
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            foreach (var item in roles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, item));
            }

            context.Validated(identity);
            context.Response.Headers.Add("UserRoles", roles.ToArray());
        }
コード例 #29
0
ファイル: SecurityService.cs プロジェクト: jechtom/DevUpdater
        public ClaimsIdentity ProcessClientCertificate(X509Certificate2 cert, string ipAddress)
        {
            using (var per = PersistenceFactory())
            {
                var hash = cert.GetCertHash();
                var client = per.ClientGetByCertificateHash(hash);

                // not found? add to pending certificates list
                if (client == null)
                {
                    TraceSource.TraceInformation("Pending certificate:\n{0} ({1})", ByteArrayHelper.ByteArrayToString(hash), ipAddress);
                    per.PendingCertificateAddOrUpdate(hash, ipAddress);
                    per.Save();
                }

                // build identity
                var identity = new ClaimsIdentity("ClientAuthentication");
                identity.AddClaim(new Claim(CertificateHashClaimType, ByteArrayHelper.ByteArrayToString(hash), ClaimValueTypes.HexBinary, ClaimIssuer));
                identity.AddClaim(new Claim(IsKnownClaimType, client == null ? "false" : "true", ClaimValueTypes.Boolean, ClaimIssuer)); // known client?

                // add details only if authenticated
                if (client != null)
                {
                    identity.AddClaim(new Claim(identity.NameClaimType, client.Name, ClaimValueTypes.String, ClaimIssuer)); // nick name
                    identity.AddClaim(new Claim(ClientIdClaimType, client.Id.ToString(), ClaimValueTypes.Integer, ClaimIssuer)); // ID
                    identity.AddClaims(client.ClientGroups.Select(group => new Claim(identity.RoleClaimType, group.Id.ToString(), ClaimValueTypes.Integer, ClaimIssuer))); // assigned groups
                    identity.AddClaims(client.ClientGroups.Select(group => new Claim(RoleNameClaimType, group.Name, ClaimValueTypes.String, ClaimIssuer))); // assigned groups (names - informative)
                }

                return identity;
            }
        }
コード例 #30
0
ファイル: AccountController.cs プロジェクト: danixeee/ISA
        public ActionResult Login(LoginFormViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }


            User user = userService.GetByLogin(model.Email, model.Password);
            if (user != null)
            {
                var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Role, user.Role.Naziv) }, "ApplicationCookie");
                var ctx = Request.GetOwinContext();
                var authManager = ctx.Authentication;

                authManager.SignOut("ApplicationCookie");
                Session.Clear();

                authManager.SignIn(identity);

                Session.Add(Constants.User,user);
                return RedirectToAction("Index", "Home");
            }

            ModelState.AddModelError("", "Greska");
            return View();
        }
コード例 #31
0
        public ActionResult LoginIndex(LoginModel log, string ReturnURL = "")
        {
            if (!ModelState.IsValid)
            {
                return(View(log));
            }

            var user = BOSSDB.Accounts.Where(a => a.Username == log.username && a.IsLock == false).FirstOrDefault();

            if (user != null)
            {
                var validate = PasswordHash.PasswordHash.ValidatePassword(log.password, user.Password);
                if (validate == true)
                {
                    var identity = new System.Security.Claims.ClaimsIdentity(new[] { new Claim(ClaimTypes.Authentication, user.AccountID.ToString()) }, DefaultAuthenticationTypes.ApplicationCookie);

                    Authentication.SignIn(new AuthenticationProperties(), identity);

                    var ActionName     = "Index";
                    var ControllerName = "Home";
                    return(RedirectToAction(ActionName, ControllerName));
                }
                else
                {
                    return(View());
                }
            }
            else
            {
                return(View());
            }
        }
コード例 #32
0
        public virtual async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<IdentityUser> manager, ClaimsIdentity ext = null)
        {
            // Observe que o authenticationType precisa ser o mesmo que foi definido em CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            var claims = new List<Claim>();

            if (!string.IsNullOrEmpty(CurrentClientId))
            {
                claims.Add(new Claim("AspNet.Identity.ClientId", CurrentClientId));
            }

            //  Adicione novos Claims aqui //

            // Adicionando Claims externos capturados no login
            if (ext != null)
            {
                await SetExternalProperties(userIdentity, ext);
            }

            // Gerenciamento de Claims para informaçoes do usuario
            //claims.Add(new Claim("AdmRoles", "True"));

            userIdentity.AddClaims(claims);

            return userIdentity;
        }
コード例 #33
0
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);

            if (Request.Cookies["lang"] == null)
            {
                var value = Request.Cookies["lang"].Value;
                Thread.CurrentThread.CurrentCulture   = new CultureInfo(value);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(value);
            }

            if (Request.Cookies["access_token"] != null)
            {
                var value = Request.Cookies["access_token"].Value;
                if (!string.IsNullOrEmpty(value))
                {
                    var            jwtToken     = new JwtSecurityToken(value);
                    var            claims       = jwtToken.Claims;
                    ClaimsIdentity claim        = new ClaimsIdentity(claims);
                    var            cp           = new ClaimsPrincipal(claim);
                    var            transformer  = new ClaimsAuthenticationManager();
                    var            newPrincipal = transformer.Authenticate(string.Empty, cp);
                    Thread.CurrentPrincipal = newPrincipal;
                    HttpContext.User        = newPrincipal;
                }
            }
        }
コード例 #34
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (model.UserName != model.Password) return View();

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, model.UserName),
                new Claim(ClaimTypes.Email, "*****@*****.**"),
                new Claim(ClaimTypes.Role, "Administrator"),
                new Claim("Data", "Read"),
            };

            var id = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);
            var authenticationManager = Request.GetOwinContext().Authentication;

            var authProperties = new AuthenticationProperties { IsPersistent = true };

            authenticationManager.SignIn(authProperties, id);

            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }

            return RedirectToAction("Index", "Home");
        }
コード例 #35
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (AuthRepository _repo = new AuthRepository())
            {
                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));

                var roles = await _repo.FindUserRoles(user.Id);

                foreach (var r in roles)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, r));
                }
                //identity.AddClaim(new Claim("sub", context.UserName));
                
                context.Validated(identity);
            }
        }
コード例 #36
0
ファイル: Claim.cs プロジェクト: er0dr1guez/corefx
        /// <summary>
        /// Initializes an instance of <see cref="Claim"/> using a <see cref="BinaryReader"/>.
        /// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>.
        /// </summary>
        /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="Claim"/>.</param>
        /// <param name="subject"> the value for <see cref="Claim.Subject"/>, which is the <see cref="ClaimsIdentity"/> that has these claims.</param>
        /// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
        public Claim(BinaryReader reader, ClaimsIdentity subject)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            Initialize(reader, subject);
        }
コード例 #37
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Allow CORS on the token middleware provider
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            //TODO
            // Usually this would be done via dependency injection
            // But I haven't got it to work with the OWIN startup class yet
            AppDBContext _ctx = new AppDBContext();
            UserRepository _repo = new UserRepository(_ctx);

                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
コード例 #38
0
ファイル: Common.cs プロジェクト: hw-infotech/hwwebapp
        public static T GetClaimsValue <T>(this System.Security.Claims.ClaimsIdentity claimsIdentity, string claimType)
        {
            Type underlyingType = typeof(T);
            var  value          = claimsIdentity.Claims.Where(c => c.Type == claimType)
                                  .Select(c => Convert.ChangeType(c.Value, underlyingType)).SingleOrDefault();
            var objType = value.GetType();

            return((T)value);
        }
コード例 #39
0
        public ActionResult About()
        {
            System.Security.Claims.ClaimsIdentity claimsIdentity = System.Web.HttpContext.Current.User.Identity as System.Security.Claims.ClaimsIdentity;
            foreach (Claim claim in claimsIdentity.Claims)
            {
                ViewBag.Message = ViewBag.Message + claim.Type + ":" + claim.Value;
            }
            // ViewBag.Message = "Your app description page.";

            return(View());
        }
コード例 #40
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var svc    = context.OwinContext.Environment.GetUserAccountService <UserAccount>();
            var user   = svc.GetByUsername("users", context.UserName);
            var claims = user.GetAllClaims();

            var id = new System.Security.Claims.ClaimsIdentity(claims, "MembershipReboot");

            context.Validated(id);

            return(base.GrantResourceOwnerCredentials(context));
        }
コード例 #41
0
        private void SignIn(Nalozi account)
        {
            try
            {
                ApplicationUser user = new ApplicationUser();
                user.nalogId = account.Id;
                user.Email   = account.Email;

                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

                List <Claim> claims = new List <Claim>();

                Claim nalogId = new Claim("nalogId", user.nalogId.ToString());
                claims.Add(nalogId);

                Claim schemaUsername = new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", user.Email);
                claims.Add(schemaUsername);

                Claim schemaUserId = new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", user.nalogId.ToString());
                claims.Add(schemaUserId);

                Claim schemaApp = new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Plivacki Centar NERETVA");
                claims.Add(schemaApp);

                ClaimsIdentity identity = new System.Security.Claims.ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
                AuthenticationManager.SignIn(identity);

                Session["current-account-name"] = account.Ime + " " + account.Prezime;

                if (account.IsAdministrator)
                {
                    Session["current-account-role"] = "admin";
                }
                else if (account.IsPlivac)
                {
                    Session["current-account-role"] = "plivac";
                }
                else if (account.IsRekreativac)
                {
                    Session["current-account-role"] = "rekreativac";
                }
                else if (account.IsTrener)
                {
                    Session["current-account-role"] = "trener";
                }
            }
            catch (Exception)
            {
                RedirectToAction("LogOff", "guest");
            }
        }
コード例 #42
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));
        }
コード例 #43
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);
        }
コード例 #44
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);
        }
コード例 #45
0
        private void SignIn(User user)
        {
            List <Claim> claims = new List <Claim> {
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", user.Username),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", user.Id.ToString()),
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Surveys")
            };
            ClaimsIdentity identity = new System.Security.Claims.ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

            HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties()
            {
                IsPersistent = true
            }, identity);
        }
コード例 #46
0
        private static System.Security.Claims.ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context, IdentityUser user)
        {
            var identity = new System.Security.Claims.ClaimsIdentity();

            identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, context.UserName));
            identity.AddClaim(new System.Security.Claims.Claim("sub", context.UserName));

            var userRoles = context.OwinContext.Get <BookUserManager>().GetRoles(user.Id);

            foreach (var role in userRoles)
            {
                identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, role));
            }
            return(identity);
        }
コード例 #47
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var identity = new System.Security.Claims.ClaimsIdentity(context.Options.AuthenticationType);

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (var db = new TestModel())
            {
                if (db != null)
                {
                    IQueryable <USER_MASTER> rtn = from temp in db.USER_MASTER select temp;
                    var user = rtn.ToList();
                    //var empl = db.Employees.ToList();
                    //var user = db.USER_MASTER;
                    if (user != null)
                    {
                        if (!string.IsNullOrEmpty(user.Where(u => u.Email == context.UserName && u.Password == context.Password).FirstOrDefault().Email))
                        {
                            identity.AddClaim(new Claim("Age", "16"));

                            var props = new AuthenticationProperties(new Dictionary <string, string>
                            {
                                {
                                    "userdisplayname", context.UserName
                                },
                                {
                                    "role", "admin"
                                }
                            });

                            var ticket = new AuthenticationTicket(identity, props);
                            context.Validated(ticket);
                        }
                        else
                        {
                            context.SetError("invalid_grant", "Provided username and password is incorrect");
                            context.Rejected();
                        }
                    }
                }
                else
                {
                    context.SetError("invalid_grant", "Provided username and password is incorrect");
                    context.Rejected();
                }
                return;
            }
        }
コード例 #48
0
        public ActionResult ClientInfo()
        {
            ClientInfoViewModel model = new ClientInfoViewModel();

            StringBuilder msg = new StringBuilder();

            try
            {
                if (!Request.IsAuthenticated)
                {
                    msg.AppendLine("Request not authenticated");
                }
                var user            = this.User;
                var claimsPrincipal = user as SSC.ClaimsPrincipal;
                if (claimsPrincipal != null)
                {
                    SSC.ClaimsIdentity claimsIdentity = claimsPrincipal.Identity as SSC.ClaimsIdentity;
                    if (claimsIdentity != null)
                    {
                        int claimNum = 1;
                        foreach (SSC.Claim claim in claimsIdentity.Claims)
                        {
                            model.ClientInfo.Add(new InfoItem
                            {
                                Name  = string.Format("Claim {0}", claimNum),
                                Value = string.Format("Issuer: \"{1}\" {0}OriginalIssuer: \"{2}\" {0}Properties.Count: \"{3}\" {0}Subject: \"{4}\" {0}Type: \"{5}\" {0}ValueType: \"{6}\" {0}Value: \"{7}\" {0}",
                                                      Environment.NewLine,
                                                      claim.Issuer,
                                                      claim.OriginalIssuer,
                                                      claim.Properties.Count,
                                                      claim.Subject,
                                                      claim.Type,
                                                      claim.ValueType,
                                                      claim.Value)
                            });
                            claimNum++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportException(ex, msg);
            }
            model.Message = msg.ToString();

            return(View(model));
        }
コード例 #49
0
        /// <summary>
        /// Used to get updated claims information on the username.
        /// Can be used when an action is denyed by attempting to check if updated claim will allow the action.
        /// You may also choose a frequency to check for updated claims on the client side.
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public ClaimsIdentity GetClaimsIdentity(string userName, string sharedClientKey)
        {
            // Ensure the clients are certified.
            if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey)
            {
                return(null);
            }

            var accountUserIdentity = AccountUserManager.GetUserIdentity(userName);

            System.Security.Claims.ClaimsIdentity identity = AccountUserManager.GetUserClaimsIdentity(
                accountUserIdentity,
                DefaultAuthenticationTypes.ApplicationCookie); //<-- Uses a cookie for the local web application

            return(identity);
        }
コード例 #50
0
        public async Task <IActionResult> PcoLoginCallback(string code)
        {
            var redirectUrl = this.Url.Action("PcoLoginCallback", "Home", null, "https");

            var client = new System.Net.Http.HttpClient();

            var tokenRequest = new
            {
                grant_type    = "authorization_code",
                code          = code,
                client_id     = _pcoApp.ClientID,
                client_secret = _pcoApp.ClientSecret,
                redirect_uri  = redirectUrl
            };
            var tokenRequestJson = Newtonsoft.Json.JsonConvert.SerializeObject(tokenRequest);

            var callbackResponse = await client.PostAsync(_pcoAuthOptions.AuthTokenUrl, new StringContent(tokenRequestJson, System.Text.Encoding.UTF8, "application/json"));

            var token = await callbackResponse.Content.ReadJsonAsync <PcoAuthTokenResponse>();

            var pcoClient = new PcoApiClient.PcoApiClient(client, new PcoApiOptions()
            {
                AuthenticationMethod = "Bearer",
                Password             = token.AccessToken
            });

            var myInfo = await pcoClient.Get <PcoPeoplePerson>("people/v2/me");

            var ident = new System.Security.Claims.ClaimsIdentity("PCO");

            ident.AddClaim(new Claim(ClaimTypes.NameIdentifier, myInfo.Data.ID));
            ident.AddClaim(new Claim(ClaimTypes.Name, myInfo.Data.Attributes.Name));
            ident.AddClaim(new Claim(ClaimsExtensions.OrganizationID, myInfo.Meta.Parent.ID.ToString()));
            ident.AddClaim(new Claim(ClaimsExtensions.AccessToken, token.AccessToken));
            ident.AddClaim(new Claim(ClaimsExtensions.RefreshToken, token.RefreshToken));

            var principal = new System.Security.Claims.ClaimsPrincipal(ident);

            await this.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties()
            {
                ExpiresUtc   = DateTimeOffset.UtcNow.AddHours(1),
                AllowRefresh = true,
                IsPersistent = true
            });

            return(RedirectToAction("Index"));
        }
コード例 #51
0
        /// <summary>
        /// Get loggedon user groups that contain 'key' and display name from AD.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="claimsIdentity"></param>
        /// <returns></returns>
        public static async Task <List <string> > GetGroups(string key, System.Security.Claims.ClaimsIdentity claimsIdentity)
        {
            List <string> kgroups   = new List <string>();
            List <string> allgroups = await GetAllGroups(claimsIdentity);

            //
            kgroups.Add(allgroups[0]); //add the user DisplayName
            //
            foreach (string s in allgroups)
            {
                if (s.Contains(key))
                {
                    kgroups.Add(s);
                }
            }
            return(kgroups);
        }
コード例 #52
0
        private async void SetCookie(PersianNov.DataStructure.Author author)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, $"{author.FirstName} {author.LastName}"),
                new Claim(ClaimTypes.NameIdentifier, author.Username),
                new Claim(ClaimTypes.Email, author.Email),
                new Claim("Id", author.Id.ToString()),
                new Claim(ClaimTypes.Role, "Author"),
            };


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

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

                ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(20),
                // 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);
        }
コード例 #53
0
        /// <summary>
        /// Get all loggedon user groups and display name from AD.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="dn"></param>
        /// <returns></returns>
        public static async Task <List <string> > GetAllGroups(System.Security.Claims.ClaimsIdentity claimsIdentity)
        {
            List <string> lgroups  = new List <string>();
            ObjectCache   cache    = MemoryCache.Default;
            var           cacheKey = GetCacheKey(claimsIdentity);

            // If the claims identity is not populated, return an empty list
            if (String.IsNullOrEmpty(cacheKey))
            {
                return(lgroups);
            }

            // If the claims identity is populated and already in the cache, just return the cached list
            if (cache.Contains(cacheKey))
            {
                return(cache.Get(cacheKey) as List <string>);
            }

            // If the claims identity is populated and NOT in the cache, call the Graph API and populate the cache
            try
            {
                MSGraphClient msGraphClient = new MSGraphClient(
                    ConfigHelper.Authority,
                    new ADALTokenCache(claimsIdentity.FindFirst("oid")?.Value));

                System.Collections.Generic.IList <Group> groups = await msGraphClient.GetCurrentUserGroupsAsync();

                var groupNameList = await GetGroupNameList(groups);

                return(cache.AddOrGetExisting(cacheKey, groupNameList, _CacheItemPolicy) as List <string>);
            }
            catch (AdalException ex)
            {
                //TODO: error handling
                return(new List <string>());
            }
            catch (Exception ex)
            {
                //TODO: error handling
                return(new List <string>());
            }
        }
コード例 #54
0
        public static AuthResult GetAuth <TKey>(System.Security.Claims.ClaimsIdentity claim, IUserDevice <TKey> model)
        {
            var now = DateTime.Now;
            var jwt = new JwtSecurityToken(
                issuer: AuthOption.ISSUER,
                audience: AuthOption.AUDINECE,
                notBefore: now,
                claims: claim.Claims,
                expires: now.Add(TimeSpan.FromMinutes(AuthOption.LifeTime)),
                signingCredentials: new SigningCredentials(State.GetSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            AuthResult result = new AuthResult()
            {
                AccessToken  = encodedJwt,
                RefreshToken = ComputeSha256Hash(now.ToLongDateString() + now.ToLongTimeString() + RepositoryRule.State.State.RandomString(6)),
                AccessTime   = now,
            };

            return(result);
        }
コード例 #55
0
ファイル: Utility.cs プロジェクト: nazrulcsebd/minibanking
        public static AppClaim ParseClaim(this System.Security.Claims.ClaimsIdentity claimsIdentity)
        {
            var appClaim = new AppClaim
            {
                UserId       = claimsIdentity.GetSpecificClaim("UserId"),
                UserTypeId   = Convert.ToString(claimsIdentity.GetSpecificClaim("UserTypeId")),
                CustomerId   = claimsIdentity.GetSpecificClaim("CustomerId"),
                AccountId    = Convert.ToString(claimsIdentity.GetSpecificClaim("AccountId")),
                PersonalCode = claimsIdentity.GetSpecificClaim("PersonalCode"),
                Email        = Convert.ToString(claimsIdentity.GetSpecificClaim("Email"))
            };

            //appClaim.SubscriptionId = claimsIdentity.GetSpecificClaim("SubscriptionId");
            //if (appClaim.SubscriptionId.IsNotNullOrEmpty())
            //{
            //    appClaim.DBName = claimsIdentity.GetSpecificClaim("DBName");
            //    appClaim.DBUserId = claimsIdentity.GetSpecificClaim("DBUserId");
            //    appClaim.DBUserPassword = claimsIdentity.GetSpecificClaim("DBUserPassword");
            //}

            return(appClaim);
        }
コード例 #56
0
        private void SignInAsync(User user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            List <System.Security.Claims.Claim> claims = new List <System.Security.Claims.Claim>();

            claims.Add(new System.Security.Claims.Claim(ClaimTypes.Name, String.IsNullOrEmpty(user.Name) ? user.UserName : user.Name)); //user.Name from my database
            claims.Add(new System.Security.Claims.Claim(ClaimTypes.NameIdentifier, user.UserId));                                       //user.Id from my database
            claims.Add(new System.Security.Claims.Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "MyApplication"));
            if (!String.IsNullOrEmpty(user.FirstName))
            {
                claims.Add(new System.Security.Claims.Claim("FirstName", user.FirstName)); //user.FirstName from my database
            }
            foreach (var role in user.Roles)
            {
                claims.Add(new System.Security.Claims.Claim(ClaimTypes.Role, role));
            }

            System.Security.Claims.ClaimsIdentity identity = new System.Security.Claims.ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
            AuthenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = isPersistent
            }, identity);
        }
コード例 #57
0
        public async Task SignIn(User user)
        {
            var identity = new System.Security.Claims.ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.FirstName));
            identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
            identity.AddClaim(new Claim(ClaimTypes.Role, user.Role.ToString()));

            var principal = new ClaimsPrincipal(identity);

            var authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(60),
                IsPersistent = true,
                IssuedUtc    = DateTimeOffset.UtcNow
            };

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authProperties);

            //WebUser.SetUser(user);
        }
コード例 #58
0
        /// <summary>
        /// This static method is setup as a delegate in Startup.Auth and will be called each time a userIdentity is created
        /// </summary>
        /// <param name="userIdentity">the ClaimsIdentity created from CRM</param>
        /// <param name="manager">the user manager used to add claims in the CRM storage</param>
        public static async Task AddCustomUserClaims(System.Security.Claims.ClaimsIdentity userIdentity, UserManager <CrmIdentityUser <string>, string> manager)
        {
            // Here you can add your custom claims to the userIdentity
            // Below is an example of how to add a custom claim:

            // Check if the customClaim has been retrieved from CRM storage
            if (!userIdentity.HasClaim("MyClaimType", "MyClaimValue"))
            {
                // Add the claim to the CRM Claim storage
                System.Security.Claims.Claim customClaim = new Claim("MyClaimType", "MyClaimValue");
                IdentityResult result = await manager.AddClaimAsync(userIdentity.GetUserId(), customClaim);

                // If all goes well, add the claim to the userIdentity. Next time the user logs in
                if (result.Succeeded)
                {
                    userIdentity.AddClaim(customClaim);
                }
                else
                {
                    // Handle the error
                }
            }
        }
コード例 #59
0
 public JsonResult Escoger(int AgenciaId)
 {
     try {
         var authenticationManager = HttpContext.GetOwinContext().Authentication;
         var identity = new System.Security.Claims.ClaimsIdentity(User.Identity);
         var Claim    = identity.FindFirst(Lib.DataFilters.MustHaveAgencyParam);
         if (Claim != null)
         {
             identity.RemoveClaim(identity.FindFirst(Lib.DataFilters.MustHaveAgencyParam));
         }
         identity.AddClaim(new System.Security.Claims.Claim(Lib.DataFilters.MustHaveAgencyParam, AgenciaId.ToString()));
         authenticationManager.AuthenticationResponseGrant =
             new AuthenticationResponseGrant(
                 new ClaimsPrincipal(identity),
                 new AuthenticationProperties {
             IsPersistent = true
         }
                 );
         return(Json(new { success = true }));
     } catch (Exception ex) {
         return(Json(new { success = false, errors = ex.Message }));
     }
 }
コード例 #60
0
    public async Task <IActionResult> LoginAsync(string username, string password)
    {
        List <Claim> claims = new List <Claim>()
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.Role, "admin")
        };

        string scheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;

        ClaimsIdentity  claimIden   = new System.Security.Claims.ClaimsIdentity(claims, scheme, ClaimTypes.Name, ClaimTypes.Role);
        ClaimsPrincipal claimsPrinc = new ClaimsPrincipal(claimIden);

        Microsoft.AspNetCore.Authentication.AuthenticationProperties authProps = new Microsoft.AspNetCore.Authentication.AuthenticationProperties {
            //RedirectUri = "",
            IsPersistent = true
        };

        _log.LogWarning($"Logging In User: {username}");

        await HttpContext.SignInAsync(scheme, claimsPrinc);

        return(Json("ok"));
    }