示例#1
0
        public async Task <IAuthenticationResponse> Refresh(
            IRefreshCred refreshCred,
            TokenValidationParameters tokenValidationParameters)
        {
            var jwtRefreshCred = refreshCred as JwtRefreshCred;

            SecurityToken validatedToken;

            var principal = new JwtSecurityTokenHandler().ValidateToken(
                jwtRefreshCred.JwtToken,
                tokenValidationParameters,
                out validatedToken);

            if (!IsValidToken(validatedToken as JwtSecurityToken))
            {
                throw new SecurityTokenException("Invalid token passed!");
            }

            var userLogin = principal.Claims.ToList().Where(claim => claim.Type == "Login").FirstOrDefault().Value;

            if (jwtRefreshCred.JwtRefreshToken != await _JwtAuthenticationManager.RefreshTokensDictionary.GetStringAsync(userLogin))
            {
                throw new SecurityTokenException("Invalid token passed!");
            }

            return(await _JwtAuthenticationManager.AuthenticateAsync(principal.Claims.ToList()));
        }
示例#2
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ActionResult Authorize()
        {
            //验证是否登录,如果没有,
            IAuthenticationManager authentication = HttpContext.GetOwinContext().Authentication;
            AuthenticateResult     ticket         = authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie).Result;
            ClaimsIdentity         identity       = ticket == null ? null : ticket.Identity;

            if (identity == null)
            {
                //如果没有验证通过,则必须先通过身份验证,跳转到验证方法
                authentication.Challenge();
                return(new HttpUnauthorizedResult());
            }
            identity = new ClaimsIdentity();
            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim(ClaimTypes.Name, "admin"));
            claims.Add(new Claim(ClaimTypes.NameIdentifier, "admin"));
            identity = new ClaimsIdentity(identity.Claims, "Bearer");
            //hardcode添加一些Claim,正常是从数据库中根据用户ID来查找添加
            identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
            identity.AddClaim(new Claim("MyType", "MyValue"));

            authentication.SignIn(new AuthenticationProperties()
            {
                IsPersistent = true, RedirectUri = Request.QueryString["redirect_uri"]
            }, identity);


            return(new EmptyResult());
        }
示例#3
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            //验证是否登录,如果没有,
            IAuthenticationManager authentication = HttpContext.GetOwinContext().Authentication;
            AuthenticateResult     ticket         = authentication.AuthenticateAsync("client_credentials").Result;
            ClaimsIdentity         identity       = ticket == null ? null : ticket.Identity;

            //if (identity == null)
            //{
            //    //如果没有验证通过,则必须先通过身份验证,跳转到验证方法
            //    authentication.Challenge();
            //    return new HttpUnauthorizedResult();
            //}
            identity = new ClaimsIdentity();
            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim(ClaimTypes.Name, "admin"));
            claims.Add(new Claim(ClaimTypes.NameIdentifier, "admin"));
            identity = new ClaimsIdentity(identity.Claims, "Bearer");
            //hardcode添加一些Claim,正常是从数据库中根据用户ID来查找添加
            identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
            identity.AddClaim(new Claim("MyType", "MyValue"));

            authentication.SignIn(new AuthenticationProperties()
            {
                IsPersistent = true
            }, identity);


            return(new EmptyResult());
        }
        /// <inheritdoc />
        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpRequestMessage request = context.Request;

            if (request == null)
            {
                throw new InvalidOperationException(OwinResources.HttpAuthenticationContext_RequestMustNotBeNull);
            }

            IAuthenticationManager authenticationManager = GetAuthenticationManagerOrThrow(request);

            cancellationToken.ThrowIfCancellationRequested();
            AuthenticateResult result = await authenticationManager.AuthenticateAsync(_authenticationType);

            if (result != null)
            {
                IIdentity identity = result.Identity;

                if (identity != null)
                {
                    context.Principal = new ClaimsPrincipal(identity);
                }
            }
        }
示例#5
0
        public static async Task <Dictionary <string, string> > GetWeChatLoginInfoAsync(this IAuthenticationManager manager, string authenticationType)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            var result = await manager.AuthenticateAsync(authenticationType);

            if (result != null && result.Identity != null && result.Identity.FindFirst(Constants.ClaimType) != null)
            {
                var value = result.Identity.FindFirst(Constants.ClaimType).Value;

                if (!string.IsNullOrEmpty(value))
                {
                    var jObject = JObject.Parse(value);

                    Dictionary <string, string> dict = new Dictionary <string, string>();

                    foreach (var item in jObject)
                    {
                        dict[item.Key] = item.Value == null ? null : item.Value.ToString();
                    }

                    return(await Task.FromResult(dict));
                }
            }
            return(null);
        }
示例#6
0
        public async Task <IActionResult> CreateToken(
            [FromBody] LoginModel model)
        {
            var result = await _authenticationManager.AuthenticateAsync(model);

            return(Created("", result));
        }
		public async Task<ExternalAuthenticationResult> GetAuthenticationResult(IAuthenticationManager authenticationManager)
		{
			var authResult = await authenticationManager.AuthenticateAsync(ExternalCookieName);
			if (authResult == null)
				return null;
			if (!authResult.Identity.IsAuthenticated)
				return null;
			var externalIdentity = authResult.Identity;
			var providerKeyClaim = externalIdentity.FindFirst(ClaimTypes.NameIdentifier);
			var issuer = providerKeyClaim.Issuer;
			var providerKey = providerKeyClaim.Value;
			var name = externalIdentity.FindFirstValue(ClaimTypes.Name);
			var email = externalIdentity.FindFirstValue(ClaimTypes.Email);
			if (String.IsNullOrEmpty(issuer))
				throw new NullReferenceException("The identity claims contain no issuer.");
			if (String.IsNullOrEmpty(providerKey))
				throw new NullReferenceException("The identity claims contain no provider key");
			var result = new ExternalAuthenticationResult
			             {
				             Issuer = issuer,
				             ProviderKey = providerKey,
				             Name = name,
				             Email = email
			             };
			return result;
		}
 /// <summary>
 ///     Extracts login info out of an external identity
 /// </summary>
 /// <param name="manager"></param>
 /// <returns></returns>
 public static async Task <ExternalLoginInfo> GetExternalLoginInfoAsync(this IAuthenticationManager manager)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     return(GetExternalLoginInfo(await manager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie).WithCurrentCulture()));
 }
示例#9
0
 /// <summary>
 ///     Extracts login info out of an external identity
 /// </summary>
 /// <param name="manager"></param>
 /// <param name="authenticationType"></param>
 /// <returns></returns>
 public static async Task <ExternalLoginInfo> GetExternalLoginInfoAsync(this IAuthenticationManager manager, string authenticationType)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     return(GetExternalLoginInfo(await manager.AuthenticateAsync(authenticationType)));
 }
示例#10
0
        public async static Task <bool> TwoFactorBrowserRememberedAsync(this IAuthenticationManager manager, int userId)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            var result = await manager.AuthenticateAsync(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            return(result != null && result.Identity != null && result.Identity.GetUserId <int>() == userId);
        }
        public virtual async Task <int?> GetVerifiedUserIdAsync()
        {
            var result = await _authenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.TwoFactorCookie).ConfigureAwait(false);

            if (result != null && result.Identity != null && !String.IsNullOrEmpty(result.Identity.GetUserId()))
            {
                return(int.Parse(result.Identity.GetUserId()));
            }
            return(null);
        }
示例#12
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            IAuthenticationManager authentication = filterContext.HttpContext.GetOwinContext().Authentication;
            AuthenticateResult     ticket         = authentication.AuthenticateAsync("PCM").Result;

            if (!ticket?.Identity.IsAuthenticated ?? true)
            {
                base.OnAuthorization(filterContext);
            }
        }
        private static async Task<bool> TwoFactorBrowserRememberedAsync(IAuthenticationManager manager, long userId)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            AuthenticateResult authenticateResult = await manager
                .AuthenticateAsync("TwoFactorRememberBrowser");
            return authenticateResult != null && authenticateResult.Identity != null && authenticateResult.Identity.GetUserId<long>() == userId;

        }
示例#14
0
        public async Task <bool> SignUpUser(IAuthenticationManager authenticationManager, ISecureDataFormat <AuthenticationTicket> df, AuthenticationTicket at)
        {
            List <ClaimsIdentity> claims = new List <ClaimsIdentity>()
            {
                new ClaimsIdentity()
            };
            AuthenticationProperties authProp = new AuthenticationProperties();

            var authResult = await authenticationManager.AuthenticateAsync("");

            authenticationManager.Challenge(new string[] { "" });
            var authResults = await authenticationManager.AuthenticateAsync(new string[] { "", "" });

            authenticationManager.Challenge(authProp, new string[] { "" });
            authenticationManager.SignOut(authProp, new string[] { "" });

            string prot = df.Protect(at);
            AuthenticationTicket unProtectedAT = df.Unprotect(prot);

            return(at.Equals(unProtectedAT));
        }
示例#15
0
        /// <summary>
        ///     Returns true if there is a TwoFactorRememberBrowser cookie for a user
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static async Task <bool> InspurTwoFactorBrowserRememberedAsync(this IAuthenticationManager manager,
                                                                              string userId)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            var result =
                await manager.AuthenticateAsync(InspurDefaultAuthenticationTypes.TwoFactorRememberBrowserCookie).WithCurrentCulture();

            return(result != null && result.Identity != null && result.Identity.GetUserId() == userId);
        }
示例#16
0
        public async Task <bool> SignUpUser(IAuthenticationManager authenticationManager, ISecureDataFormat <AuthenticationTicket> df)
        {
            List <ClaimsIdentity> claims = new List <ClaimsIdentity>()
            {
                new ClaimsIdentity()
            };
            AuthenticationProperties authProp = new AuthenticationProperties();

            var authResult = await authenticationManager.AuthenticateAsync("");

            authenticationManager.Challenge(new string[] { "" });
            var authResults = await authenticationManager.AuthenticateAsync(new string[] { "", "" });

            authenticationManager.Challenge(authProp, new string[] { "" });
            var authTypes = authenticationManager.GetAuthenticationTypes();

            authenticationManager.SignIn(claims.ToArray());
            authenticationManager.SignOut(authProp, new string[] { "" });

            ExternalLoginInfo info       = authenticationManager.GetExternalLoginInfo();
            ExternalLoginInfo infoAsync1 = await authenticationManager.GetExternalLoginInfoAsync();

            ExternalLoginInfo infoAsync2 = await authenticationManager.GetExternalLoginInfoAsync("key_here", "expected");

            List <AuthenticationDescription> desc = authenticationManager.GetExternalAuthenticationTypes().ToList();
            bool rem      = authenticationManager.TwoFactorBrowserRemembered("userID");
            bool remAsync = await authenticationManager.TwoFactorBrowserRememberedAsync("userID");

            AuthenticationTicket at            = new AuthenticationTicket(claims.First(), authProp);
            string prot                        = df.Protect(at);
            AuthenticationTicket unProtectedAT = df.Unprotect(prot);

            OAuthAuthorizationServerOptions auth = new OAuthAuthorizationServerOptions()
            {
                AccessTokenExpireTimeSpan = new TimeSpan(),
                AllowInsecureHttp         = true,
            };

            return(at.Equals(unProtectedAT));
        }
示例#17
0
        public async Task <IActionResult> Login(User user)
        {
            var requireUser = await _repository.GetOneAsync(user.Login);

            if (requireUser is null)
            {
                return(Unauthorized());
            }

            var resp = (JwtAuthenticationResponse)await _authentication.AuthenticateAsync(user);

            AddTokensToCache(resp);

            return(RedirectToAction("Index"));
        }
示例#18
0
        public async Task <string> GetNonceAsync(IAuthenticationManager authenticationManager)
        {
            var data = await authenticationManager.AuthenticateAsync("TempState");

            if (data == null)
            {
                return(null);
            }

            var nonce = data.Identity.FindFirst("nonce").Value;

            authenticationManager.SignOut("TempState");

            return(nonce);
        }
        /// <summary>
        ///     Return the identity associated with the default external authentication type
        /// </summary>
        /// <returns></returns>
        public static async Task <ClaimsIdentity> GetExternalIdentityAsync(this IAuthenticationManager manager,
                                                                           string externalAuthenticationType)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            var result = await manager.AuthenticateAsync(externalAuthenticationType).WithCurrentCulture();

            if (result != null && result.Identity != null &&
                result.Identity.FindFirst(ClaimTypes.NameIdentifier) != null)
            {
                return(result.Identity);
            }
            return(null);
        }
        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            HttpRequestMessage     request = context.Request;
            IAuthenticationManager authenticationManager = GetAuthenticationManagerOrThrow(request);
            AuthenticateResult     result = await authenticationManager.AuthenticateAsync(_authenticationType);

            if (result != null)
            {
                IIdentity identity = result.Identity;

                if (identity != null)
                {
                    context.Principal = new ClaimsPrincipal(identity);
                }
            }
        }
示例#21
0
        //method below based on discussion at http://stackoverflow.com/questions/19564479/mvc-5-owin-facebook-auth-results-in-null-reference-exception
        private static async Task <ExternalLoginInfo> GetExternalLoginInfoAsync_Workaround(IAuthenticationManager authenticationManager)
        {
            ExternalLoginInfo loginInfo = null;

            var result = await authenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            if (result != null && result.Identity != null)
            {
                var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);
                if (idClaim != null)
                {
                    loginInfo = new ExternalLoginInfo()
                    {
                        DefaultUserName = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", ""),
                        Login           = new UserLoginInfo(idClaim.Issuer, idClaim.Value)
                    };
                }
            }
            return(loginInfo);
        }
        /// <summary>
        ///     Extracts login info out of an external identity
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="xsrfKey">key that will be used to find the userId to verify</param>
        /// <param name="expectedValue">
        ///     the value expected to be found using the xsrfKey in the AuthenticationResult.Properties
        ///     dictionary
        /// </param>
        /// <returns></returns>
        public static async Task <ExternalLoginInfo> GetExternalLoginInfoAsync(this IAuthenticationManager manager,
                                                                               string xsrfKey, string expectedValue)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            var result = await manager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie).WithCurrentCulture();

            // Verify that the userId is the same as what we expect if requested
            if (result != null &&
                result.Properties != null &&
                result.Properties.Dictionary != null &&
                result.Properties.Dictionary.ContainsKey(xsrfKey) &&
                result.Properties.Dictionary[xsrfKey] == expectedValue)
            {
                return(GetExternalLoginInfo(result));
            }
            return(null);
        }
        protected async Task AuthenticateAsync(
            CancellationToken cancellationToken = default
            )
        {
            // ToDo: Figure out how to sign-in without TenantId.
            _authConf = _configurationProvider
                        .GetAuthenticationConfiguration(
                AzureEnvironment.KnownEnvironments
                );

            _authenticationManager = AuthenticationManagerFactory
                                     .GetAuthenticationManager(
                _authConf.AzureEnvironment,
                _authConf.TenantId,
                _authConf.ClientId,
                _authConf.ClientSecret
                );

            await _authenticationManager
            .AuthenticateAsync(cancellationToken);
        }
示例#24
0
        public async Task <ExternalAuthenticationResult> GetAuthenticationResult(IAuthenticationManager authenticationManager)
        {
            var authResult = await authenticationManager.AuthenticateAsync(ExternalCookieName);

            if (authResult == null)
            {
                return(null);
            }
            if (!authResult.Identity.IsAuthenticated)
            {
                return(null);
            }
            var externalIdentity = authResult.Identity;
            var providerKeyClaim = externalIdentity.FindFirst(ClaimTypes.NameIdentifier);
            var issuer           = providerKeyClaim.Issuer;
            var providerKey      = providerKeyClaim.Value;
            var name             = externalIdentity.FindFirstValue(ClaimTypes.Name);
            var email            = externalIdentity.FindFirstValue(ClaimTypes.Email);

            if (String.IsNullOrEmpty(issuer))
            {
                throw new NullReferenceException("The identity claims contain no issuer.");
            }
            if (String.IsNullOrEmpty(providerKey))
            {
                throw new NullReferenceException("The identity claims contain no provider key");
            }
            var result = new ExternalAuthenticationResult
            {
                Issuer      = issuer,
                ProviderKey = providerKey,
                Name        = name,
                Email       = email
            };

            return(result);
        }
示例#25
0
        public async Task <JObject> Create(JObject request)
        {
            var providerName = (string)request["providerName"];

            if (string.IsNullOrEmpty(providerName))
            {
                ThrowHttpResponse(HttpStatusCode.BadRequest, "providerName is required!");
            }

            User user = null;

            try
            {
                user = await _authenticationManager.AuthenticateAsync(providerName, request);
            }
            catch (AuthenticationException)
            {
                ThrowHttpResponse(HttpStatusCode.Unauthorized, "Invalid credentials or account is disabled!");
            }

            var accessKey = CreateAccessKey(user);

            return(new JObject(new JProperty("id", accessKey.ID), new JProperty("key", accessKey.Key)));
        }
 public async Task <BearerViewModel> LoginAsync(LoginViewModel loginRequest)
 {
     return(await _authenticationManager.AuthenticateAsync(loginRequest.Username, loginRequest.Password));
 }