public async Task <IActionResult> Facebook([FromBody] FacebookAuthViewModel model) { // 1.generate an app access token var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppKey}&grant_type=client_credentials"); var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse); // 2. validate the user access token var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}"); var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse); if (!userAccessTokenValidation.Data.IsValid) { return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid facebook token.", ModelState))); } // 3. we've got a valid token so we can request user data from fb var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v3.2/me?fields=id,email,first_name,name,birthday,picture&access_token={model.AccessToken}"); var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse); // 4. ready to create the local user account (if necessary) and jwt var user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { var appUser = new AppUser { FirstName = userInfo.FirstName, FacebookId = userInfo.Id, Email = userInfo.Email, UserName = userInfo.Email, PictureUrl = userInfo.Picture.Data.Url }; var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8)); if (!result.Succeeded) { return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState))); } await _appDbContext.Trainers.AddAsync(new Trainers { IdentityId = appUser.Id }); await _appDbContext.SaveChangesAsync(); } // generate the jwt for the local user... var localUser = await _userManager.FindByNameAsync(userInfo.Email); if (localUser == null) { return(BadRequest(Errors.AddErrorToModelState("login_failure", "Failed to create local user account.", ModelState))); } var jwt = await Token.GenerateJwt(_jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id), _jwtFactory, localUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented }); return(new OkObjectResult(jwt)); }
public void WhenGeneratingClaimsIdentityItShouldReturnAnIdentity() { _jwtOptionsnMock.Setup(p => p.Value) .Returns(new JwtOptions { Audience = "", Issuer = "", SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256), Subject = "ASubject", ValidFor = new TimeSpan(0, 0, 7200) }); _objectToTest = new JwtFactory(_jwtOptionsnMock.Object); var identity = _objectToTest.GenerateClaimsIdentity("AUserName", "Id"); Assert.NotNull(identity); }
public async Task WhenGeneratingEncodedTokenItShouldReturnAnAuthToken() { _jwtOptionsnMock.Setup(p => p.Value) .Returns(new JwtOptions { Audience = "", Issuer = "", SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256), Subject = "ASubject", ValidFor = new TimeSpan(0, 0, 7200) }); _objectToTest = new JwtFactory(_jwtOptionsnMock.Object); var claims = _objectToTest.GenerateClaimsIdentity("UserName", "Id"); var token = await _objectToTest.GenerateEncodedToken("UserName", claims); Assert.NotNull(token); }
private async Task <ClaimsIdentity> GetClaimsIdentity(string email) { if (!string.IsNullOrEmpty(email)) { var user = await UserManager.Users.FirstOrDefaultAsync(u => u.Email == email); var roles = await UserManager.GetRolesAsync(user); if (user != null) { return(await Task.FromResult(JwtFactory.GenerateClaimsIdentity(email, user.Id, roles.ToArray()))); } } return(await Task.FromResult <ClaimsIdentity>(null)); }
public async Task WhenGeneratingJwtTokenItShouldReturnAWellFormatedOne() { var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("ASecretKeyGoesHere......")); var jwtOptions = new JwtOptions { Audience = "", Issuer = "", SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256), Subject = "ASubject", ValidFor = new TimeSpan(0, 0, 7200) }; var jwtOptionsnMock = new Mock <IOptions <JwtOptions> >(); jwtOptionsnMock.Setup(p => p.Value).Returns(jwtOptions); var jwtFactory = new JwtFactory(jwtOptionsnMock.Object); var identity = jwtFactory.GenerateClaimsIdentity("AUserName", "Id"); var jwt = await TokenGenerator.GenerateJwt( identity, jwtFactory, "AUserName", jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented }); Assert.NotNull(jwt); dynamic jsonObject = JObject.Parse(jwt); string id = (string)jsonObject.id; string authToken = (string)jsonObject.authToken; string expiresIn = (string)jsonObject.expiresIn; Assert.Equal("Id", id); Assert.NotNull(authToken); Assert.Equal("7200", expiresIn); }
private async Task <ClaimsIdentity> GetClaimsIdentity(string userName, string password) { if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) { return(await Task.FromResult <ClaimsIdentity>(null)); } // get the user to verifty var userToVerify = await _userManager.FindByNameAsync(userName); if (userToVerify == null) { return(await Task.FromResult <ClaimsIdentity>(null)); } // check the credentials if (await _userManager.CheckPasswordAsync(userToVerify, password)) { return(await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(userName, userToVerify.Id))); } // Credentials are invalid, or account doesn't exist return(await Task.FromResult <ClaimsIdentity>(null)); }
private async Task <ClaimsIdentity> GetClaimsIdentity(string email, string password) { if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) { return(await Task.FromResult <ClaimsIdentity>(null)); } ApplicationUser userToVerify = await _userManager.FindByEmailAsync(email); //no user with matching email if (userToVerify == null) { return(await Task.FromResult <ClaimsIdentity>(null)); } //password is correct if (await _userManager.CheckPasswordAsync(userToVerify, password)) { return(await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(email, userToVerify.Id))); } //any other errors (i.e. password is incorrect) return(await Task.FromResult <ClaimsIdentity>(null)); }