示例#1
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new
            {
                token = tokenHandler.WriteToken(token),
                //user
            }));
        }
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            userForLoginDto.Username = userForLoginDto.Username.ToLower();
            var user = await _repo.Login(userForLoginDto.Username, userForLoginDto.Password);

            if (user == null)
            {
                return(Unauthorized("Incorrect Credientials"));
            }


            // Send the token to the user so that any further request will be authenticated based on the JWT Token

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddHours(2),
                SigningCredentials = cred
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
        public async Task <IActionResult> login(UserFromLoginDto userFromLoginDto)
        {
            //Check if Login credentials match against the DB
            //
            var userFromRepo = await _repo.Login(userFromLoginDto.Username, userFromLoginDto.Password);

            //If Login credentials do not match...the user is unauthorized
            //
            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            //Start building Claims for UserName and password.  Claim = Build Identity of user
            //We already verified that this usrNm/pass exists
            //
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.UserName)
            };

            //We define this key in our appSettings.json but, a key must be in bytes[]
            //The key is required for the Server to sign the Token
            //
            var key = new SymmetricSecurityKey(Encoding.UTF8
                                               .GetBytes(_config.GetSection("AppSettings:Token").Value));

            //In order for Server to sign the token.  Our key must be hashed using a security algorithm.
            //The Server Validates the Token by signing using the key... Microsoft.IdentityModel.Tokens
            //
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            //Bundle (Claims we made about the user + Validation = Server Signed Token "creds")
            //
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            //The token needs a handler to deal with the token in a secure way
            //
            var tokenHandler = new JwtSecurityTokenHandler();

            //Create a JWT token and pass the bundles properties of the token
            //Contains the JWT token that we want to return to our client
            //
            var token = tokenHandler.CreateToken(tokenDescriptor);

            // Convert user to Dto with photoUrl info, not full user so, only limited info passed
            // This is passed on login so that, we can save the main photo will be passed to
            // local storage.  We will use photoUrl to display member picture in NavBar
            //
            var user = _mapper.Map <UserForListDto>(userFromRepo);

            // Return the JWT Token as an (obj) Token to the Client
            // Serialize/Write token (obj) as a response back to the client
            // Anonymous object passed that we can customize
            //
            return(Ok(
                       new
            {
                token = tokenHandler.WriteToken(token),
                user
            }
                       ));
        }
示例#4
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            //lesson 51:
            //throw new Exception("This is a not-useful error message from the API!");
            //it's only at the top while you see it in action in Postman and the browser tools.

            //usual approach to handling errors is the Try-Catch block:
            //which deleted in lesson 52 to use a global handler instead.

            // try
            // {
            var userFromRepo = await _repo.Login(userForLoginDto.UserName.ToLower(), userForLoginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
                //when someone logs in wrong
                //don't give them a hint about what's wrong (ie, not found or wrong password, etc)
                //it's safer that way (and more annoying for the user ahem.)
            }

            //create a token to return to the user:
            //we add info here so the server won't have to check the db each time
            //it just has to look at the token.
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.UserName)
            };

            //the next lines encrypt the key
            //and prepare stuff to put into the token.

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));
            //the proj just knew what to type here.
            //GetSection is a built in method from the IConfig stuff.
            //"AppSettings:Token" value will be added to / found in appsettings.json

            //for the next parts, again -- prof just knows what to type to create the variables.

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            //actual creation of the token itself.
            var token = tokenHandler.CreateToken(tokenDescriptor);

            //this is what gets returned to the client.

            //this return statement will send OK
            //plus the token, written so the client will understand it.
            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
示例#5
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            // user: taren password: pwd
            // (used for testing purposes) throw new Exception("new exception thrown! (in AuthController.cs, Login method.)");

            // Checking to make sure that we have a user and the username
            // and pass matches what's stored in the Db for that particular user.
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

            // THe user is not found in the database, however,
            // This does not allow the login attempt any glimpse at a "hint",
            // eg. Username exists but password is wrong, or username doesn't exist, etc.
            if (userFromRepo == null)
            {
                return(Unauthorized());
            }


            // Build a token which gets returned to user. Contains user ID and Username
            var claims = new[]
            {
                // ID Token claim
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                // Username Token Claim
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };

            // To ensure the token is a valid token when it comes back, the server
            // needs a key to sign this token. This creates and encrypts a security
            // key and using the key as part of the signing credentials.
            // This AppSettings:Token in reality should not be shor t, it should
            // be an extremely long randomly generated token. The token in this project
            // is very short and simple for the purposes of this exersize.
            var key = new SymmetricSecurityKey(Encoding.UTF8
                                               .GetBytes(_config.GetSection("AppSettings:Token").Value));

            // Generate Signing credentials
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            // Create security token descriptor which contains claims,
            // expiry date for token, and sign in credentials
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                // expy of 1 day is for the purposes of training. Something like
                // a bank might have an expiration date of 30 minutes, or something
                // less strict might be permant until logout, etc. etc.
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            // Security token handler allows us to create the token based on the
            // token handler which is given the token descriptor being passed,
            // and is then stored in token variable.
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            // Use token variable to write token into response which is sent
            // back to the client.
            return(Ok(new
            {
                token = tokenHandler.WriteToken(token)
            }));
        } // end try