/// <summary>
    /// Retrieves a new token from Webtrends auth service
    /// </summary>
    public string Execute()
    {
        var builder = new JWTBuilder();
        var header = new JWTHeader
        {
            Type = "JWT",
            Algorithm = "HS256"
        };
        var claimSet = new JWTClaimSet
        {
            Issuer = clientId,
            Principal = clientId,
            Audience = audience,
            Expiration = DateTime.Now.AddSeconds(30),
            Scope = scope
        };

        string assertion = builder.BuildAssertion(header, claimSet, clientSecret);
        var client = new RestClient(authUrl);
        var request = new RestRequest("token/", Method.POST);
        request.AddParameter("client_id", clientId);
        request.AddParameter("client_assertion", assertion);
        request.AddParameter("grant_type", "client_credentials");
        request.AddParameter("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");

        var response = client.Execute(request).Content;
        return (string)JObject.Parse(response)["access_token"];
    }
示例#2
0
        public async Task Execute(RequestDelegate next, HttpContext context, ArgonautOptions options)
        {
            var username   = context.Request.Form["username"];
            var password   = context.Request.Form["password"];
            var audienceId = context.Request.Form["audience"];

            var userValidation = options.ValidateUser.Invoke(username, password, audienceId); //Passback ArgonautUser, which should include audience.

            if (!userValidation.Validated)
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;

                var msg = "";
                if (!string.IsNullOrEmpty(userValidation.ValidationFailureUserMessage))
                {
                    msg = userValidation.ValidationFailureUserMessage;
                }
                else
                {
                    msg = "Invalid username, password, or audience.";
                }

                await context.Response.WriteAsync(msg);

                return;
            }

            _jwtBuilder = JWTBuilder.New(userValidation.Audience);
            foreach (var c in userValidation.Claims)
            {
                _jwtBuilder.AddClaim(c);
            }

            await GenerateAccessToken(context, username, options);
        }
    /// <summary>
    /// Retrieves a new token from Webtrends auth service
    /// </summary>
    public string Execute()
    {
        var builder = new JWTBuilder();
        var header = new JWTHeader
        {
            Type = "JWT",
            Algorithm = "HS256"
        };
        var claimSet = new JWTClaimSet
        {
            Issuer = clientId,
            Principal = clientId,
            Audience = audience,
            Expiration = DateTime.Now.ToUniversalTime().AddSeconds(30),
            Scope = scope
        };

        string assertion = builder.BuildAssertion(header, claimSet, clientSecret);
        var client = new RestClient(authUrl);
        var request = new RestRequest("token/", Method.POST);
        request.AddParameter("client_id", clientId);
        request.AddParameter("client_assertion", assertion);
        request.AddParameter("grant_type", "client_credentials");
        request.AddParameter("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");

        var response = client.Execute(request).Content;
        return (string)JObject.Parse(response)["access_token"];
    }
        public static void Entry(IServiceCollection services, IConfiguration configuration)
        {
            //Doitsu.Identity.DBConStr
            #region Main Database Config
            // Config identity db config
            services.AddDbContext <ResoIdentityDbContext>(options =>
                                                          options.UseSqlServer(configuration.GetConnectionString("UniLogDB")));

            services.AddIdentity <ResoUserInt, IdentityRole <int> >()
            .AddEntityFrameworkStores <ResoIdentityDbContext>()
            .AddDefaultTokenProviders();

            services.AddScoped(typeof(DbContext), typeof(ResoIdentityDbContext));
            services.AddScoped(typeof(ResoUserIntManager));
            services.AddScoped(typeof(IUnitOfWork), typeof(UnitOfWork));

            JWTBuilder.BuildJWTService(services);
            #endregion

            #region DI Config

            #endregion

            //#region Mapper Config
            //var autoMapperConfig = new MapperConfiguration(cfg => {
            //    cfg.CreateMissingTypeMaps = true;
            //});
            //IMapper mapper = autoMapperConfig.CreateMapper();
            //services.AddSingleton(mapper);
            //#endregion
        }
示例#5
0
        public async Task <IActionResult> Register([FromBody] RegisterDetails details)
        {
            var u = await this._usersService.FindByEmail(details.Email);

            if (u != null)
            {
                return(BadRequest(new { Message = "Korisnik već postoji." }));
            }

            Models.User user = new Models.User()
            {
                CompanyName      = details.CompanyName,
                Email            = details.Email,
                ClientId         = Guid.NewGuid().ToString("N").ToLower(),
                Contact          = details.Contact,
                IsEmailConfirmed = false,
                Password         = SecurityUtils.EncryptPassword(details.Password),
                Phone            = details.Phone,
                Roles            = new string[] { "User" }
            };

            Models.User createdUser = await _usersService.CreateNew(user);

            if (createdUser == null)
            {
                _logger.LogInformation($"Could not register ({details.Email})");
                return(StatusCode(400, new { Message = "Došlo je do pogreške" }));
            }
            JWTBuilder jwtBuild   = new JWTBuilder(createdUser.Email, createdUser.ClientId, _jwtOptions, createdUser.Roles);
            string     encodedJwt = jwtBuild.GetJWT();

            var userProfile = new
            {
                ClientId = createdUser.ClientId,
                Email    = createdUser.Email
            };

            // Serialize and return the response
            var tokenWrapper = new
            {
                token = encodedJwt,
                user  = userProfile
            };

            //Response.Cookies.Append(
            //  "refreshToken",
            //  "testRefreshTokenContent",
            //  new CookieOptions()
            //  {
            //    HttpOnly = true
            //  });

            var json = JsonConvert.SerializeObject(tokenWrapper, _serializerSettings);

            return(Ok(tokenWrapper));
        }
示例#6
0
 public static void Entry(IServiceCollection services, IConfiguration configuration)
 {
     services.AddDbContext <NesopsAuthorizeDbContext>(options => options.UseMySql(configuration.GetConnectionString("NesopsAuthorizeDB")));
     services.AddScoped(typeof(DbContext), typeof(NesopsAuthorizeDbContext));
     services.AddScoped(typeof(NesopsUserManager));
     services.AddIdentity <NesopsUser, NesopsRole>()
     .AddEntityFrameworkStores <NesopsAuthorizeDbContext>();
     services.AddHttpContextAccessor();
     services.AddScoped(typeof(SignInManager <NesopsUser>));
     JWTBuilder.BuildJWTService(services);
     AMC.Configure();
     services.AddScoped(typeof(AuthorizeService));
 }
示例#7
0
        public JwtController(IOptions <JwtIssuerOptions> jwtOptions,
                             ILoggerFactory loggerFactory,
                             UsersService usersService)
        {
            _usersService = usersService;
            _jwtOptions   = jwtOptions.Value;
            JWTBuilder.ThrowIfInvalidOptions(_jwtOptions);

            _logger = loggerFactory.CreateLogger <JwtController>();

            _serializerSettings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented
            };
        }
 public static void Entry(IServiceCollection services, IConfiguration configuration)
 {
     services.AddScoped(typeof(DbContext), typeof(Mya2billingContext));
     JWTBuilder.BuildJWTService(services);
     #region Auto Mapper Config
     services.AddAutoMapper(typeof(BaseMappingProfile).GetTypeInfo().Assembly);
     #endregion
     #region Config Validator
     // FluentValidation read on class extend AbstractValidator
     var types = typeof(BaseCreateModelValidator).Assembly.GetTypes();
     new AssemblyScanner(types).ForEach(pair => {
         services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType));
     });
     #endregion
     services.AddScoped(typeof(AuthorizeService));
     //services.AddTransient<IValidator<VoucherGenerateModel>, VoucherGenerateModelValidator>();
 }
示例#9
0
        public async Task <IActionResult> Get([FromBody] ApplicationUser applicationUser)
        {
            var userFound = await this._usersService.FindByEmailPassword(applicationUser.Email, applicationUser.Password);

            if (userFound == null)
            {
                _logger.LogInformation($"Invalid username ({applicationUser.Email}) or password ({applicationUser.Password})");
                return(StatusCode(422, new { Message = "Neispravna email adresa ili lozinka" }));
            }

            JWTBuilder jwtBuild   = new JWTBuilder(userFound.Email, userFound.ClientId, _jwtOptions, userFound.Roles);
            string     encodedJwt = jwtBuild.GetJWT();

            var userProfile = new
            {
                ClientId = userFound.ClientId,
                Email    = userFound.Email
            };

            // Serialize and return the response
            var tokenWrapper = new
            {
                token = encodedJwt,
                user  = userProfile
            };

            //Response.Cookies.Append(
            //  "refreshToken",
            //  "testRefreshTokenContent",
            //  new CookieOptions()
            //  {
            //    HttpOnly = true
            //  });

            var json = JsonConvert.SerializeObject(tokenWrapper, _serializerSettings);

            return(Ok(tokenWrapper));
        }
示例#10
0
        public async Task Execute(RequestDelegate next, HttpContext context, ArgonautOptions options)
        {
            var rtFromRequest        = context.Request.Form["refresh_token"];
            var hashedRefreshTokenId = Argonaut.Internal.Hashing.GetHash(rtFromRequest);

            var persistenceResponse = options.RefreshAccessToken(hashedRefreshTokenId); //Client returns refresh token model with encrpted ticket.

            if (persistenceResponse == null)
            {
                await RespondRefreshTokenInvalid(context);

                return;
            }

            if (persistenceResponse.RefreshToken == null)
            {
                await RespondRefreshTokenInvalid(context);

                return;
            }

            if (persistenceResponse.Audience == null)
            {
                await RespondRefreshTokenInvalid(context);

                return;
            }

            //Map to domain refresh token
            Domain.RefreshToken rt = Domain.RefreshToken.New(
                persistenceResponse.RefreshToken.Id,
                persistenceResponse.RefreshToken.Subject,
                persistenceResponse.RefreshToken.AudienceId,
                persistenceResponse.RefreshToken.ProtectedTicket,
                persistenceResponse.RefreshToken.IssuedUtc,
                persistenceResponse.RefreshToken.ExpiresUtc
                );

            var nowUtc = DateTime.UtcNow; //TODO: Could do with moving to interface

            if (nowUtc > rt.ExpiresUtc)
            {
                await RespondRefreshTokenInvalid(context);

                return;
            }

            try {
                rt.DecryptTicket(_encryptor, rtFromRequest.ToString());
            } catch {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("Persisted refresh token failed decryption - Log in using username and password.");

                return;
            }

            if (rt.ProtectedTicket == null)
            {
                await RespondRefreshTokenInvalid(context);

                return;
            }

            var vp      = new JWTValidationParametersGenerator(persistenceResponse.Audience).SecretOnly();
            var handler = new JwtSecurityTokenHandler();

            Microsoft.IdentityModel.Tokens.SecurityToken validatedToken = null;
            try {
                handler.ValidateToken(rt.ProtectedTicket, vp, out validatedToken);
            } catch {
                await RespondRefreshTokenInvalid(context);

                return;
            }

            if (validatedToken == null)
            {
                await RespondRefreshTokenInvalid(context);

                return;
            }

            var jwt         = validatedToken as System.IdentityModel.Tokens.Jwt.JwtSecurityToken;
            var sub         = jwt.Claims.Where(l => l.Type == "sub").FirstOrDefault().Value;
            var claimsToUse = jwt.Claims.ExcludeDefaultAccessTokenClaims();

            _jwtBuilder = JWTBuilder.New(persistenceResponse.Audience);
            _jwtBuilder.AddClaims(claimsToUse);

            await GenerateAccessToken(context, sub, options);
        }
示例#11
0
 public JWTRESTClient(string secret)
 {
     this.Client = new HttpClient();
     JWTTocken   = JWTBuilder.Build(Payload, secret);
 }
示例#12
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     #region Authorization Config
     JWTBuilder.BuildJWTService(services);
     #endregion
     services.AddDbContext <NesopsMonitorContext>(options => options.UseSqlServer(Configuration.GetConnectionString("NesopsMonitorDB")));
     #region
     ServiceRootConfig.Entry(services, Configuration);
     #endregion
     services.AddSwaggerGen(c =>
     {
         c.SwaggerDoc("nesopsmonitor", new OpenApiInfo
         {
             Version     = "v1",
             Title       = "Nesops Monitor Swagger Docs",
             Description = "Nesops Swagger for Monitor Services",
             Contact     = new OpenApiContact
             {
                 Name  = "LuanDNH",
                 Email = "*****@*****.**",
                 Url   = new Uri("https://www.facebook.com/luandnh98")
             },
             TermsOfService = new Uri("http://nesops.xyz"),
             License        = new OpenApiLicense
             {
                 Name = "Use under LICX",
                 Url  = new Uri("http://nesops.xyz")
             }
         });
         c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
         {
             In          = ParameterLocation.Header,
             Description = "Please insert JWT with Bearer into field",
             Name        = "Authorization",
             Type        = SecuritySchemeType.ApiKey,
             Scheme      = "Bearer"
         });
         c.AddSecurityRequirement(new OpenApiSecurityRequirement
         {
             {
                 new OpenApiSecurityScheme
                 {
                     Reference = new OpenApiReference
                     {
                         Type = ReferenceType.SecurityScheme,
                         Id   = "Bearer"
                     },
                     Scheme = "oauth2",
                     Name   = "Bearer",
                     In     = ParameterLocation.Header
                 },
                 new List <string>()
             }
         });
         // Set the comments path for the Swagger JSON and UI.
         var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
         var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
         c.IncludeXmlComments(xmlPath);
     });
     services.AddCors(options =>
     {
         options.AddPolicy(MyAllowSpecificOrigins,
                           builder =>
         {
             builder.WithOrigins(NESOPSDOMAINS);
             builder.AllowAnyHeader();
             builder.AllowAnyMethod();
         });
     });
     services.AddControllersWithViews(options =>
     {
         options.Filters.Add(typeof(ValidatorActionFilter));
         //options.Filters.Add(typeof(CustomExceptionFilter));
     }).AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>());
 }