private OAuthResponse RefreshAuthorization(OAuthParams oAuth) { string userName = null; if (_cache.TryGetValue(oAuth.refresh_token, out userName)) { if (!string.IsNullOrEmpty(userName)) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(_config["Tokens:Issuer"], _config["Tokens:Issuer"], claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return(new OAuthResponse() { access_token = new JwtSecurityTokenHandler().WriteToken(token), expires_in = (int)TimeSpan.FromMinutes(30).TotalSeconds, refresh_token = oAuth.refresh_token, }); } } return(null); }
public async Task <IActionResult> Authorize(OAuthParams oAuth) { if (oAuth.grant_type == "password") { var auth = await GrantAuthorization(oAuth); if (auth != null) { return(Ok(auth)); } else { return(BadRequest("Could not create token")); } } else if (oAuth.grant_type == "refresh_token") { var auth = RefreshAuthorization(oAuth); if (auth != null) { return(Ok(auth)); } else { return(BadRequest("Could not create token")); } } else { return(BadRequest(new ApplicationException("Invalid authorization request"))); } }
public async Task <IActionResult> CreateAccount(OAuthParams oAuth) { var response = await _userRepo.AddOrUpdate(new Data.User() { UserName = oAuth.username, Password = oAuth.password, CorrelationID = Guid.NewGuid().ToString(), UTCTickStamp = DateTime.UtcNow.Ticks }); if (response.error != null) { return(BadRequest(response.error)); } else { return(Ok(response.dict)); } }
private async Task <OAuthResponse> GrantAuthorization(OAuthParams oAuth) { var obj = await _userRepo.GetByLogin(oAuth.username, oAuth.password); if (obj != null) { obj.Password = string.Empty; var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, oAuth.username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(_config["Tokens:Issuer"], _config["Tokens:Issuer"], claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); var refreshToken = Guid.NewGuid().ToString().Replace("-", string.Empty).Trim(); var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromDays(3)); _cache.Set(refreshToken, oAuth.username, cacheEntryOptions); return(new OAuthResponse() { access_token = new JwtSecurityTokenHandler().WriteToken(token), expires_in = (int)TimeSpan.FromMinutes(30).TotalSeconds, refresh_token = refreshToken, meta_data = JsonConvert.SerializeObject(obj) }); } else { return(null); } }