Ejemplo n.º 1
0
 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(AuthUserManager manager)
 {
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
     // Add custom user claims here
     return userIdentity;
 }
        public async Task <HttpMessage <IdentityResult> > Login(LoginUser login)
        => await TryCatchResponseAsync(async() =>
        {
            HttpMessage <UserWithRole> postResult = await Json.PostAsync <HttpMessage <UserWithRole>, LoginUser>(AppSettings.AccountService.Server, AppSettings.AccountService.ApiAccount + "/login", login,
                                                                                                                 onError: (e) =>
            {
                postResult = CreateResponseError <UserWithRole>(e);
            });


            UserWithRole user = postResult?.Data;

            if (user == null)
            {
                throw new Exception("Невозможно произвести авторизацию!");
            }

            Principal principal = new Principal(user);
            AuthUserManager.LogIn(principal);
            int siteUserId = SetUserUid(login.Uid, user.Id);

            bool Cms = user.Roles != null && user.Roles.Count > 0 && user.Roles.FirstOrDefault(f => f.Role == 1) != null;

            return(CreateResponseOk(new IdentityResult {
                SiteUserId = siteUserId, Auth = true, Cms = Cms, Token = principal.GetKey(), User = user
            }));
        });
        public async Task Invoke(HttpContext context)
        {
            StringValues authorization = context.Request.Headers["Authorization"];

            if (authorization.Count > 0)
            {
                foreach (var item in authorization)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        string[] v   = item.Split(' ');
                        string   key = "";
                        string   val = "";
                        if (v.Length > 0)
                        {
                            key = v[0];
                        }
                        if (v.Length > 1)
                        {
                            val = v[1];
                        }
                        if (key == API_KEY_HEADER && !string.IsNullOrEmpty(val))
                        {
                            Principal principal = AuthUserManager.GetLogIn(val);
                            if (principal != null)
                            {
                                SetPrincipal(principal);
                            }
                        }
                    }
                }
            }

            await _next.Invoke(context);
        }
Ejemplo n.º 4
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && _userManager != null)
            {
                _userManager.Dispose();
                _userManager = null;
            }

            base.Dispose(disposing);
        }
 public async Task <HttpMessage <string> > Logout(string uid)
 => await TryCatchResponseAsync(async() =>
 {
     SetUserUid(uid, 0);
     Principal principal = Core.Http.HttpContext.Current.User as Principal;
     if (principal != null)
     {
         AuthUserManager.LogOut(principal.GetKey());
     }
     return(CreateResponseOk("Ok"));
 });
Ejemplo n.º 6
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (var _repo = new AuthUserManager())
            {
                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);
        }
        public async Task <HttpMessage <UidResult> > Uid(string uid)
        => await TryCatchResponseAsync(async() =>
        {
            return(await Task.Run(() =>
            {
                Principal principal = Core.Http.HttpContext.Current.User as Principal;
                UserWithRole user = null;
                if (principal == null || principal.User == null)
                {
                    UserUid uu = GetUserUid(uid);
                    HttpMessage <UserWithRole> postResult = Json.Post <HttpMessage <UserWithRole>, UserUid>(AppSettings.AccountService.Server, AppSettings.AccountService.ApiAccount + "/loginCheck", uu);
                    user = postResult?.Data;
                }
                else
                {
                    user = (principal.User as UserWithRole);
                }

                if (principal == null && user != null && user.Id != 0)
                {
                    principal = new Principal(user);
                    AuthUserManager.LogIn(principal);
                }

                int userId = user.Id;
                int siteUserId = SetUserUid(uid, userId);

                bool Cms = user.Roles != null && user.Roles.Count > 0 && user.Roles.FirstOrDefault(f => f.Role == 1) != null;
                bool auth = user != null && user.Id != 0;
                string version = this.GetType().Assembly.GetCustomAttribute <AssemblyFileVersionAttribute>().Version;
                return CreateResponseOk(new UidResult()
                {
                    Version = version, Identity = new IdentityResult {
                        SiteUserId = siteUserId, Auth = auth, Cms = Cms, Token = principal == null ? "" : principal.GetKey(), User = user
                    }
                });
            }));
        });
Ejemplo n.º 8
0
        public object BeforeCall(string operationName, object[] inputs)
        {
            var msg = OperationContext.Current.RequestContext.RequestMessage.ToString();



            int index = OperationContext.Current.IncomingMessageHeaders.FindHeader("UserName", Ns);

            if (index != -1)
            {
                string userName = OperationContext.Current.IncomingMessageHeaders.GetHeader <string>("UserName", Ns);
                string password = OperationContext.Current.IncomingMessageHeaders.GetHeader <string>("Password", Ns);

                if (AuthUserManager.CheckUser(userName, password))
                {
                    return(null);
                }
            }

            Dev.Log.Loger.Error("非法调用" + operationName + "\r\n" + this.GetHeaders());

            throw new UnauthorizedAccessException(operationName + "未经授权的调用");
        }
Ejemplo n.º 9
0
        public override void Validate(string userName, string password)
        {
            // validate arguments
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException("userName");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }

            // check the user credentials from database
            //int userid = 0;
            //CheckUserNameAndPassword(userName, password, out userid);
            //if (0 == userid)
            //    throw new SecurityTokenException("Unknown username or password");

            if (!AuthUserManager.CheckUser(userName, password))
            {
                throw new SecurityTokenException("Unknown username or password");
            }
        }
Ejemplo n.º 10
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            IList<string> roles;
            IList<Claim> claims;

            var appAuthContext = AuthContext.Create();
            using (AuthUserManager authUserManager = new AuthUserManager(new UserStore<AuthUser>(appAuthContext)))
            {
                IdentityUser user = await authUserManager.FindAsync(context.UserName, context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect");
                    return;
                }
                else
                {
                    roles = await authUserManager.GetRolesAsync(user.Id);
                    claims = await authUserManager.GetClaimsAsync(user.Id);
                }
            }
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));

            foreach (string role in roles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
            }

            foreach(Claim claim in claims)
            {
                identity.AddClaim(claim);
            }

            context.Validated(identity);
        }
Ejemplo n.º 11
0
 public ManageController(AuthUserManager userManager, AuthSignInManager signInManager)
 {
     UserManager   = userManager;
     SignInManager = signInManager;
 }
Ejemplo n.º 12
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_userManager != null)
                {
                    _userManager.Dispose();
                    _userManager = null;
                }

                if (_signInManager != null)
                {
                    _signInManager.Dispose();
                    _signInManager = null;
                }
            }

            base.Dispose(disposing);
        }
Ejemplo n.º 13
0
 public AuthModelFactory(HttpRequestMessage request, AuthUserManager authUserManager)
 {
     _urlHelper = new UrlHelper(request);
     _authUserManager = authUserManager;
 }
Ejemplo n.º 14
0
 public SubscriptionController(AuthUserManager userManager, ISubscriptionRepository subscriptionRepository)
 {
     _userManager = userManager;
     _subscriptionRepository = subscriptionRepository;
 }
Ejemplo n.º 15
0
        //[Route("Register")]

        //public async Task<IHttpActionResult> Register(UserModel userModel)
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        return BadRequest(ModelState);
        //    }

        //    IdentityResult result = await _repo.RegisterUser(userModel.UserName, userModel.Password, userModel.Email);

        //    IHttpActionResult errorResult = GetErrorResult(result);

        //    if (errorResult != null)
        //    {
        //        return errorResult;
        //    }

        //    return Ok();
        //}

        public AccountController(AuthUserManager userManager,
                                 ISecureDataFormat <AuthenticationTicket> accessTokenFormat)
        {
            //UserManager = userManager;
            //AccessTokenFormat = accessTokenFormat;
        }
Ejemplo n.º 16
0
 public AccountController()
 {
     _aum = new AuthUserManager();
 }
Ejemplo n.º 17
0
 public UsersController(AuthUserManager userManager)
 {
     _userManager = userManager;
 }