public IActionResult CheckToken([FromBody] TokenDto token)
        {
            JwtSecurityTokenHandler handler  = new JwtSecurityTokenHandler();
            JwtSecurityToken        jwtToken = handler.ReadJwtToken(token.Token);
            SecurityToken           securityToken;

            string        id    = jwtToken.Claims.Where(x => x.Type == ClaimTypes.Name).Select(x => x.Value).FirstOrDefault();
            List <string> roles = jwtToken.Claims.Where(x => x.Type == ClaimTypes.Role).Select(x => x.Value).ToList();

            try
            {
                handler.ValidateToken(token.Token, validationParameters.GetTokenValidationParameters(), out securityToken);
            }
            catch (Exception ex)
            {
                ClaimsIdentity claimsIdentity = getClaimsIdentity(id, roles);

                return(Ok(new
                {
                    id,
                    roles,
                    token = getJwtToken(claimsIdentity)
                }));
            }

            return(Ok(new
            {
                id,
                roles,
                token
            }));
        }
Пример #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <DataContext>(x => x.UseInMemoryDatabase("TestDb"));

            services.AddCors();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserOnly", policy => policy.RequireRole("User"));
            });

            ValidationTokenParameters validationParameters = new ValidationTokenParameters(Configuration);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = false;
                options.TokenValidationParameters = validationParameters.GetTokenValidationParameters();
            });

            services.AddMvc();

            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <UserDto, User>().ForMember(m => m.Roles, opt => opt.Ignore());
                cfg.CreateMap <SingleItemDto, Item>();
            });

            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ISteamIdConverter, SteamIdConverter>();
            services.AddSingleton(Configuration);
            services.AddScoped <HttpClient>();
            services.AddSingleton(validationParameters);
            services.AddScoped <IAdminItemsService, AdminItemsService>();
            services.AddScoped <IItemsService, ItemsService>();
        }