コード例 #1
0
 public AccountController(ILogger <AccountController> logger, JwtTokenCreator jwtCreator, UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager)
 {
     _logger        = logger;
     _jwtCreator    = jwtCreator;
     _userManager   = userManager;
     _signInManager = signInManager;
 }
コード例 #2
0
        public HttpResponseMessage GetWithAuthentication()
        {
            AuthenticationHeaderValue authorization = Request.Headers.Authorization;

            if (authorization == null)
            {
                return(this.Request.CreateResponse(HttpStatusCode.Forbidden, "Missing autorization header"));
            }
            else if (authorization.Scheme != "Bearer")
            {
                return(this.Request.CreateResponse(HttpStatusCode.Forbidden, "Invalid autorization scheme"));
            }
            else if (!String.IsNullOrEmpty(authorization.Parameter))
            {
                string token = authorization.Parameter;

                JwtTokenCreator tokenCreator = new JwtTokenCreator();
                if (tokenCreator.ValidateToken(token))
                {
                    return(this.Request.CreateResponse(HttpStatusCode.OK, new { ProductId = 100, ProductName = "Laptop", Price = "300$" }));
                }
                else
                {
                    return(this.Request.CreateResponse(HttpStatusCode.Forbidden, "Invalid autorization"));
                }
            }
            else
            {
                return(this.Request.CreateResponse(HttpStatusCode.Forbidden, "Missing autorization header"));
            }
        }
コード例 #3
0
        public HttpResponseMessage Login([FromBody] dynamic Data)
        {
            if (Data.username != null && Data.password != null)
            {
                if (Data.username.Value == "John" && Data.password.Value == "1234")
                {
                    Dictionary <string, string> ClaimDic = new Dictionary <string, string>();
                    ClaimDic.Add("userId", Data.username.Value);
                    ClaimDic.Add("FirstName", "John");
                    ClaimDic.Add("LastName", "Smith");
                    ClaimDic.Add("PersonalCode", "123456");


                    JwtTokenCreator tokenCreator = new JwtTokenCreator();
                    string          newToken     = tokenCreator.GenerateJwtToken(ClaimDic);

                    return(this.Request.CreateResponse(HttpStatusCode.OK, new { jwt = newToken }));
                }
                else
                {
                    return(this.Request.CreateResponse(HttpStatusCode.Forbidden, "UserName or Password is Not Valid"));
                }
            }
            else
            {
                return(this.Request.CreateResponse(HttpStatusCode.Forbidden, "Input Parameters are Not Valid"));
            }
        }
コード例 #4
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("GetAccess message received");

            try
            {
                log.Info("Reading body message");

                UserCredentials userCredentials = JsonConvert.DeserializeObject <UserCredentials>(await req.Content.ReadAsStringAsync());
                if (userCredentials == null || string.IsNullOrWhiteSpace(userCredentials.Login) || string.IsNullOrWhiteSpace(userCredentials.Password))
                {
                    return(req.CreateResponse(HttpStatusCode.Unauthorized, "Missing credentials"));
                }

                log.Info("Getting User");
                CosmoOperation cosmoOperation = await CosmosDBOperations.QueryDBAsync(new CosmoOperation()
                {
                    Collection = Environment.GetEnvironmentVariable(Config.COSMOS_COLLECTION),
                    Database   = Environment.GetEnvironmentVariable(Config.COSMOS_DATABASE),
                    Payload    = $"SELECT * FROM c WHERE c.type = 'User' AND c.login = '******' AND c.password = '******'"
                });

                if (cosmoOperation.Results == null || cosmoOperation.Results.Length == 0)
                {
                    return(req.CreateResponse(HttpStatusCode.Unauthorized, "Invalid credentials"));
                }

                if (cosmoOperation.Results.Length > 1)
                {
                    throw new Exception("More than one user has found");
                }

                Dictionary <string, object> user = JsonConvert.DeserializeObject <Dictionary <string, object> >(cosmoOperation.Results[0].ToString());
                string token = JwtTokenCreator.CreateJwtToken(
                    (string)user["name"],
                    (string)user["id"],
                    new Dictionary <string, string>()
                {
                    { "user", JsonConvert.SerializeObject(user) }
                });

                return(await Task.Factory.StartNew(() => req.CreateResponse(HttpStatusCode.OK, token)));
            }
            catch (Exception ex)
            {
                log.Error("Erro: ", ex);
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
コード例 #5
0
        public AuthenticatedUserDto TryLogin(LoginRequest loginRequest)
        {
            User user;

            if (!IsUserAuthenticated(loginRequest, out user))
            {
                return(null);
            }

            AuthenticatedUserDto authenticatedUserDto = Mapper.Map <AuthenticatedUserDto>(user);
            string securityToken = JwtTokenCreator.CreateToken(user, ConfigurationManager.AppSettings["SecretSignatureKey"]);

            authenticatedUserDto.Token = securityToken;
            return(authenticatedUserDto);
        }
コード例 #6
0
        public async Task <IActionResult> SignIn(UserToSignInDTO model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = ModelState })));
                }

                var user = _userManager.Users.FirstOrDefault(x => x.Email == model.Email);

                if (user == null)
                {
                    return(Unauthorized(ResponseMessage.Message("Unauthorized", errors: new { message = "Invalid credentials" })));
                }

                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);

                var userRoles = await _userManager.GetRolesAsync(user);

                if (result.Succeeded)
                {
                    LoginTokenDTO loginToken = new LoginTokenDTO();
                    loginToken.UserId = user.Id;
                    loginToken.Token  = JwtTokenCreator.GetToken(user, _configuration, userRoles[0]);
                    return(Ok(ResponseMessage.Message("Success", data: new { loginToken })));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return(BadRequest(ResponseMessage.Message("Bad request", errors: new { message = "Data processing error" })));
            }

            return(Unauthorized(ResponseMessage.Message("Unauthorized", errors: new { message = "Invalid credentials" })));
        }
コード例 #7
0
        private string CreateAuthToken(string username, string email)
        {
            var tokenCreator = new JwtTokenCreator(configuration.GetSection("Keys")["JwtPrivateKey"]);

            return(tokenCreator.CreateToken(username, email));
        }