AddClaim() 공개 메소드

Adds a single Claim to an internal list.
If Claim.Subject != this, then Claim.Clone(this) is called before the claim is added.
if 'claim' is null.
public AddClaim ( Claim claim ) : void
claim Claim the add.
리턴 void
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //Cors
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            //Validate the User
            using (var authRepository = new AuthorizationRepository())
            {
                var user = await authRepository.FindUser(context.UserName, context.Password);

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

                    return;
                }
                else
                {
                    var token = new ClaimsIdentity(context.Options.AuthenticationType);

                    token.AddClaim(new Claim("sub", context.UserName));
                    token.AddClaim(new Claim("role", "user"));

                    context.Validated(token);
                }
            }
        }
        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);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            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, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            identity.AddClaim(new Claim("sub", context.UserName));

            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                {
                    "as:client_id", context.ClientId ?? string.Empty
                },
                {
                    "userName", context.UserName
                }
            });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }
        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);
        }
예제 #5
0
        public bool Validate(string userName, string password, out ClaimsIdentity oAuthIdentity, out ClaimsIdentity cookiesIdentity)
        {
            using (var ctx = new PrincipalContext(ContextType.Domain, DomainName))
            {
                bool isValid = ctx.ValidateCredentials(userName, password);
                if (isValid)
                {
                    oAuthIdentity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
                    cookiesIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationType);
                    var groups=GetUserGroups(userName);
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, userName));
                    cookiesIdentity.AddClaim(new Claim(ClaimTypes.Name, userName));

                    if (groups.Contains("BD"))
                    {
                        oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "BD"));
                        cookiesIdentity.AddClaim(new Claim(ClaimTypes.Role, "BD"));
                    }
                    else
                    {
                        oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, string.Join(",", groups)));
                        cookiesIdentity.AddClaim(new Claim(ClaimTypes.Role, string.Join(",", groups)));
                    }

                }
                else
                {
                    oAuthIdentity = null;
                    cookiesIdentity = null;
                }

                return isValid;
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            try
            {
                var user = _service.Authenticate(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "E-mail ou senha inválidos.");
                    return;
                }

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

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

                GenericPrincipal principal = new GenericPrincipal(identity, null);
                Thread.CurrentPrincipal = principal;

                context.Validated(identity);
            }
            catch (Exception)
            {
                context.SetError("invalid_grant", "E-mail ou senha inválidos.");
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
			string userId;
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

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

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

				userId = user.Id;
            }

			//Use this in test propose
			//using (UserManager<ApplicationUser> manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new AuctionDb())))
			//{
			//	var ident = manager.Find(context.UserName, context.Password);
			//	var userIdentity = await manager.CreateIdentityAsync(ident, "Bearer");
			//	context.Validated(userIdentity);
			//}

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
			identity.AddClaim(new Claim("userIdString", userId));
			identity.AddClaim(new Claim("sub", context.UserName));
			identity.AddClaim(new Claim("role", "user"));
            context.Validated(identity);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

                Usuario user = _usuarioAppService.Get(el => el.Login == context.UserName && el.Senha == context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "Usuário ou Senha inválidos.");
                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, user.NomeUsuario));

                var roles = new List<string>();
                roles.Add("User");

                foreach (var item in roles)
                    identity.AddClaim(new Claim(ClaimTypes.Role, item));

                GenericPrincipal principal = new GenericPrincipal(identity, roles.ToArray());
                Thread.CurrentPrincipal = principal;

                context.Validated(identity);
            }
            catch (Exception ex)
            {
                context.SetError("invalid_grant", ex.Message);
                return;
            }
        }
        /// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of "password". This occurs when the user has provided name and password
        /// credentials directly into the client application's user interface, and the client application is using those to acquire an "access_token" and
        /// optional "refresh_token". If the web application supports the
        /// resource owner credentials grant type it must validate the context.Username and context.Password as appropriate. To issue an
        /// access token the context.Validated must be called with a new ticket containing the claims about the resource owner which should be associated
        /// with the access token. The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious callers.
        /// The default behavior is to reject this grant type.
        /// See also http://tools.ietf.org/html/rfc6749#section-4.3.2
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>
        /// Task to enable asynchronous execution
        /// </returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});

            string actorType;
            using (var repo = new AuthorisationRepository())
            {
                var user = await repo.FindUser(context.UserName, context.Password); //actual authentication here

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

                actorType = user.Claims.First(x => x.ClaimType == ClaimTypes.Actor).ClaimValue;

                context.OwinContext.Set("user_type", actorType);
                //determine if it's a buyer or a seller
            }

            //useful info to include in the token here
           
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
            identity.AddClaim(new Claim("actor", actorType));

            context.Validated(identity);
        }
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
     // SharePoint...
     using (ClientContext ctx = new ClientContext(Constants.SPURL))
     {
         ctx.Credentials = new NetworkCredential(context.UserName, context.Password);
         var u = ctx.Web.CurrentUser;
         ctx.Load(u, _ => _.Title);
         try
         {
             ctx.ExecuteQuery();
             var identity = new ClaimsIdentity(context.Options.AuthenticationType);
             identity.AddClaim(new Claim("user", u.Title));
             identity.AddClaim(new Claim("login", EncryptionHelper.Encrypt(context.UserName)));
             identity.AddClaim(new Claim("pw", EncryptionHelper.Encrypt(context.Password)));
             context.Validated(identity);
         }
         catch (Exception ex)
         {
            
             context.SetError("invalid_grant", "Invalid UserName or Password");
         }
     }
 }
 public TokenBuilder(string userId, string username, string role)
 {
     this.Identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
     Identity.AddClaim(new Claim(ClaimTypes.Name, username));
     Identity.AddClaim(new Claim("role", role));
     Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId));
 }
        /// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of "password". 
        /// This occurs when the user has provided name and password credentials directly into the 
        /// client application's user interface, and the client application is using those to acquire an 
        /// "access_token" and optional "refresh_token". If the web application supports the resource owner 
        /// credentials grant type it must validate the context.Username and context.Password as appropriate. 
        /// To issue an access token the context.Validated must be called with a new ticket containing the 
        /// claims about the resource owner which should be associated with the access token. 
        /// The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious callers. 
        /// The default behavior is to reject this grant type. See also http://tools.ietf.org/html/rfc6749#section-4.3.2
        /// </summary>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

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

            if (context.UserName == "Pussy" && context.Password == "Cat")
            {


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

                // 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(identity, props);
                context.Validated(ticket);
                //context.Validated(identity);
                return;
            }
            context.Rejected();
        }
        public void DefaultUniqueClaimTypes_NotPresent_SerializesAllClaimTypes()
        {
            var identity = new ClaimsIdentity();
            identity.AddClaim(new Claim(ClaimTypes.Email, "*****@*****.**"));
            identity.AddClaim(new Claim(ClaimTypes.GivenName, "some"));
            identity.AddClaim(new Claim(ClaimTypes.Surname, "one"));
#if DNX451
            // CoreCLR doesn't support an 'empty' name
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, string.Empty));
#endif

            // Arrange
            var claimsIdentity = (ClaimsIdentity)identity;

            // Act
            var identiferParameters = DefaultClaimUidExtractor.GetUniqueIdentifierParameters(claimsIdentity)
                                                              .ToArray();
            var claims = claimsIdentity.Claims.ToList();
            claims.Sort((a, b) => string.Compare(a.Type, b.Type, StringComparison.Ordinal));

            // Assert
            int index = 0;
            foreach (var claim in claims)
            {
                Assert.Equal(identiferParameters[index++], claim.Type);
                Assert.Equal(identiferParameters[index++], claim.Value);
            }
        }
        public override Task HandleTokenRequest(HandleTokenRequestContext context) {
            // Only handle grant_type=password token requests and let the
            // OpenID Connect server middleware handle the other grant types.
            if (context.Request.IsPasswordGrantType()) {
                var user = new { Id = "users-123", UserName = "******", Password = "******" };

                if (!string.Equals(context.Request.Username, user.UserName, StringComparison.Ordinal) ||
                    !string.Equals(context.Request.Password, user.Password, StringComparison.Ordinal)) {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid username or password.");

                    return Task.FromResult(0);
                }

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

                identity.AddClaim(ClaimTypes.NameIdentifier, user.Id,
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                identity.AddClaim(ClaimTypes.Name, user.UserName,
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                context.Validate(new ClaimsPrincipal(identity));
            }

            return Task.FromResult(0);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {  //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (AuthService _repo = new AuthService())
            {
                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("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);
        }

        catch (Exception exp)
    {}
        }
예제 #16
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());
        }
        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);

        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)

        {
            //allow CORS specfically for OAuth and Authenticate
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });



            //Find User Base on Username and Password in Auth Repository 
            using (var authorizationRepository = new AuthorizationRepository())

            {
                var user = await authorizationRepository.FindUser(context.UserName, context.Password);
                //throw error if no user found
                if (user == null )
                {
                    context.SetError("invalid_grant", "username or password is incorrect");
                }
                else
                {
                    // creat a token and add some claims
                    var token = new ClaimsIdentity(context.Options.AuthenticationType);
                    token.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    token.AddClaim(new Claim(ClaimTypes.Role, "user"));
                    context.Validated(token);
                }
            }
    

        }
예제 #19
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;
        }
예제 #20
0
        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;
            }
        }
        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);

        }
        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);
        }
예제 #23
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);
 }
        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());
        }
 public override async Task Invoke(IOwinContext context)
 {
     if (context.Request.Method == "POST" && context.Request.Path.Value.ToLower().EndsWith("/account/login"))
     {
         var form = await context.Request.ReadFormAsync();
         var userName = form["username"];
         var password = form["password"];
         if (!string.IsNullOrWhiteSpace(userName))
         {
             var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationType);
             identity.AddClaim(new Claim(ClaimTypes.Name, userName));
             if (userName == "admin")
                 identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
             context.Authentication.SignIn(identity);
             context.Response.StatusCode = 200;
             context.Response.ReasonPhrase = "Authorized";
         }
         else
         {
             context.Authentication.SignOut();
             context.Response.StatusCode = 401;
             context.Response.ReasonPhrase = "Unauthorized";
         }
         return;
     }
     await Next.Invoke(context);
 }
        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);
            }
        }
        private ClaimsIdentity BuildIdentity(CasAuthenticationOptions options, string username, XElement successNode)
        {
            var identity = new ClaimsIdentity(options.AuthenticationType, options.NameClaimType, ClaimTypes.Role);
            identity.AddClaim(new Claim(ClaimTypes.Name, username, "http://www.w3.org/2001/XMLSchema#string", options.AuthenticationType));

            var attributesNode = successNode.Element(_ns + "attributes");
            if (attributesNode != null)
            {
                foreach (var element in attributesNode.Elements())
                {
                    identity.AddClaim(new Claim(element.Name.LocalName, element.Value));
                }
            }

            string identityValue = username;
            if (options.NameIdentifierAttribute != null && attributesNode != null)
            {
                var identityAttribute = attributesNode.Elements().FirstOrDefault(x => x.Name.LocalName == options.NameIdentifierAttribute);
                if (identityAttribute == null)
                    throw new ApplicationException(string.Format("Identity attribute [{0}] not found for user: {1}", options.NameIdentifierAttribute, username));

                identityValue = identityAttribute.Value;
            }
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identityValue, "http://www.w3.org/2001/XMLSchema#string", options.AuthenticationType));

            return identity;
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            IdentityUser user;
            using (var _repo = new AuthRepository())
            {
                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("userId", user.Id));

            if (user.Id == "c417fc8e-5bae-410f-b2ee-463afe2fdeaa")
                identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                {
                    "userId", user.Id
                }
            });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);

        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*";
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var user = await _userRepository.FindUserAsync(context.UserName, context.Password);
            if (user == null)
            {
                context.SetError("invalid_grant", "The username or password is incorrect.");
                return;
            }

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

            var authenticationProperties = new AuthenticationProperties(new Dictionary<string, string>
            {
                { "as:client_id", context.ClientId ?? string.Empty },
                { "username", context.UserName }
            });
            var ticket = new AuthenticationTicket(identity, authenticationProperties);
            context.Validated(ticket);
        }
        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);
        }
        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);
        }
예제 #32
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);
        }
예제 #33
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"));
        }
예제 #34
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);
        }
예제 #35
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;
            }
        }
예제 #36
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
                }
            }
        }
예제 #37
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 }));
     }
 }
예제 #38
0
파일: Startup.cs 프로젝트: tanyo520/auth
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.Map("/login", builder => builder.Use(next =>
            {
                return(async(context) =>
                {
                    var claimIdentity = new System.Security.Claims.ClaimsIdentity("Custom");
                    claimIdentity.AddClaim(new System.Security.Claims.Claim(ClaimTypes.Name, "jim"));
                    await context.SignInAsync("myScheme", new ClaimsPrincipal(claimIdentity));
                });
            }));

            // 退出
            app.Map("/logout", builder => builder.Use(next =>
            {
                return(async(context) =>
                {
                    await context.SignOutAsync("myScheme");
                });
            }));

            // 认证
            app.Use(next =>
            {
                return(async(context) =>
                {
                    var result = await context.AuthenticateAsync("myScheme");
                    if (result?.Principal != null)
                    {
                        context.User = result.Principal;
                    }
                    await next(context);
                });
            });


            // 授权
            app.Use(async(context, next) =>
            {
                var user = context.User;
                if (user?.Identity?.IsAuthenticated ?? false)
                {
                    if (user.Identity.Name != "jim")
                    {
                        await context.ForbidAsync("myScheme");
                    }
                    else
                    {
                        await next();
                    }
                }
                else
                {
                    await context.ChallengeAsync("myScheme");
                }
            });
            // 访问受保护资源
            app.Map("/resource", builder => builder.Run(async(context) => await context.Response.WriteAsync("Hello, ASP.NET Core!")));
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });
        }
예제 #39
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login")
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            #region ServerOAuth

            app.UseOAuthBearerAuthentication(new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions
                                                 ()
            {
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                AuthenticationType = "Emad",
                Realm = "EHM"     //anything
            });

            var options = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions();
            options.TokenEndpointPath     = new PathString("/account/token");
            options.AuthorizeEndpointPath = new PathString("/account/auth");
            options.AllowInsecureHttp     = true; //Don't do that!! always be on secure scheme, this is set to "true" for demo purposes
            var provider = new OAuthAuthorizationServerProvider();

            provider.OnValidateClientRedirectUri = (context) =>
            {
                return(Task.Run(() =>
                {
                    //Caution: this is not to validate that the uri is valid syntax wise, this is to validate it business wise. If this uri is not
                    //valid syntax wise this entry will not be hit in the first place, and your authentication process will not work!
                    context.Validated();
                }));
            };

            provider.OnValidateAuthorizeRequest = (context) =>
            {
                return(Task.Run(() =>
                {
                    //Authorization validation here
                    //Somewhere in the request you should create the identity and sign in with it, I put it here, it could be a page on your app?
                    context.OwinContext.Authentication.SignIn(new System.Security.Claims.ClaimsIdentity("Bearer"));
                    context.Validated();
                }));
            };

            provider.OnAuthorizeEndpoint = (context) =>
            {
                return(Task.Run(() =>
                {
                    //This is the last chance to alter the request, you can either end it here using RequestCompleted and start resonding,
                    //or you can let it go through to the subsequent middleware,
                    //except that you have to make sure the response returns a 200, otherwise the whole thing will not work
                    context.RequestCompleted();
                    var str = context.Options.AccessTokenFormat;
                }));
            };


            provider.OnValidateClientAuthentication = (context) =>
            {
                return(Task.Run(() =>
                {
                    //Client validation here
                    context.Validated();
                }));
            };

            options.Provider = provider;

            AuthenticationTokenProvider authTokenProvider = new AuthenticationTokenProvider();
            authTokenProvider.OnCreate = (context) =>
            {
                //create a dummy token
                context.SetToken("MyTokenblablabla");
            };

            //This is called when a client is requesting with Authorization header and passing the token, like this "Authorization: Bearer jdksjkld"
            authTokenProvider.OnReceive = (context) =>
            {
                //create dummy identity regardless of the validty of the token :)
                var claimsIdentity = new System.Security.Claims.ClaimsIdentity("Bearer");
                claimsIdentity.AddClaim(new Claim("something", "Ahmad")); //This claim type "something" is used for protection from anti-forgery...
                //Check the Global.asax for "AntiForgeryConfig.UniqueClaimTypeIdentifier = "something";"
                //you can avoid setting this, but you have to use the default claims type. check http://bartwullems.blogspot.com.au/2013/09/aspnet-mvc-4-error-when-using-anti.html

                context.SetTicket(new Microsoft.Owin.Security.AuthenticationTicket(claimsIdentity,
                                                                                   new Microsoft.Owin.Security.AuthenticationProperties
                {
                    ExpiresUtc = new System.DateTimeOffset(2015, 3, 1, 1, 1, 1, new System.TimeSpan()),
                }
                                                                                   ));
            };

            options.AuthorizationCodeProvider = authTokenProvider;
            options.RefreshTokenProvider      = authTokenProvider;
            options.AccessTokenProvider       = authTokenProvider;

            app.UseOAuthBearerTokens(options);

            #endregion

            //app.UseGoogleAuthentication();
        }
예제 #40
0
 public static void ReplaceClaim(this ClaimsIdentity identity, string type, string value)
 {
     identity.TryRemoveClaim(identity.Claims.FirstOrDefault(c => c.Type == type));
     identity.AddClaim(new Claim(type, value));
 }
예제 #41
0
 public static void MakeAttendee(this ClaimsIdentity identity) =>
 identity.AddClaim(new Claim(AuthConstants.IsAttendee, AuthConstants.TrueValue));