public UserController(
     UserManager <CyberSparrow> userManager,
     IUserHandler userHandler,
     JwtHandler jwtHandler,
     SignInManager <CyberSparrow> signInManager,
     RegistrationCodesHandler rch
     )
 {
     this.userManager   = userManager;
     this.userHandler   = userHandler;
     this.jwtHandler    = jwtHandler;
     this.signInManager = signInManager;
     this.rch           = rch;
 }
Esempio n. 2
0
        public static void SetupJwtConf(this IServiceCollection services, ref IConfiguration configuration)
        {
            var jwtOptions = services.GetTypedOptions <JwtOptions>(configuration, "JWT");

            if (jwtOptions == null)
            {
                return;
            }

            var jwtHandler = new JwtHandler(jwtOptions);

            services.AddSingleton <IJwtHandler>(jwtHandler);
            SetupJwtNetCore(services, jwtOptions, jwtHandler);
        }
Esempio n. 3
0
        public LoginResultDTO Login(LoginCredentialsDTO credentialsDTO)
        {
            var user = _userRepository.GetByEmail(credentialsDTO.Email);

            Validate.NotNull(user);

            var encryptedPassword = this.GenerateEncryptedPassword(credentialsDTO.Password);

            Validate.EqualThan(user.Password, encryptedPassword);

            var token = JwtHandler.GenerateToken(_tokenOptions.Value.SecretKey, user.Name, user.Id, user.IsAdmin);

            return(new LoginResultDTO(token));
        }
Esempio n. 4
0
        public async Task <UserModel?> TryGetUserAsync(string jwt, CancellationToken cancellationToken)
        {
            var tokenConfiguration = await fTokenConfigurationRepository.GetAsync(cancellationToken);

            var parameters = GetValidationParams(tokenConfiguration);

            var principal = JwtHandler.ValidateToken(jwt, parameters);

            if (principal is null)
            {
                return(null);
            }

            return(CreateModel(principal));
        }
Esempio n. 5
0
 public AccountService(
     IStoredProcedureService storedProcedure,
     RandomMaker randomMaker,
     Cryptograph cryptograph,
     IAccountProfileService accountProfileService,
     IAccountDeviceService accountDeviceService,
     JwtHandler jwtHandler)
 {
     _storedProcedure       = storedProcedure;
     _randomMaker           = randomMaker;
     _cryptograph           = cryptograph;
     _accountProfileService = accountProfileService;
     _accountDeviceService  = accountDeviceService;
     _jwtHandler            = jwtHandler;
 }
Esempio n. 6
0
        public async Task <IHttpActionResult> Login(UserModel model)
        {
            // validate user and password in DB
            var userId = 5;

            var claims = new List <Claim> {
                new Claim("name", model.UserName),
                new Claim("userId", userId.ToString())
            };

            var tokenString = JwtHandler.GetToken(claims, Request.BaseUrl());

            return(Ok(tokenString));
            //return Ok(ApiAuthorizationFilterAttribute.Bearer + tokenString);
        }
Esempio n. 7
0
        public async Task FTCreateAndValidateTest()
        {
            var testCertificate = await "CN=test1, O=Test".CreateSelfSignedCertificateAsync();
            var testKey         = await testCertificate.ToFTJsonWebKeyAsync(true);

            var issuer      = "test-issuer";
            var audience    = "test-aud";
            var token       = JwtHandler.CreateToken(testKey, issuer, new[] { audience }, new[] { new Claim("sub", "test-user") });
            var tokenString = await token.ToJwtString();

            (ClaimsPrincipal claimsPrincipal, MSTokens.SecurityToken securityToken) = JwtHandler.ValidateToken(tokenString, issuer, new[] { testKey }, audience: audience);

            Assert.True(claimsPrincipal?.Claims?.Count() > 1);
            Assert.NotNull(securityToken);
        }
Esempio n. 8
0
        public int ExractIdFromToken()
        {
            try {
                var token  = Request.Headers.FirstOrDefault(x => x.Key == "Authorization").Value.FirstOrDefault();
                int userId = 0;
                if (JwtHandler.IsTokenValid(token, out userId) == false)
                {
                    return(0);
                }

                return(userId);
            }
            catch (Exception ex) {
                return(1019);
            }
        }
        public async Task <BaseResponse> Login([FromBody] LoginRequest request)
        {
            var response = new BaseResponse();

            try
            {
                var user = await _usersRepository.GetByEmail(request.Email);

                var sha1         = new SHA1CryptoServiceProvider();
                var hashedString = Encoding.ASCII.GetString(
                    sha1.ComputeHash(
                        Encoding.ASCII.GetBytes(request.Email + request.Password)
                        )
                    );

                if (user == null || hashedString != user.Password)
                {
                    HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    response.Message = "Unauthorized.";
                    return(response);
                }

                var token = JwtHandler.GenerateToken(new JwtOptions
                {
                    Issuer       = _configuration["JwtSecurity:Issuer"],
                    Audience     = _configuration["JwtSecurity:Audience"],
                    SecretKey    = _configuration["JwtSecurity:SecretKey"],
                    PublicClaims = new Dictionary <string, string>(),
                    Id           = user.Id,
                    Subject      = "Authorization"
                });

                HttpContext.Response.Headers.Add("ACCESS-TOKEN", token.Token);
                HttpContext.Response.Headers.Add("ACCESS-TOKEN-EXPIRATION", token.ValidTo.ToString());

                response.Success = true;
                response.Message = "User logged in!";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                response.Message = "Failed to login.";
            }

            return(response);
        }
Esempio n. 10
0
        public async Task <UserLoginResponseDTO> Login(UserLoginDTO dto)
        {
            var user = await _userRepository.GetByEmail(dto.Email);

            Validate.NotNull(user, "User not found");

            var passwordIsValid = SecurityManager.VerifyPasswordPbkdf2(dto.Password, user.Password);

            Validate.IsTrue(passwordIsValid, "Password is incorrect");

            return(new UserLoginResponseDTO()
            {
                Name = user.Name,
                Email = user.Email,
                Token = JwtHandler.GenerateToken(_options.Value.SecretKey, user.Id, user.Name)
            });
        }
Esempio n. 11
0
 public Token Token(string token)
 {
     try
     {
         if (!string.IsNullOrEmpty(token))
         {
             return(JwtHandler.ReadToken(token));
         }
         else
         {
             throw new Exception("Bitte neu Anmelden Session Abgelaufen");
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Esempio n. 12
0
        public async Task MSCreateAndOidcDiscoveryValidateTest()
        {
            var testCertificate = await "CN=test1, O=Test".CreateSelfSignedCertificateAsync();
            var testKey         = await testCertificate.ToMSJsonWebKeyAsync(true);

            var issuer      = "test-issuer";
            var audience    = "test-aud";
            var token       = JwtHandler.CreateToken(testKey, issuer, new[] { audience }, new[] { new Claim("sub", "test-user") });
            var tokenString = await token.ToJwtString();

            var jsonWebKeySetAsJson = GetOidcDiscoveryJsonWebKeySet(testKey.ToFTJsonWebKey());
            var jsonWebKeySet       = jsonWebKeySetAsJson.ToObject <JsonWebKeySet>();

            (ClaimsPrincipal claimsPrincipal, MSTokens.SecurityToken securityToken) = JwtHandler.ValidateToken(tokenString, issuer, jsonWebKeySet.Keys.ToMSJsonWebKeys(), audience: audience);

            Assert.True(claimsPrincipal?.Claims?.Count() > 1);
            Assert.NotNull(securityToken);
        }
Esempio n. 13
0
        /// <summary>
        /// 常用自定义验证策略,模仿自定义中间件JwtCustomerauthorizeMiddleware的验证范围
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRequirement requirement)
        {
            var httpContext = accssor.HttpContext;

            //var httpContext = (context.Resource as AuthorizationFilterContext).HttpContext;

            #region 身份验证,并设置用户Ruser值

            var result = httpContext.Request.Headers.TryGetValue("Authorization", out StringValues authStr);
            if (!result || string.IsNullOrEmpty(authStr.ToString()))
            {
                return(Task.CompletedTask);
            }
            result = JwtHandler.Validate(authStr.ToString().Substring("Bearer ".Length).Trim(), payLoad =>
            {
                var success = true;
                //可以添加一些自定义验证,用法参照测试用例
                //验证是否包含aud 并等于 roberAudience
                success = success && payLoad["aud"]?.ToString() == jwtOption.Value.Audience;
                if (success)
                {
                    //设置Ruse值,把user信息放在payLoad中,(在获取jwt的时候把当前用户存放在payLoad的ruser键中)
                    //如果用户信息比较多,建议放在缓存中,payLoad中存放缓存的Key值
                    userContext.TryInit(payLoad["ruser"]?.ToString());
                }
                return(success);
            });
            if (!result)
            {
                return(Task.CompletedTask);
            }

            #endregion
            #region 权限验证
            if (!userContext.Authorize(httpContext.Request.Path))
            {
                return(Task.CompletedTask);
            }
            #endregion

            //context.Succeed(requirement);是验证成功,如果没有这个,就默认验证失败
            context.Succeed(requirement);
            return(Task.CompletedTask);
        }
Esempio n. 14
0
        public async Task <ClaimsPrincipal> ValidateAccessTokenAsync(string accessToken, string issuer, TParty party, string clientId)
        {
            (var validKeys, var invalidKeys) = party.Keys.GetValidKeys();
            try
            {
                (var claimsPrincipal, _) = await Task.FromResult(JwtHandler.ValidateToken(accessToken, issuer, validKeys, clientId, validateAudience: false));

                return(claimsPrincipal);
            }
            catch (Exception ex)
            {
                var ikex = GetInvalidKeyException(invalidKeys, ex);
                if (ikex != null)
                {
                    throw ikex;
                }
                throw;
            }
        }
Esempio n. 15
0
        public void ShouldCreateValidTokenWhenKeysAreValid()
        {
            var jwtSettingsMock = new Mock <IOptions <JwtSettings> >();
            var jwtSettings     = new JwtSettings();

            jwtSettings.Issuer        = "http://localhost:5000";
            jwtSettings.PrivateKeyXML = "private-key.xml";
            jwtSettings.PublicKeyXML  = "public-key.xml";

            jwtSettingsMock.Setup(j => j.Value).Returns(jwtSettings);

            var jwtHandler = new JwtHandler(jwtSettingsMock.Object);
            var token      = jwtHandler.Create(Guid.NewGuid().ToString());

            var tokenHandler = new JwtSecurityTokenHandler();
            var exception    = Record.Exception(() => tokenHandler.ValidateToken(token.Token, jwtHandler.Parameters, out _));

            Assert.Null(exception);
        }
Esempio n. 16
0
        public async Task <ActionResult> CreateUser(UserPartial iUser)
        {
            try
            {
                SignalRChatContext DB = new SignalRChatContext();

                using (var transaction = DB.Database.BeginTransaction())
                {
                    try
                    {
                        bool isExist = UserFunctions.CheckIfUserExist(iUser, DB);

                        if (isExist == true)
                        {
                            return(BadRequest());
                        }

                        UserCls newUser = UserFunctions.CreateNewUser(iUser, DB);
                        newUser.code = SignInCodesFucntions.GenerateCodeForUser(newUser.id, DB);

                        transaction.Commit();

                        newUser.token = JwtHandler.CreateJwt(newUser.id, newUser.userName, DateTime.Now);

                        await hubContext.Clients.All.AddUserEvent(newUser.id);

                        return(new JsonResult(newUser));
                    }
                    catch (Exception exc)
                    {
                        //write exc to log...
                        transaction.Rollback();
                        return(BadRequest());
                    }
                }
            }
            catch (Exception ex)
            {
                //write ex to log...
                return(BadRequest());
            }
        }
Esempio n. 17
0
        public void Token_Service_Generate_Tokens()
        {
            var secret  = Guid.NewGuid().ToString();
            var options = Options.Create <JwtOptions>(new JwtOptions {
                ExpiryMinutes = 2, Issuer = "JuntoSeguros", SecretKey = secret
            });

            var jwtProvider = new JwtHandler(options);

            var token = jwtProvider.Create("my_login", "my_name");

            Assert.NotNull(token);
            Assert.IsNotEmpty(token.Token);

            var decodedToken = jwtProvider.Decode(token.Token);

            Assert.NotNull(decodedToken);
            Assert.AreEqual(decodedToken.Login, "my_login");
            Assert.AreEqual(decodedToken.Name, "my_name");
        }
Esempio n. 18
0
        public async Task <ActionResult> LogIn(loginCls iLoginObj)
        {
            var userValidData = SignInCodesFucntions.ValidateCode(iLoginObj.phone, iLoginObj.code);

            if (userValidData == null)
            {
                return(BadRequest());
            }

            var token = JwtHandler.CreateJwt(userValidData.userId, userValidData.userName, DateTime.Now);

            UserCls res = UserFunctions.UserByPhoneAndCode(iLoginObj.phone, iLoginObj.code);

            res.token = token;
            res.id    = res.id; //id should not be returned. selected user should return dummy id or encrypted one.
            res.code  = null;

            await this.hubContext.Clients.All.AddUserEvent(res.id);

            return(new JsonResult(res));
        }
Esempio n. 19
0
        public AuthControllerIntegrationTests()
        {
            // Setup
            var options = new DbContextOptionsBuilder <DatabaseContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var dbContext       = new DatabaseContext(options);
            var userRepository  = new UserRepository(dbContext);
            var tokenRepository = new TokenRepository(dbContext);
            var jwtOptions      = Options.Create(new JwtSettings {
                Issuer = "Backend", Audience = "Users", SecretKey = "myXAuthenticationSecret"
            });
            var jwtHandler = new JwtHandler(jwtOptions);

            _authService = new AuthService(userRepository, jwtHandler, tokenRepository);

            _authService.Register(new RegisterRequestDTO {
                Username = "******", Password = "******", ClientId = "Test"
            });
        }
        public string GenerateUserJwt(UserDoc user, string grant)
        {
            var issuedAtUtc = DateTime.UtcNow;
            var claims      = new List <Claim>(8)
            {
                new Claim(Constants._NameClaim, user.Id.ToString()),
                new Claim(Constants._EmailClaim, user.Email),
                new Claim(Constants._GrantClaim, grant)
            };

            if (user.Username != null)
            {
                claims.Add(new Claim(Constants._UsernameClaim, user.Username));
            }
            if (user.GivenName != null)
            {
                claims.Add(new Claim(Constants._GivenNameClaim, user.GivenName));
            }
            if (user.FamilyName != null)
            {
                claims.Add(new Claim(Constants._FamilyNameClaim, user.FamilyName));
            }
            if (user.Admin)
            {
                claims.Add(new Claim(Constants._RoleClaim, nameof(UserModel.Admin)));
            }

            using var rsa = RSA.Create();
            var dto = new JwtSecurityTokenDto
            {
                Audience           = fConfig.BearerTokenAudience,
                Issuer             = fConfig.BearerTokenIssuer,
                Claims             = claims,
                NotBefore          = issuedAtUtc,
                Expires            = issuedAtUtc.AddSeconds(fConfig.BearerTokenDuration),
                SigningCredentials = rsa.ToSigningCredentials(fConfig.BearerPrivateKey)
            };

            return(JwtHandler.CreateToken(dto));
        }
Esempio n. 21
0
        public async Task <ClaimsPrincipal> ValidatePartyClientTokenAsync(TClient client, string token, bool validateLifetime = true)
        {
            var issuerSigningKeys = new List <JsonWebKey>();

            issuerSigningKeys.Add(RouteBinding.PrimaryKey.Key);
            if (RouteBinding.SecondaryKey != null)
            {
                issuerSigningKeys.Add(RouteBinding.SecondaryKey.Key);
            }

            try
            {
                (var claimsPrincipal, var securityToken) = await Task.FromResult(JwtHandler.ValidateToken(token, Issuer(RouteBinding), issuerSigningKeys, audience: client.ClientId, validateLifetime: validateLifetime));

                return(claimsPrincipal);
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"Party client JWT not valid. Client id '{client.ClientId}', Route '{RouteBinding.Route}'.");
                return(null);
            }
        }
Esempio n. 22
0
        public async Task <string> CreateIdTokenAsync(TClient client, IEnumerable <Claim> claims, IEnumerable <string> selectedScopes, string nonce, IEnumerable <string> responseTypes, string code, string accessToken, string algorithm)
        {
            if (!(client is OidcDownClient))
            {
                throw new InvalidOperationException("Include ID Token only possible for OIDC Down Client.");
            }

            var onlyIdToken   = !responseTypes.Contains(IdentityConstants.ResponseTypes.Code) && !responseTypes.Contains(IdentityConstants.ResponseTypes.Token);
            var idTokenClaims = new List <Claim>(await claimsDownLogic.FilterJwtClaimsAsync(client, claims, selectedScopes, includeIdTokenClaims: true, includeAccessTokenClaims: onlyIdToken));

            var clientClaims = claimsDownLogic.GetClientJwtClaims(client, onlyIdTokenClaims: true);

            if (clientClaims?.Count() > 0)
            {
                idTokenClaims.AddRange(clientClaims);
            }

            if (!nonce.IsNullOrEmpty())
            {
                idTokenClaims.AddClaim(JwtClaimTypes.Nonce, nonce);
            }

            if (!onlyIdToken)
            {
                if (responseTypes.Contains(IdentityConstants.ResponseTypes.Token))
                {
                    idTokenClaims.AddClaim(JwtClaimTypes.AtHash, await accessToken.LeftMostBase64urlEncodedHashAsync(algorithm));
                }
                if (responseTypes.Contains(IdentityConstants.ResponseTypes.Code))
                {
                    idTokenClaims.AddClaim(JwtClaimTypes.CHash, await code.LeftMostBase64urlEncodedHashAsync(algorithm));
                }
            }

            logger.ScopeTrace(() => $"Down, JWT ID token claims '{idTokenClaims.ToFormattedString()}'", traceType: TraceTypes.Claim);
            var token = JwtHandler.CreateToken(await trackKeyLogic.GetPrimarySecurityKeyAsync(RouteBinding.Key), trackIssuerLogic.GetIssuer(), client.ClientId, idTokenClaims, expiresIn: (client as OidcDownClient).IdTokenLifetime, algorithm: algorithm);

            return(await token.ToJwtString());
        }
Esempio n. 23
0
        public async Task <ClaimsPrincipal> ValidateTokenAsync(string token, bool validateAudience = false, bool validateLifetime = true)
        {
            var issuerSigningKeys = new List <JsonWebKey>();

            issuerSigningKeys.Add(RouteBinding.Key.PrimaryKey.Key);
            if (RouteBinding.Key.SecondaryKey != null)
            {
                issuerSigningKeys.Add(RouteBinding.Key.SecondaryKey.Key);
            }

            try
            {
                (var claimsPrincipal, _) = await Task.FromResult(JwtHandler.ValidateToken(token, trackIssuerLogic.GetIssuer(), issuerSigningKeys, validateAudience: validateAudience, validateLifetime: validateLifetime));

                return(claimsPrincipal);
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"JWT not valid. Route '{RouteBinding.Route}'.");
                return(null);
            }
        }
Esempio n. 24
0
        public async Task <string> CreateAccessTokenAsync(TClient client, IEnumerable <Claim> claims, IEnumerable <string> selectedScopes, string algorithm)
        {
            var accessTokenClaims = new List <Claim>();

            (var audiences, var audienceScopes) = await oauthResourceScopeLogic.GetValidResourceAsync(client, selectedScopes);

            if (audiences.Count() > 0)
            {
                accessTokenClaims.AddClaim(JwtClaimTypes.Scope, audienceScopes.ToSpaceList());
            }
            else
            {
                audiences.Add(client.ClientId);
            }

            accessTokenClaims.AddClaim(JwtClaimTypes.ClientId, client.ClientId);

            accessTokenClaims.AddRange(await claimsLogic.FilterJwtClaims(client, claims, selectedScopes, includeAccessTokenClaims: true));

            var token = JwtHandler.CreateToken(trackKeyLogic.GetSecurityKey(RouteBinding.PrimaryKey), Issuer(RouteBinding), audiences, accessTokenClaims, expiresIn: client.AccessTokenLifetime, algorithm: algorithm, x509CertificateSHA1Thumbprint: RouteBinding.PrimaryKey.Key.Kid);

            return(await token.ToJwtString());
        }
        public void TestGetClaims()
        {
            var jwtHandler = new JwtHandler(_config);
            var user       = new ApplicationUser
            {
                Id           = "13265262",
                UserName     = "******",
                PasswordHash = "jerryricehashed",
                FullName     = "Jerry Rice",
                PhoneNumber  = "111-111-1111",
                Email        = "*****@*****.**",
                TeamID       = Guid.NewGuid(),
                RoleName     = Roles.HC,
                StatLineID   = Guid.NewGuid()
            };
            var claims = jwtHandler.GetClaims(user);

            foreach (var claim in claims)
            {
                Assert.NotEmpty(claim.Type);
                Assert.NotEmpty(claim.Value);
            }
        }
Esempio n. 26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Study Group Finder API V1", Version = "v1"
                });
            });
            #endregion

            #region JWT Token
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ClockSkew = TimeSpan.Zero,

                    ValidIssuer      = Configuration["JwtSecurity:Issuer"],
                    ValidAudience    = Configuration["JwtSecurity:Audience"],
                    IssuerSigningKey = JwtHandler.CreateSigningKey(Configuration["JwtSecurity:SecretKey"])
                };
            });
            #endregion

            #region Dependency Injection
            services.AddTransient <DatabaseProvider>();
            services.AddTransient <UsersRepository>();
            #endregion

            services.AddMvc();
        }
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            try
            {
                var accessToken = GetAccessTokenFromHeader();

                var routeBinding = Context.GetRouteBinding();
                var authority    = UrlCombine.Combine(GetFoxIDsEndpoint(), routeBinding.TenantName, Constants.Routes.MasterTrackName, Options.DownParty);

                var oidcDiscoveryUri     = UrlCombine.Combine(authority, IdentityConstants.OidcDiscovery.Path);
                var oidcDiscoveryHandler = Context.RequestServices.GetService <OidcDiscoveryHandlerService>();
                var oidcDiscovery        = await oidcDiscoveryHandler.GetOidcDiscoveryAsync(oidcDiscoveryUri);

                var oidcDiscoveryKeySet = await oidcDiscoveryHandler.GetOidcDiscoveryKeysAsync(oidcDiscoveryUri);

                ClaimsPrincipal principal;
                try
                {
                    (principal, _) = JwtHandler.ValidateToken(accessToken, oidcDiscovery.Issuer, oidcDiscoveryKeySet.Keys, Options.DownParty);
                }
                catch (SecurityTokenInvalidSignatureException isex)
                {
                    Logger.LogWarning(isex, $"Invalid signature reload OIDC discovery keys, uri '{oidcDiscoveryUri}'.");
                    oidcDiscoveryKeySet = await oidcDiscoveryHandler.GetOidcDiscoveryKeysAsync(oidcDiscoveryUri, refreshCache : true);

                    (principal, _) = JwtHandler.ValidateToken(accessToken, oidcDiscovery.Issuer, oidcDiscoveryKeySet.Keys, Options.DownParty);
                }

                var ticket = new AuthenticationTicket(principal, Scheme.Name);
                return(AuthenticateResult.Success(ticket));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, ex.Message);
                return(AuthenticateResult.Fail(ex.Message));
            }
        }
Esempio n. 28
0
        public override async Task OnAuthorizationAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
        {
            try
            {
                var token = actionContext.Header(Authorization); //HttpContext.Current.Request.Headers[Authorization];
                if (string.IsNullOrEmpty(token))
                {
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                    {
                        ReasonPhrase = "No token!"
                    };
                    return;
                }

                token = token.Replace(Bearer, "");

                var result = JwtHandler.DecodeToken(token, actionContext.BaseUrl());
                var name   = result.ClaimsPrincipal.FindFirst(c => c.Type == Name);
                var userId = result.ClaimsPrincipal.FindFirst(c => c.Type == UserId);

                //get user from Db by user id


                actionContext.ActionArguments.Add(Name, $"{name.Value}:{userId.Value}");

                var issuer = result.SecurityToken.Issuer;
            }
            catch (Exception)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    ReasonPhrase = "Wrong token or userId!"
                };
                return;
            }
        }
Esempio n. 29
0
        public StringResult LoginStudent([FromBody] StudentLoginRequest student)
        {
            if (string.IsNullOrEmpty(student.Username) || string.IsNullOrEmpty(student.Password))
            {
                return(StringResult.Error("Username and password cannot be blank"));
            }

            var loginResult = studentBl.LoginStudent(student.Username, student.Password);

            if (loginResult.Success)
            {
                var secretKey = configuration[CONSTANTS.Keys.JWT_SECRETKEY];
                var issuer    = configuration[CONSTANTS.Keys.JWT_ISSUER];
                var audience  = configuration[CONSTANTS.Keys.JWT_AUDIENCE];
                var token     = JwtHandler.GenerateAPIToken(loginResult.ResultOk.ToString(), secretKey, issuer, audience);
                return(StringResult.Ok(token));
            }
            else
            {
                var result = StringResult.Error();
                result.ResultError = loginResult.ResultError;
                return(result);
            }
        }
Esempio n. 30
0
 public AuthenticationController(UserManager <ApplicationUser> userManager, JwtHandler jwtHandler)
 {
     _userManager = userManager;
     _jwtHandler  = jwtHandler;
 }