Пример #1
0
        public Task <string> StoreAsync(AuthenticationTicket ticket)
        {
            //Log.Info("ADFS: In StoreAsync", this);
            string key = Guid.NewGuid().ToString();

            _permStore.Entries.Add(new AuthSessionEntry {
                Key = key, TicketString = _formatter.Protect(ticket), ValidUntil = ticket.Properties.ExpiresUtc
            });
            _permStore.SaveChanges();
            return(Task.FromResult(key));
        }
Пример #2
0
        private Tuple <Token, User> GenerateToken(User user)
        {
            var secureDataFormat = new TicketDataFormat(_dataProtector);
            var expirationDate   = DateTimeOffset.UtcNow.AddDays(1);

            var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

            identity.AddClaims(user.GetClaims());

            var tokenValue = secureDataFormat.Protect(new AuthenticationTicket(identity, new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = expirationDate
            }));

            var token = new Token()
            {
                AccessToken = tokenValue,
                TokenType   = OAuthDefaults.AuthenticationType,
                ExpiresAt   = expirationDate,
                ExpiresIn   = (uint)(expirationDate - DateTime.UtcNow).TotalSeconds
            };

            return(Tuple.Create(token, user));
        }
Пример #3
0
        private async Task <string> GetCookie()
        {
            await CreateNewUser();

            if (NewUser == null)
            {
                return(null);
            }
            var authenticationMethod = NewUser.Logins.FirstOrDefault()?.LoginProvider ?? "Google";
            var claims = new[]
            {
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", NewUser.Id.ToString()),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", NewUser.UserName),
                new Claim("AspNet.Identity.SecurityStamp", NewUser.SecurityStamp),
                new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", authenticationMethod)
            };
            const string cookieSchema     = "Identity.Application";
            var          myService        = TestServer.Host.Services.GetRequiredService <IOptionsMonitor <CookieAuthenticationOptions> >();
            var          dataProtector    = myService.CurrentValue.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", cookieSchema, "v2");
            var          principal        = new ClaimsPrincipal(new ClaimsIdentity(claims, cookieSchema));
            var          ticket           = new AuthenticationTicket(principal, cookieSchema);
            var          ticketDataFormat = new TicketDataFormat(dataProtector);
            var          cookie           = ticketDataFormat.Protect(ticket);

            return(cookie);
        }
Пример #4
0
        public string GenerateToken(string code, string name, int timeout, Dictionary <string, string> extras = null)
        {
            var principal = CreatePrincipal(code, name, extras);
            var props     = CreateProperties(timeout);

            return(_format.Protect(new AuthenticationTicket(principal, props, TenjinConstants.BEARER_AUTHORIZATION_NAME)));
        }
Пример #5
0
        public string Protect(AuthenticationTicket data, string purpose)
        {
            string base64url = _ticketDataFormat.Protect(data, purpose);

            // Fix up '-' -> '~', as '--' sequence in cookie values trigger
            // "942440 SQL Comment Sequence Detected" rule in Azure WAF
            return(base64url.Replace('-', '~'));
        }
Пример #6
0
        public Task <string> StoreAsync(AuthenticationTicket ticket)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException(nameof(ticket));
            }

            string key = Guid.NewGuid().ToString();

            using (SqlAuthSessionStoreContext store = new SqlAuthSessionStoreContext(_connectionString))
            {
                store.Entries.Add(new AuthSessionEntry {
                    Key = key, TicketString = _formatter.Protect(ticket), ValidUntil = ticket.Properties.ExpiresUtc
                });
                store.SaveChanges();
            }

            return(Task.FromResult(key));
        }
        private string ProtectedData(AuthenticationTokenCreateContext context)
        {
            if (_dataFormat == null)
            {
                _dataFormat = CreateDataFormat();
            }

            var data = context.Ticket;
            var text = _dataFormat.Protect(data);

            return(text);
        }
        public ActionResult Index()
        {
            var cookie = System.Web.HttpContext.Current.Request.Cookies.Get(".AspNet.ApplicationCookie");
            var ticket = cookie.Value;

            //Handle encoding
            ticket = ticket.Replace('-', '+').Replace('_', '/');
            var padding = 3 - ((ticket.Length + 3) % 4);

            if (padding != 0)
            {
                ticket = ticket + new string('=', padding);
            }

            var machineKeyProtector = new MachineKeyProtector();
            var ticketData          = new TicketDataFormat(machineKeyProtector);


            //Set the purpose for decrypting the cookie based ticket
            machineKeyProtector.Purpose = new string[]
            {
                typeof(CookieAuthenticationMiddleware).FullName,
                "ApplicationCookie",
                "v1"
            };
            var decryptedTicket = ticketData.Unprotect(ticket);

            //Change the purpose for creating an encrypted bearer token
            machineKeyProtector.Purpose = new string[]
            {
                typeof(OAuthAuthorizationServerMiddleware).Namespace,
                "Access_Token",
                "v1"
            };
            var encryptedTicket = ticketData.Protect(decryptedTicket);

            string bearerToken = $"Bearer {encryptedTicket}";

            var client = new HttpClient();

            client.BaseAddress = new Uri("http://localhost:58719/");
            client.DefaultRequestHeaders.Add("Authorization", bearerToken);
            var result = client.GetAsync("/api/ResourceData").Result.Content.ReadAsStringAsync().Result;

            ViewBag.ResultData  = result;
            ViewBag.BearerToken = bearerToken;
            return(View());
        }
Пример #9
0
        private void AddCookieFromIdentity(ClaimsIdentity identity, DateTime?expirationTime = null)
        {
            var authProperties = new AuthenticationProperties()
            {
                IsPersistent = false,
                ExpiresUtc   = expirationTime ?? DateTime.UtcNow.AddHours(24),
                IssuedUtc    = DateTime.UtcNow
            };

            var ticket = new AuthenticationTicket(identity, authProperties);

            var ticketFormat     = new TicketDataFormat(new DataProtector(ProtectionPurpose));
            var serializedTicked = ticketFormat.Protect(ticket);

            var cookie = new HttpCookie(CookiesIdentifier, serializedTicked);

            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        public string GenerateToken(string code, string company, string permission, int timeout)
        {
            var identity = new ClaimsIdentity(HelperConstants.BearerAuthenName);

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, code));

            var current = DateTime.UtcNow;
            var props   = new AuthenticationProperties
            {
                IssuedUtc  = current,
                ExpiresUtc = current.Add(TimeSpan.FromDays(timeout))
            };

            var principal = new ClaimsPrincipal();

            principal.AddIdentity(identity);

            return(format.Protect(new AuthenticationTicket(principal, props, HelperConstants.BearerAuthenName)));
        }
Пример #11
0
        public string Generate()
        {
            // Generate an OAuth bearer token for ASP.NET/Owin Web Api service that uses the default OAuthBearer token middleware.
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, "WebApiUser"),
                new Claim(ClaimTypes.Role, "User"),
                new Claim(ClaimTypes.Role, "PowerUser"),
            };
            var identity  = new ClaimsIdentity(claims, "Test");
            var principal = new ClaimsPrincipal(identity);

            // Use the same token generation logic as the OAuthBearer Owin middleware.
            var tdf         = new TicketDataFormat(_dataProtector);
            var ticket      = new AuthenticationTicket(principal, new AuthenticationProperties(), "Cookie");
            var accessToken = tdf.Protect(ticket);

            return(accessToken);
        }
Пример #12
0
        private string GenerateToken()
        {
            // Generate an OAuth bearer token for ASP.NET/Owin Web Api service that uses the default OAuthBearer token middleware.
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, "WebApiUser"),
                new Claim(ClaimTypes.Role, "User"),
                new Claim(ClaimTypes.Role, "PowerUser"),
            };
            var identity = new ClaimsIdentity(claims, "Test");

            // Use the same token generation logic as the OAuthBearer Owin middleware.
            var tdf    = new TicketDataFormat(this.DataProtector);
            var ticket = new AuthenticationTicket(identity, new AuthenticationProperties {
                ExpiresUtc = DateTime.UtcNow.AddHours(1)
            });
            var accessToken = tdf.Protect(ticket);

            return(accessToken);
        }
Пример #13
0
        /// <summary>
        /// Gets an encrypted authentication ticket for the specified principal that expires in the specified number of seconds.
        /// </summary>
        /// <param name="principal">The authenticated claims principal.</param>
        /// <param name="expiresSeconds">The number of seconds for the ticket expiration. Defaults to 1 min, but cannot exceed 5 minutes.</param>
        /// <returns>The encrypted authentication ticket for the specified principal.</returns>
        public string GetSignInTicket(ClaimsPrincipal principal, int expiresSeconds = 60)
        {
            var props = new AuthenticationProperties
            {
                ExpiresUtc = DateTime.Now.AddSeconds(Math.Min(expiresSeconds, 300))
            };
            var uri = Navigation.ToAbsoluteUri(Navigation.Uri);

            if (QueryHelpers.ParseQuery(uri.Query).TryGetValue(RedirectUriParam, out var param))
            {
                props.RedirectUri = param.First();
            }
            var ticket           = new AuthenticationTicket(principal, props, principal.Identity.AuthenticationType);
            var dataProtector    = DataProtection.CreateProtector(SignInTicketProtectionPurpose);
            var ticketDataFormat = new TicketDataFormat(dataProtector);

            string protectedTicket = ticketDataFormat.Protect(ticket);

            return(protectedTicket);
        }
Пример #14
0
        public async Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
        {
            if (user == null || this.Context == null)
            {
                return;
            }
            properties ??= new AuthenticationProperties();
            properties.ExpiresUtc = this.Clock.UtcNow + this.Options.ExpireTime; // 过期时间
            properties.IssuedUtc  = DateTime.Now;                                // 发行时间

            var name = user.Identity.Name;

            if (!string.IsNullOrEmpty(name))
            {
                // 创建Ticket
                var ticket = new AuthenticationTicket(user, properties, this.Scheme.Name);
                var token  = _dataformat.Protect(ticket);
                this.Context.Items.Add(ApiTokenKey, token);
            }
            await Task.FromResult(true);
        }
Пример #15
0
        public static IObservable <Token> GenerateToken(this IObservable <ExternalUser> userStream, DateTime expirationDate)
        {
            var secureDataFormat = new TicketDataFormat(_dataProtector);

            var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

            identity.AddClaims(claims);

            var tokenValue = secureDataFormat.Protect(new AuthenticationTicket(identity, new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = expirationDate
            }));

            return(new Token()
            {
                AccessToken = tokenValue,
                TokenType = OAuthDefaults.AuthenticationType,
                ExpiresAt = expirationDate,
                ExpiresIn = (uint)(expirationDate - DateTime.UtcNow).TotalSeconds
            });
        }
        protected async override Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (this.Context == null)
            {
                return(AuthenticateResult.Fail("Context is Null"));
            }
            if (this.Options == null)
            {
                return(AuthenticateResult.Fail("Options is Null"));
            }
            var token = this.Context.Request.Query[Options.TokenQueryKey].FirstOrDefault();

            if (string.IsNullOrEmpty(token))
            {
                // 地址过滤标识
                var    flag = false;
                string key1 = this.Context.Request.Query["name"];
                if (!string.IsNullOrEmpty(key1) && key1 == "admin")
                {
                    flag = true;
                }

                if (flag)
                {
                    ClaimsIdentity id = new ClaimsIdentity(APIScheme, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
                    id.AddClaim(new Claim(ClaimTypes.Role, key1));
                    id.AddClaim(new Claim(ClaimTypes.Name, key1));
                    //id.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, "admin"));


                    ClaimsPrincipal      p     = new ClaimsPrincipal(id);
                    AuthenticationTicket tiket = new AuthenticationTicket(p, APIScheme);
                    this.Context.Items.Add(APIUserKey, _format.Protect(tiket));
                    return(AuthenticateResult.Success(tiket));
                }
                return(AuthenticateResult.Fail("暂无权限"));//.NoResult();
            }

            if (string.IsNullOrEmpty(token))
            {
                return(AuthenticateResult.NoResult());
            }


            int index = token.IndexOf('1');

            if (index == -1)
            {
                return(AuthenticateResult.Fail("format wrong"));
            }

            var user = token.Substring(index + 1);

            var userEntity = await _userManager.FindByNameAsync(user);

            if (userEntity == null)
            {
                return(AuthenticateResult.Fail("user is not found"));
            }



            var ticketStr = await _userManager.GetAuthenticationTokenAsync(userEntity, "APILOGIN", token);

            if (string.IsNullOrEmpty(ticketStr))
            {
                return(AuthenticateResult.NoResult());
            }

            var tokenObj = _format.Unprotect(ticketStr);

            if (tokenObj == null)
            {
                return(AuthenticateResult.NoResult());
            }
            // 验证过期时间
            if (tokenObj.Properties.ExpiresUtc.HasValue)
            {
                if (tokenObj.Properties.ExpiresUtc < base.Clock.UtcNow)
                {
                    return(AuthenticateResult.Fail("Ticket Expire"));
                }
            }

            if (tokenObj.Principal == null)
            {
                return(AuthenticateResult.Fail("NO Principal"));
            }

            this.Context.Items.Add(APIUserKey, tokenObj.Principal);
            this.Context.Items.Add("ticket", token);
            _log.LogDebug($"Get a token ticket user is {tokenObj?.Principal?.Identity?.Name}");
            return(AuthenticateResult.Success(tokenObj));
        }
        string ISecureDataFormat <AuthenticationTicket> .Protect(AuthenticationTicket data)
        {
            var output = innerDataFormat.Protect(data);

            return(output);
        }
Пример #18
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ApplicationCookie);

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/account/ntlmlogin"),
                ReturnUrlParameter = "ReturnUrl",
                Provider           = new CookieAuthenticationProvider
                {
                    OnApplyRedirect = ctx => {
                        if (!ctx.Request.IsNtlmAuthenticationCallback())
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                    }
                }
            });

            var oauthServerOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath           = new PathString("/token"),
                AccessTokenExpireTimeSpan   = new TimeSpan(1, 0, 0),
                ApplicationCanDisplayErrors = true,
                AllowInsecureHttp           = true,
                Provider = new OAuthAuthorizationServerProvider()
            };

            app.UseOAuthBearerTokens(oauthServerOptions);

            app.UseNtlmAuthentication(new NtlmAuthOptions()
            {
                DomainName   = Environment.MachineName, // test only, my machinename (domain)
                ExpiryPeriod = new TimeSpan(1, 0, 0),
                //AppAuthFactory = _appAuthFactory,
                Options          = oauthServerOptions,
                OnCreateIdentity = (windowsIdentity, authOptions, request /*, properties*/) => {
                    var options       = authOptions as NtlmAuthOptions;
                    var parts         = windowsIdentity.Name.Split(new[] { '\\' }, 2);
                    string username   = parts.Length == 1 ? parts[0] : parts[parts.Length - 1];
                    string domainname = parts.Length == 1 ? null : parts[parts.Length - 2];
                    if (domainname == null ||
                        !domainname.Equals(options.DomainName, StringComparison.OrdinalIgnoreCase))
                    {
                        return(null);
                    }

                    //var user = appAuthManager.Value.FindUserByName(username);
                    var user = new ApplicationUser
                    {
                        Id       = "1",
                        UserName = username
                    };

                    var claims = new List <Claim> {
                        new Claim(ClaimTypes.NameIdentifier, user.Id),
                        new Claim(ClaimTypes.Name, user.UserName)
                    };

                    //var roles = appAuthManager.Value.UserRoles(user.Id);
                    //claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

                    //var accessRights = appAuthManager.Value.UserAccessRights(user.Id);
                    //claims.AddRange(accessRights.Select(accessRight => new Claim(ClaimTypes.UserData, accessRight)));

                    // bearer token
                    var oauthIdentity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

                    // see: http://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin.Security.OAuth/OAuthAuthorizationServerMiddleware.cs
                    var ticket = new AuthenticationTicket(oauthIdentity, new AuthenticationProperties(new Dictionary <string, string> {
                        { "userId", user.Id },
                        { "userName", user.UserName }
                    }));
                    var protector    = app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1");
                    var tdf          = new TicketDataFormat(protector);
                    var access_token = tdf.Protect(ticket);

                    // return the token as a query parameter of the redirectUrl
                    //properties.RedirectUri += $"?access_token={access_token}";
                    //properties.ExpiresUtc = DateTime.UtcNow.Add(options.ExpiryPeriod);
                    //properties.IsPersistent = true;
                    //properties.AllowRefresh = true;

                    // cookies
                    var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                    return(identity);
                }
            });
        }