public HelpersManagementTests()
 {
     _helpersManagementService            = ServiceProvider.Instance.Resolve <IHelpersManagementService>();
     _accountManagementService            = ServiceProvider.Instance.Resolve <IAccountManagementService>();
     _helpersManagementService.RequestUri = RequestUriHelper.HelpersUri;
     _accountManagementService.RequestUri = RequestUriHelper.JwtTokenUri;
     _testingHelper = TestingObjectProvider.Instance.Helper;
     _token         = _accountManagementService.SignIn(TestingObjectProvider.Instance.Login).Result;
 }
 public PaymentsController(JwtToken jwtToken,
                           StripeEventHandlerService stripeEventHandlerService, IUserManagementService userManagementService,
                           StripePaymentService stripePaymentService)
 {
     _jwtToken = jwtToken;
     _stripeEventHandlerService = stripeEventHandlerService;
     _userManagementService     = userManagementService;
     _stripePaymentService      = stripePaymentService;
 }
Exemple #3
0
 public ProposalsManagementTests()
 {
     _proposalsManagementService            = ServiceProvider.Instance.Resolve <IProposalsManagementService>();
     _accountManagementService              = ServiceProvider.Instance.Resolve <IAccountManagementService>();
     _proposalsManagementService.RequestUri = RequestUriHelper.ProposalsUri;
     _accountManagementService.RequestUri   = RequestUriHelper.JwtTokenUri;
     _testingProposal = TestingObjectProvider.Instance.Proposal;
     _token           = _accountManagementService.SignIn(TestingObjectProvider.Instance.Login).Result;
 }
Exemple #4
0
 public void SaveToken(string token)
 {
     Token          = JwtToken.Process(token);
     _context.Token = Token.RawToken;
     _context.Id    = Token.Id;
     //TODO: This will be null.
     _context.Email      = Token.Email;
     _context.IsLoggedIn = true;
 }
Exemple #5
0
 public async Task SignOut()
 {
     _httpClient.DefaultRequestHeaders.Remove(AuthorizationHeader);
     JwtToken        = null;
     IsAuthenticated = false;
     CurrentUser     = null;
     _sessionStorage.RemoveItem(JhiAuthenticationtoken);
     NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
 }
 public CommentsManagementTests()
 {
     _commentsManagementService              = ServiceProvider.Instance.Resolve <ICommentsManagementService>();
     _accountManagementService               = ServiceProvider.Instance.Resolve <IAccountManagementService>();
     _commentsManagementService.RequestUri   = RequestUriHelper.CommentsUri;
     _accountManagementService.RequestUriJwt = RequestUriHelper.JwtTokenUri;
     _testingComment = TestingObjectProvider.Instance.Comment;
     _token          = _accountManagementService.SignIn(TestingObjectProvider.Instance.Login).Result;
 }
Exemple #7
0
 public UserManagementTest()
 {
     _userManagementService                  = ServiceProvider.Instance.Resolve <IUsersManagementService>();
     _accountManagementService               = ServiceProvider.Instance.Resolve <IAccountManagementService>();
     _userManagementService.RequestUri       = RequestUriHelper.UsersUri;
     _accountManagementService.RequestUriJwt = RequestUriHelper.JwtTokenUri;
     _testUser = TestingObjectProvider.Instance.User;
     _token    = _accountManagementService.SignIn(TestingObjectProvider.Instance.Login).Result;
 }
 public NewsManagementTest()
 {
     _newsManagementService                  = ServiceProvider.Instance.Resolve <INewsManagementService>();
     _accountManagementService               = ServiceProvider.Instance.Resolve <IAccountManagementService>();
     _newsManagementService.RequestUri       = RequestUriHelper.NewsUri;
     _accountManagementService.RequestUriJwt = RequestUriHelper.JwtTokenUri;
     _testingNews = TestingObjectProvider.Instance.News;
     _token       = _accountManagementService.SignIn(TestingObjectProvider.Instance.Login).Result;
 }
Exemple #9
0
        public async Task <IActionResult> LoginByUsernameAsync([FromBody] LoginByUsernameViewModelRequest login)
        {
            ViewModelResponse <LoginViewModelResponse> viewModelResponse = new ViewModelResponse <LoginViewModelResponse>()
            {
                Success      = false,
                ErrorMessage = string.Empty,
                ErrorCode    = string.Empty
            };

            User     user     = null;
            JwtToken jwtToken = null;
            string   name     = string.Empty;
            string   role     = string.Empty;
            string   issuer   = string.Empty;
            string   audience = string.Empty;
            string   key      = string.Empty;
            int      expires  = 0;

            try
            {
                // Get user by username and password
                user = await _userService.GetByUsernameAsync(login.Username, login.Password);

                // Validate if the user exists
                if (user == null)
                {
                    viewModelResponse.ErrorMessage = CoreConstant.MESSAGE_USERNAME_PASSWORD_INVALID;
                    viewModelResponse.ErrorCode    = CoreConstant.CODE_USERNAME_PASSWORD_INVALID;
                    return(BadRequest(viewModelResponse));
                }

                // Set values for create token
                name     = user.Username;
                role     = user.UserRoles.FirstOrDefault().Role.Denomination;
                issuer   = _configuration["Tokens:Issuer"];
                audience = _configuration["Tokens:Issuer"];
                key      = _configuration["JWT:Key"];
                expires  = int.Parse(_configuration["Jwt:Expires"]);

                // Get token
                jwtToken = await _jwtTokenService.GenerateTokenAsync(name, role, issuer, audience, expires, key);

                if (jwtToken == null)
                {
                    viewModelResponse.ErrorMessage = CoreConstant.MESSAGE_TOKEN_INVALID;
                    viewModelResponse.ErrorCode    = CoreConstant.CODE_TOKEN_INVALID;
                    return(BadRequest(viewModelResponse));
                }

                await _jwtTokenService.AddAsync(jwtToken);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(Ok(viewModelResponse));
        }
Exemple #10
0
 public OrganizationInfoManagementTest()
 {
     _organizationInfoManagementService            = ServiceProvider.Instance.Resolve <IOrganizationManagementService>();
     _accountManagementService                     = ServiceProvider.Instance.Resolve <IAccountManagementService>();
     _organizationInfoManagementService.RequestUri = RequestUriHelper.OrganizationInfoUri;
     _accountManagementService.RequestUri          = RequestUriHelper.JwtTokenUri;
     _testingOrganization = TestingObjectProvider.Instance.Organization;
     _token = _accountManagementService.SignIn(TestingObjectProvider.Instance.Login).Result;
 }
Exemple #11
0
        public async Task <bool> DepositAccount(AccountRequest request)
        {
            string uri      = configuration["proxy:urlAccountDeposit"];
            string token    = "Bearer " + JwtToken.Create(jwtOption);
            var    response = await httpClient.PostAsync(uri, request, token);

            response.EnsureSuccessStatusCode();
            return(true);
        }
Exemple #12
0
        public async Task <MessageModel <dynamic> > TokenAssig([FromBody] LoginViewModel loginViewModel)
        {
            var data = new MessageModel <dynamic>();

            if (ModelState.IsValid)
            {
                loginViewModel.Password = loginViewModel.Password.ToMD5();
                SysUser Info = await _userserver.CheckUser(loginViewModel.User, loginViewModel.Password);

                await _schedulerCenter.AddScheduleJobAsync(new SysSchedule
                {
                    Name           = "test1",
                    JobGroup       = "test1group",
                    AssemblyName   = "Uwl.QuartzNet.JobCenter",
                    ClassName      = "Simple",
                    IntervalSecond = 5,
                });

                //_rabbitMQ.SendData("hello", Info);
                if (Info == null)
                {
                    data.msg = "账号或者密码错误";
                    return(data);
                }
                else
                {
                    try
                    {
                        //_schedulerCenter.AddScheduleJobAsync<SysSchedule>(new SysSchedule());
                        var RoleName = await _userserver.GetUserRoleByUserId(Info.Id);

                        var claims = new List <Claim>
                        {
                            new Claim(ClaimTypes.Name, Info.Name),                                                                      //设置用户名称
                            new Claim(JwtRegisteredClaimNames.Jti, Info.Id.ToString()),                                                 //设置用户ID
                            new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()), //设置过期时间
                        };
                        claims.AddRange(RoleName.Split(',').Select(x => new Claim(ClaimTypes.Role, x)));                                //将用户角色填充到claims中
                        //用户标识
                        var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                        identity.AddClaims(claims);
                        var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
                        data.response = token;
                        data.msg      = "Token获取成功";
                        data.success  = true;
                        return(data);
                    }
                    catch (Exception ex)
                    {
                        data.msg = "获取角色信息失败" + ex.Message;
                        return(data);
                    }
                }
            }
            data.msg = "账号或者密码错误";
            return(data);
        }
        public async Task InvokeAsync(HttpContext context, JwtToken jwtToken)
        {
            jwtToken.UserId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            context.Request.Headers.TryGetValue("Authorization", out var accessToken);

            jwtToken.AccessToken = accessToken;

            await _next(context);
        }
        public async Task <MessageModel <dynamic> > TokenAssig([FromBody] LoginViewModel loginViewModel)
        {
            var FromMailAddres = Appsettings.app(new string[] { "FromMailConfig", "FromMailAddres" });
            var FromMailPwd    = Appsettings.app(new string[] { "FromMailConfig", "FromMailPwd" });
            var ToMail         = Appsettings.app(new string[] { "FromMailConfig", "ToMail" });
            //await SendEmail.SendMailAvailableAsync(FromMailAddres, FromMailPwd, ToMail, $"{ DateTime.Now.ToString("yyyy-MM-dd")}Redis超出限制错误", "测试发送邮件抄送功能");//new string[] { "*****@*****.**" }
            var data  = new MessageModel <dynamic>();
            var cheke = loginViewModel.CheckModel();

            if (cheke.Item1)
            {
                loginViewModel.Password = loginViewModel.Password.ToMD5();
                var Ip = HttpContext.GetClientIP();
                //await Console.Out.WriteAsync($"IP为【{Ip}】的客户机访问");
                SysUser Info = await _userserver.CheckUser(loginViewModel.User, loginViewModel.Password);

                if (Info == null)
                {
                    data.msg = "账号或者密码错误";
                    return(data);
                }
                else
                {
                    try
                    {
                        var RoleName = await _userserver.GetUserRoleByUserId(Info.Id);

                        var claims = new List <Claim>
                        {
                            new Claim(ClaimTypes.Name, Info.Name),                                                                      //设置用户名称
                            new Claim(JwtRegisteredClaimNames.Jti, Info.Id.ToString()),                                                 //设置用户ID
                            new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()), //设置过期时间
                            new Claim("Id", Info.Id.ToString()),
                            new Claim("userName", Info.Name)
                        };
                        claims.AddRange(RoleName.Split(',').Select(x => new Claim(ClaimTypes.Role, x))); //将用户角色填充到claims中
                        var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);       //用户标识
                        identity.AddClaims(claims);
                        var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
                        data.response = token;
                        data.msg      = "Token获取成功";
                        data.success  = true;
                        return(data);
                    }
                    catch (Exception ex)
                    {
                        data.msg = "获取角色信息失败" + ex.Message;
                        return(data);
                    }
                }
            }
            else
            {
                data.msg = cheke.Item2;
                return(data);
            }
        }
Exemple #15
0
        public async Task <ActionResult <JwtToken> > Login([FromBody] DTO.LoginModel loginModel)
        {
            // Depuis ASP.NET Core 2.1, ces deux lignes sont superflues.
            // En effet, le framework prend en charge le retour d'une erreur 400
            // incluant le détail de cette dernière si la validation ne s'est pas bien déroulée.
            // Il est possible de désactiver ce mode de fonctionnement. Pour plus d'informations, voir https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.1#automatic-http-400-responses
            // if (!ModelState.IsValid)
            //     return BadRequest(ModelState);

            var repository = new AuthenticationRepository();

            Model.User userFound = repository.GetUsers().FirstOrDefault(user => user.UserName == loginModel.UserName && user.Password == loginModel.Password);
            if (userFound == null)
            {
                return(Unauthorized());
            }

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, userFound.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat,
                          ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(),
                          ClaimValueTypes.Integer64),
                new Claim(PrivateClaims.UserId, userFound.Id.ToString())
            };

            // rappel: le token est configurable. On y ajoute ce que l'on veut comme claims!
            // un ensemble de nom de claims est "réservé" (voir JwtRegisteredClaimNames)
            // le reste est utilisable à loisir! Voir classe PrivateClaims par exemple.
            if (userFound.Roles != null)
            {
                userFound.Roles.ToList().ForEach(roleName =>
                                                 claims.Add(new Claim("roles", roleName)));
            }

            //IEnumerable<string> roles = await _userManager.GetRolesAsync(user);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: _jwtOptions.NotBefore,
                expires: _jwtOptions.Expiration,
                signingCredentials: _jwtOptions.SigningCredentials
                );
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(token);

            // Sérialisation et retour
            var response = new JwtToken
            {
                access_token = encodedJwt,
                expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
            };

            return(Ok(response));
        }
 public PetsManagementTest()
 {
     _petsManagementService                  = ServiceProvider.Instance.Resolve <IPetsManagementService>();
     _accountManagementService               = ServiceProvider.Instance.Resolve <IAccountManagementService>();
     _petsManagementService.RequestUri       = RequestUriHelper.PetsUri;
     _accountManagementService.RequestUriJwt = RequestUriHelper.JwtTokenUri;
     _testingPet = TestingObjectProvider.Instance.Pet;
     _token      = _accountManagementService.SignIn(TestingObjectProvider.Instance.Login).Result;
 }
        protected override async Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
        {
            var options            = Options;
            var tvps               = options.TokenValidationParameters;
            var signingKey         = tvps.IssuerSigningKey;
            var handler            = new JwtSecurityTokenHandler();
            var newTokenExpiration = DateTime.Now.Add(options.ExpireTimeSpan);
            // TODO 优化第三方登录是绑定或创建用户
            var appUser = await _userService.GetOrCreateUserAsync(user, properties, options.CreateUserOnOAuthLogin);

            var identity = new ClaimsIdentity(new[]
            {
                new Claim(OAuthSignInAuthenticationDefaults.Sub, appUser.ID.ToString()),
                new Claim(OAuthSignInAuthenticationDefaults.UniqueName, appUser.Name),
                new Claim(OAuthSignInAuthenticationDefaults.Lang, CultureInfo.CurrentCulture.ToString())
            }, properties.Items["scheme"]);

            var securityToken = handler.CreateToken(new SecurityTokenDescriptor()
            {
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                Subject            = identity,
                Expires            = newTokenExpiration,
                Issuer             = tvps.ValidateIssuer ? tvps.ValidIssuer : null,
                Audience           = tvps.ValidateAudience ? tvps.ValidAudience : null,
            });

            var tokenValue = handler.WriteToken(securityToken);

            var encodedToken = "Bearer " + tokenValue;
            var u            = appUser as IUser;

            var jwtToken = new JwtToken
            {
                Token    = encodedToken,
                Expires  = newTokenExpiration,
                UserInfo = new UserInfo
                {
                    Avatar      = u?.Avatar,
                    Sex         = u?.Sex.ToInt(),
                    Name        = u?.Name,
                    DisplayName = u?.DisplayName,
                    ID          = u?.ID.ToString()
                }
            };

            Context.Features[typeof(JwtToken)] = jwtToken;
            properties.Items[nameof(JwtToken)] = encodedToken;

            Response.Cookies.Append(options.TokenKey, encodedToken);

            var returnUrlKey = options.ReturnUrlKey;

            if (properties.Items.TryGetValue(returnUrlKey, out var returnUrl))
            {
                Response.Cookies.Append(returnUrlKey, returnUrl);
            }
        }
Exemple #18
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                var info = Configuration.GetSection("Swagger").Get <Info>();

                c.SupportedSubmitMethods(SubmitMethod.Get, SubmitMethod.Post, SubmitMethod.Put, SubmitMethod.Patch, SubmitMethod.Delete);
                c.ShowExtensions();
                c.SwaggerEndpoint(Configuration.GetValue <String>("Swagger:Endpoint"), info.Title);
                c.RoutePrefix   = String.Empty;
                c.DocumentTitle = info.Title;
                c.InjectStylesheet(Configuration.GetValue <String>("Swagger:Stylesheet"));
            });

            app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());

            app.Use(async(context, next) =>
            {
                string token = context.Request.Headers["Authorization"];
                if (!string.IsNullOrWhiteSpace(token) && (token = token.Split(' ').Last()).Length == 32)
                {
                    var config = (IConfiguration)AppDomain.CurrentDomain.GetData("Configuration");
                    context.Request.Headers["ClientAccessToken"] = token;

                    var dc     = new DefaultDataContextLoader().GetDefaultDc();
                    var userId = dc.Table <Agent>().FirstOrDefault(x => x.ClientAccessToken == token)?.UserId;

                    context.Request.Headers["Authorization"] = "Bearer " + JwtToken.GenerateToken(config, userId);
                }

                await next.Invoke();
            });
            app.UseAuthentication();

            app.UseMvc();

            AppDomain.CurrentDomain.SetData("DataPath", Path.Combine(env.ContentRootPath, "App_Data"));
            AppDomain.CurrentDomain.SetData("Configuration", Configuration);
            AppDomain.CurrentDomain.SetData("ContentRootPath", env.ContentRootPath);
            AppDomain.CurrentDomain.SetData("Assemblies", Configuration.GetValue <String>("Assemblies").Split(','));

            InitializationLoader loader = new InitializationLoader();

            loader.Env    = env;
            loader.Config = Configuration;
            loader.Load();
        }
Exemple #19
0
        public async Task <object> GetJwtToken3(string name = "", string pass = "")
        {
            string jwtStr = string.Empty;

            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pass))
            {
                return(new JsonResult(new
                {
                    Status = false,
                    message = "用户名或密码不能为空"
                }));
            }
            pass = MD5Helper.MD5Encrypt32(pass);
            var user = await _sysUserInfoServices.Query(d => d.uLoginName == name && d.uLoginPWD == pass);

            if (user.Count > 0)
            {
                var userRoles = await _sysUserInfoServices.GetUserRoleNameStr(name, pass);

                // 如果是基于用户,添加用户,如果是基于角色则添加角色
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, name),
                    new Claim(JwtRegisteredClaimNames.Jti, user.FirstOrDefault().uID.ToString()),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString())
                };
                claims.AddRange(userRoles.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));

                var data = await _roleModulePermissionServices.RoleModuleMaps();

                var list = (from item in data
                            where item.IsDeleted == false
                            orderby item.Id
                            select new PermissionItem
                {
                    Url = item.Module?.LinkUrl,
                    Role = item.Role?.Name,
                }
                            ).ToList();
                _requirement.Permissions = list;

                // 用户标识
                var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                identity.AddClaims(claims);
                var token = JwtToken.BuildJwtToken(claims.ToArray(), _requirement);
                return(new JsonResult(token));
            }
            else
            {
                return(new JsonResult(new
                {
                    success = false,
                    message = "认证失败"
                }));
            }
        }
Exemple #20
0
        public LoginResponse(JwtToken jwt)
        {
            if (jwt == null)
            {
                return;
            }

            AuthToken = jwt.AuthToken;
            ExpiresIn = jwt.ExpiresIn;
        }
        private JwtToken GetTenantId(string id_token)
        {
            string encodedOpenIdToken = id_token;

            string decodedToken = Base64UrlDecodeJwtTokenPayload(encodedOpenIdToken);

            JwtToken token = JsonConvert.DeserializeObject <JwtToken>(decodedToken);

            return(token);
        }
Exemple #22
0
        public void JwtTokenTest4()
        {
            var key   = Encoding.UTF8.GetBytes("616161A");
            var id    = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2p3dC1pZHAuZXhhbXBsZS5jb20iLCJzdWIiOiJtYWlsdG86bWlrZUBleGFtcGxlLmNvbSIsIm5iZiI6MTQ4Mzg3MjcyMSwiZXhwIjoxNDgzODc2MzIxLCJpYXQiOjE0ODM4NzI3MjEsImp0aSI6ImlkMTIzNDU2IiwidHlwIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9yZWdpc3RlciJ9.bMdGRvtLXSzZvF_3vlJ1T8DQ_Uc6AOa0Fr9-p8pU3UI";
            var token = new JwtToken(id, null, false);

            var result = token.ValidateIncoming(key);

            token.Claims.IssuedAt = DateTime.UtcNow;
        }
Exemple #23
0
        /// <summary>
        /// Sets the token to use from storage and sets it to be used by API
        /// </summary>
        private void SetValidTokenFromStorage()
        {
            this.Token = new JwtToken
            {
                Token      = this.Storage.GetStoreModel().Token.Token,
                Expiration = this.Storage.GetStoreModel().Token.Expiration
            };

            this.ApiInteractor.AddTokenToAuthorizationHeader(this.Token);
        }
Exemple #24
0
        internal EveToken(EveCredentials credential, JwtToken token, IScope scope)
        {
            Scope      = scope;
            Token      = token;
            Credential = credential;

            string[] subjectArray = Token.Subject.Split(':');
            Expiery = DateTime.Now + new TimeSpan(0, 0, int.Parse(credential.ExpiresIn));
            UserID  = int.Parse(subjectArray[2]);
        }
 public HotToHelpInfoManagementTests()
 {
     _howToHelpInformationService = ServiceProvider.Instance.Resolve <IHowToHelpInformationService>();
     _accountManagementService    = ServiceProvider.Instance.Resolve <IAccountManagementService>();
     _howToHelpInformationService.BecomeVolunteerUrl = RequestUriHelper.OrganizationInfoUri;
     _howToHelpInformationService.DonateInfoUrl      = RequestUriHelper.HowToHelpUri;
     _accountManagementService.RequestUri            = RequestUriHelper.JwtTokenUri;
     _testingObject = TestingObjectProvider.Instance.HowToHelpInfo;
     _token         = _accountManagementService.SignIn(TestingObjectProvider.Instance.Login).Result;
 }
Exemple #26
0
        public async Task <IActionResult> GetToken([FromBody] JwtToken jwtToken)
        {
            var jwt   = jwtToken;
            var token = JwtHelper.IssueJWT(jwt, TimeSpan.FromMinutes(30));

            return(Ok(new
            {
                token = token
            }));
        }
        public IActionResult getInforToken([FromBody] JwtToken jwtToken)
        {
            var inforToken = _context.JwtTokens.Where(jwt => jwt.token == jwtToken.token && jwt.refresh_token == jwtToken.refresh_token).FirstOrDefault();

            if (inforToken == null)
            {
                return(NotFound(new { message = "Invalid token" }));
            }
            return(Ok(inforToken));
        }
Exemple #28
0
        public static async Task <UserResponse> ValidateCurrentToken(string token)
        {
            GoogleJsonWebSignature.Payload payload;
            payload = await GoogleJsonWebSignature.ValidateAsync(token, new GoogleJsonWebSignature.ValidationSettings
            {
                Audience = new[] { ClientId }
            });

            return(new UserResponse(payload.Name, payload.Email, JwtToken.GenerateToken(Guid.NewGuid()), JwtToken.GenerateRefreshToken()));
        }
        /// <summary>
        /// Registers a new user
        /// </summary>
        /// <param name="model">Register data</param>
        /// <returns></returns>
        public async Task RegisterAsync(RegisterModel model)
        {
            Logout();

            JwtToken token = await PostAsync <RegisterModel, JwtToken>(RegisterPath, model);

            await SetCredentialsAsync(model.Username, model.Password, token);

            Authenticated = true;
        }
Exemple #30
0
        public async Task <ApiResult <TokenInfoViewModel> > Login(string name = "", string pwd = "")
        {
            var r = new ApiResult <TokenInfoViewModel>();

            try
            {
                if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pwd))
                {
                    r.status = 400;
                    r.msg    = "账号或密码不能为空!";
                    return(r);
                }
                var user = await _userServices.GetEntity(t => t.UserName.Equals(name) && t.Password.Equals(MD5Helper.MD5Encrypt32(pwd)));

                if (user != null)
                {
                    var userRole = await _roleServices.GetList(_ => _.UserID == user.Id);

                    var role = string.Empty;
                    if (userRole != null && userRole.Any())
                    {
                        role = string.Join(",", userRole.Select(_ => _.RoleID).Distinct());
                    }
                    //创建声明数组
                    var claims = new Claim[] {
                        new Claim("uid", user.Id.ToString()),
                        new Claim(ClaimTypes.Name, user.UserName),
                        new Claim(ClaimTypes.Role, role),
                        new Claim(JwtRegisteredClaimNames.Email, user.Email)
                    };
                    var responseJson = JwtToken.BuildJwtToken(claims);
                    if (responseJson != null)
                    {
                        r.status = 200;
                        r.msg    = "登录成功!";
                        r.data   = responseJson;
                        new AuthHelper(_accessor, _redis).SaveCurrSessionAndUserRole(responseJson, new AuthModel()
                        {
                            UserID = user.Id, UserName = user.UserName, RoleIDs = userRole?.Select(_ => _.Id).Distinct().ToList() ?? new List <int>()
                        });
                    }
                }
                else
                {
                    r.status = 401;
                    r.msg    = "账号或密码错误!";
                }
            }
            catch (Exception ex)
            {
                r.status = 500;
                r.msg    = ex.Message;
            }
            return(r);
        }
        private string GenerateAuthorizationToken(string username)
        {
            var jwttoken = new JwtToken
            {
                Issuer = "http://feelknit.com",
                Audience = "http://feelknit-audience.com",
                Claims =
                    new List<Claim>(new[]
                    {
                        new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "User"),
                        new Claim(ClaimTypes.Name, username)
                    }),
                Expiry = DateTime.UtcNow.AddYears(10)
            };

            var token = _jwtWrapper.Encode(jwttoken, _configProvider.GetAppSetting("securekey"), JwtHashAlgorithm.HS256);
            return token;
        }