public ActionResult LoginRequest(LoginRequest loginrequest) { try { var APIresponse = Client.PostAsJsonAsync <LoginRequest>(baseAddress + "signin", loginrequest).GetAwaiter().GetResult(); if (APIresponse.IsSuccessStatusCode) { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; TokenConnect = response.accessToken; ConnectedId = response.id; ConnectedName = response.username; ConnectedRole = response.roles.ElementAt(0); if (response.roles.Contains("ROLE_ADMIN")) { return(RedirectToAction("../AdminAccount/Home")); } return(RedirectToAction("../Home")); } else { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; TempData ["message"] = response.message; return(RedirectToAction("LoginRequest")); } } catch { return(View()); } }
public JwtResponse GetJwt(ClientApi clientApi, string username) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(JwtRegisteredClaimNames.NameId, clientApi.Name), new Claim(JwtRegisteredClaimNames.UniqueName, clientApi.ClientId), new Claim(JwtRegisteredClaimNames.Sid, clientApi.ClientSecret), new Claim("Username", username.ToBase64Encode()), }; var token = new JwtSecurityToken( issuer: _config["Jwt:Issuer"], //Owner Api => Application Name or URL API audience: clientApi.ClientId, //Client Token => Client Name or URL Website claims, notBefore: DateTime.Now, expires: DateTime.Now.AddHours(int.Parse(_config["Jwt:ExpiresInHours"])), signingCredentials: credentials); var encodeToken = new JwtSecurityTokenHandler().WriteToken(token); var jwtResponse = new JwtResponse { Token = encodeToken, ValidFrom = token.ValidFrom.ToLocalTime(), ValidTo = token.ValidTo.ToLocalTime() }; return(jwtResponse); }
public async Task <JwtResponse> VerifyPhoneNumber([FromBody] VerifyPhoneNumberViewModel model) { var jwt = new JwtResponse { Status = IdentityStatus.Error }; if (!ModelState.IsValid) { jwt.Message = "Invalid JSON model"; return(jwt); } var user = await GetCurrentUser(); if (user != null) { var jwtResponse = await accountService.CompleteUserVerification(user, model.Phone, model.Code); if (jwtResponse != null) { jwtResponse.Status = IdentityStatus.AddPhoneSuccess; return(jwtResponse); } } jwt.Message = "Failed to verify phone number"; return(jwt); }
public ActionResult Login([FromBody] LoginData loginData) { //get the login user var loginUser = database.Users.SingleOrDefault(user => user.UserName == loginData.UserName && user.Password == loginData.Password); if (loginUser == null) { return(NotFound("Invalid Username or password")); } else { //get the token var jwt = new JwtSecurityToken(); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); //get the response to frontend var response = new JwtResponse() { Token = encodedJwt , FirstName = loginUser.FirstName , LastName = loginUser.LastName , UserName = loginUser.UserName }; return(Ok(response)); } //return Ok(CreateJwtPacket(user)); }
// POST api/gateway/login public async Task <IActionResult> LogIn([FromBody] LogInViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //Prepare httpParameters for request HttpParameters httpParameters = HttpParametersService.GetHttpParameters( model, ConfigHelper.AppSetting(Constants.ServerUrls, Constants.Auth), HttpMethod.Post, string.Empty); //httpclient request from class library JwtResponse authResult = await _gWService.PostTo <JwtResponse>(httpParameters); if (authResult.StatusCode == 400) { return(await ResponseService.GetResponse <BadRequestObjectResult, JwtResponse>(authResult, ModelState)); } //return jwt token return(new OkObjectResult(authResult)); }
public ActionResult Edit(User user) { try { // TODO: Add update logic here var APIresponse = Client.PutAsJsonAsync <User>(baseAddress + "updateUser", user).GetAwaiter().GetResult(); if (APIresponse.IsSuccessStatusCode) { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; LoginController.TokenConnect = response.accessToken; LoginController.ConnectedName = response.username; LoginController.ConnectedId = response.id; LoginController.ConnectedRole = response.roles.ElementAt(0); return(RedirectToAction("Details")); } return(View()); } catch { return(View()); } }
public ActionResult AddCategory(FormCollection collection, int shelfId) { try { var value = collection["category"]; Debug.WriteLine(value); var APIresponse = Client.PutAsJsonAsync <Shelf>(baseAddress + "affecterCategoryAShelf/" + value + "/" + shelfId, null).GetAwaiter().GetResult(); // TODO: Add insert logic here String message = APIresponse.ToString(); if (APIresponse.IsSuccessStatusCode) { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; return(RedirectToAction("ListOfCategory/" + shelfId)); } else { return(RedirectToAction("ListOfCategory/" + shelfId)); } } catch { return(RedirectToAction("ListOfCategory/" + shelfId)); } }
public ActionResult DeleteCategory(int id, int shelfId) { try { Debug.WriteLine(shelfId); Debug.WriteLine(id); var APIresponse = Client.PutAsJsonAsync <Shelf>(baseAddress + "daffecterCategoryAShelf/" + id + "/" + shelfId, null).GetAwaiter().GetResult(); // TODO: Add insert logic here String message = APIresponse.ToString(); if (APIresponse.IsSuccessStatusCode) { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; return(RedirectToAction("ListOfCategory/" + shelfId)); } else { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; return(RedirectToAction("ListOfCategory/" + shelfId)); } } catch { return(RedirectToAction("ListOfCategory/" + shelfId)); } }
public ActionResult Create(Shelf shelf) { try { var APIresponse = Client.PostAsJsonAsync <Shelf>(baseAddress + "addShelf", shelf).GetAwaiter().GetResult(); // TODO: Add insert logic here if (APIresponse.IsSuccessStatusCode) { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; return(RedirectToAction("Index")); } else { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; TempData["message"] = response.message; return(RedirectToAction("Create")); } } catch { return(RedirectToAction("Index")); } }
public async Task <object> Create([FromBody] WorkshopAccountViewModel workshop) { var response = new JwtResponse { Message = "Creation of workshop failed" }; Guid workshopId; if (ModelState.IsValid) { workshop.RegisterDate = DateTime.UtcNow; var user = await GetCurrentUser(); workshopId = await workshopAccountService.Add(workshop, user); if (workshopId != Guid.Empty) { response = await RefreshJwt(user); } } //TODO: think about output model return(new { Token = response, WorkshopId = workshopId }); }
public async Task <JwtResponse> GenerateJwtToken(string username) { string jti = await this.jwtOptions.JtiGenerator(); var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.GivenName, username), new Claim(JwtRegisteredClaimNames.Jti, jti), new Claim("role", "Admin") }; var jwt = new JwtSecurityToken( issuer: this.jwtOptions.Issuer, audience: this.jwtOptions.Audience, claims: claims, notBefore: this.jwtOptions.NotBefore, expires: this.jwtOptions.Expiration, signingCredentials: this.jwtOptions.SigningCredentials ); string token = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new JwtResponse() { auth_token = token, expires_in = (int)jwtOptions.ValidFor.TotalMinutes, Jti = jti }; this.refreshTokens.Add(new RefreshToken() { Username = username, Jti = jti }); return(await Task.FromResult(response)); }
public IActionResult GetToken([FromBody] AuthRequest model) { JwtResponse response = _authService.Authenticate(model); if (response == null) { return(BadRequest(new { message = "Incorrect Username or Password" })); } return(Ok(response)); }
public async Task <IActionResult> Authenticate([FromBody] GreenlitAuthDto authDto) { try { JwtResponse jwt = await _userService.AuthenticateApiUser(authDto.ApiId, authDto.AuthToken); return(Ok(jwt)); } catch (AppException ex) { return(BadRequest(_errorService.BadRequest(ex, HttpContext.Request))); } }
public static JwtResponse Produce(JwtIdentity identity, TokenProviderOptions options) { var now = System.DateTime.UtcNow; var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Email, identity.User.Email), new Claim(JwtRegisteredClaimNames.Sub, identity.User.UserName), new Claim(JwtRegisteredClaimNames.Jti, options.NonceGenerator()), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64), }; if (identity.Claims != null) { claims.AddRange(identity.Claims); claims.Add(AddIosSpecificClaims(identity.Claims)); } if (identity.Roles != null && identity.Roles.Any()) { var roleClaims = identity.Roles.Select(x => new Claim(ClaimTypes.Role, x)); claims.AddRange(roleClaims); claims.Add(AddIosSpecificRoles(identity.Roles)); } var jwt = new JwtSecurityToken( issuer: options.Issuer, audience: options.Audience, claims: claims, notBefore: now, expires: now.Add(options.Expiration), signingCredentials: options.SigningCredentials); var jwtTokenHandler = new JwtSecurityTokenHandler(); //jwtTokenHandler.InboundClaimTypeMap.Clear(); var encodedJwt = jwtTokenHandler.WriteToken(jwt); if (identity.RefreshToken == null) { return(null); } var response = new JwtResponse { AccessToken = encodedJwt, ExpiresIn = (int)options.Expiration.TotalSeconds, RefreshToken = identity.RefreshToken.Token }; return(response); }
public async Task <ActionResult> Login( [FromBody] LoginUserDto loginUserDto ) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest, "Incorrect object"); } JwtResponse jwtResponse = await _authService.LoginAsync(loginUserDto.Username, loginUserDto.Password); return(Ok(jwtResponse)); }
public static async Task <string> GenerateJwt(ClaimsIdentity identity, IJwtFactory jwtFactory, string userName, JwtIssuerOptions jwtOptions, JsonSerializerSettings serializerSettings) { var response = new JwtResponse { Id = identity.Claims.Single(c => c.Type == "id").Value, Auth_Token = await jwtFactory.GenerateEncodedToken(userName, identity), Expires_In = (int)jwtOptions.ValidFor.TotalSeconds, Code = "login_success", StatusCode = 200, Description = "user was authenticated", Error = "no_error" }; return(JsonConvert.SerializeObject(response, serializerSettings)); }
public IActionResult Login([FromBody] LoginViewModel info) { if (info == null) { info = new LoginViewModel(); TryValidateModel(info); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = _userRepository .Get().FirstOrDefault(x => x.Email.Equals(info.Email, StringComparison.InvariantCultureIgnoreCase)); if (user == null) { return(NotFound()); } var claims = new List <Claim>(); claims.Add(new Claim(ClaimValueTypes.Email, user.Email)); claims.Add(new Claim(ClaimValueTypes.KeyInfo, user.Id.ToString())); // Find current time on the system. var systemTime = DateTime.Now; var jwtExpiration = systemTime.AddSeconds(_jwtOption.LifeTime); // Write a security token. var jwtSecurityToken = new JwtSecurityToken(_jwtOption.Issuer, _jwtOption.Audience, claims, null, jwtExpiration, _jwtOption.SigningCredentials); // Initiate token handler which is for generating token code. var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); jwtSecurityTokenHandler.WriteToken(jwtSecurityToken); // Initialize jwt response. var jwt = new JwtResponse(); jwt.Code = jwtSecurityTokenHandler.WriteToken(jwtSecurityToken); jwt.LifeTime = _jwtOption.LifeTime; jwt.Expiration = _timeService.DateTimeUtcToUnix(jwtExpiration); return(Ok(jwt)); }
/// <summary> /// 获取Jwt响应数据 /// </summary> /// <param name="userName"></param> /// <returns></returns> #warning 这里最好传入User对象 public static JwtResponse GetJwtResponse(string userName) { //获取当前计算机时间并转化为世界时 var now = DateTime.UtcNow; /* iss: jwt签发者 * sub: jwt所面向的用户 * aud: 接收jwt的一方 * exp: jwt的过期时间,这个过期时间必须要大于签发时间 * nbf: 定义在什么时间之前,该jwt都是不可用的. * iat: jwt的签发时间 * jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。 */ var claims = new Claim[] { //用户 new Claim(JwtRegisteredClaimNames.Sub, userName), //身份标识 new Claim(JwtRegisteredClaimNames.Jti, "1", ClaimValueTypes.Integer), //签发时间 new Claim(JwtRegisteredClaimNames.Iat, now.ToString(), ClaimValueTypes.DateTime), //用户名 new Claim(ClaimTypes.Name, userName), //角色 new Claim(ClaimTypes.Role, "User"), }; var signingCredentials = new SigningCredentials(_issuerSigningKey, SecurityAlgorithms.HmacSha256Signature); var jwt = new JwtSecurityToken( issuer: _issuer, audience: _audience, claims: claims, notBefore: now, expires: now.Add(_expiration), signingCredentials: signingCredentials ); var response = new JwtResponse() { Status = true, AccessToken = new JwtSecurityTokenHandler().WriteToken(jwt), ExpiresIn = (int)_expiration.TotalSeconds, TokenType = TokenType }; return(response); }
public ActionResult SignUp(SignUpRequest signUpRequest) { var APIresponse = Client.PostAsJsonAsync <SignUpRequest>(baseAddress + "signup", signUpRequest).GetAwaiter().GetResult(); if (APIresponse.IsSuccessStatusCode) { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; return(RedirectToAction("Verify")); } else { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; TempData["message"] = response.message; return(RedirectToAction("SignUp")); } }
public async Task <string> GenerateJwt(ClaimsIdentity identity, IJwtService jwtService, string userName, JwtIssuerOptions jwtOptions, JsonSerializerSettings serializerSettings) { JwtResponse response = new JwtResponse { Token = new JwtToken() { Id = identity.Claims.Single(c => c.Type == "id").Value, Auth_Token = await jwtService.GenerateEncodedToken(userName, identity), Expires_In = (int)jwtOptions.ValidFor.TotalSeconds }, StatusCode = HttpStatusCode.OK, Error = "no_error", Description = "User was authenticated" }; return(JsonConvert.SerializeObject(response, serializerSettings)); }
public async Task <JwtResponse> GenerateJwtAsync(string clientId, string clientSecret, string username) { var jwtResponse = new JwtResponse(); var spec = new ClientApiSpecification(clientId, clientSecret); var clientApi = await _clientApiRepository.GetAsync(spec); if (clientApi != null) { jwtResponse = _jwt.GetJwt(clientApi, username); //update ClientApi clientApi.Token = jwtResponse.Token; clientApi.ExpiredToken = jwtResponse.ValidTo; clientApi.ModifiedBy = username; await _clientApiRepository.UpdateAsync(clientApi); } return(jwtResponse); }
public async Task <IActionResult> Setup([FromBody] UserSetupDto userSetupDto) { var authToken = userSetupDto.AuthToken; var user = _mapper.Map <User>(userSetupDto); try { var userResponse = _userService.Create(user); JwtResponse jwt = await _userService.AuthenticateApiUser(userResponse); return(Ok(new UserSetupResponse { User = userResponse, Jwt = jwt })); } catch (AppException ex) { return(BadRequest(_errorService.BadRequest(ex, HttpContext.Request))); } }
private async Task <string> SignedJwtAssertion() { string accessTokenResponse = string.Empty; // 1. Fetch Json response from OpenID Connect Discovery Endpoint, aka well-known endpoint of the Authority (Keycloak IAM) // We need this to obtain the Token Endpoint Value used as the 'aud' or Audience of the JWT. string tokenUrl = this.GetTokenEndpoint(oidcConfig.Authority); // 2. "Signed Jwt" - Using the pfx file specified in the app settings config, create a signed Json Web Token. JwtResponse jwtResponse = this.CreateSignedJsonWebToken(oidcConfig.ClientId, tokenUrl); // 3. Now using OIDC client assertion direct flow, authenticate using the Signed JWT as the client credential. // This is client credentials grant but with a Signed JWT, so no need to supply the client_id or client_secret // parameters. try { IEnumerable <KeyValuePair <string, string> > oauthParams = new[] { new KeyValuePair <string, string>(@"grant_type", @"client_credentials"), new KeyValuePair <string, string>(@"client_assertion", jwtResponse.Token), // the signed JWT new KeyValuePair <string, string>(@"audience", oidcConfig.Audience), new KeyValuePair <string, string>(@"client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"), new KeyValuePair <string, string>(@"scope", oidcConfig.Scope), }; using var content = new FormUrlEncodedContent(oauthParams); content.Headers.Clear(); content.Headers.Add(@"Content-Type", @"application/x-www-form-urlencoded"); using HttpResponseMessage response = await client.PostAsync(tokenUrl, content).ConfigureAwait(true); accessTokenResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(true); Console.WriteLine($"JWT Token response: {accessTokenResponse}"); response.EnsureSuccessStatusCode(); } catch (HttpRequestException e) { Console.WriteLine($"Error Message {e.Message}"); } // 4. Return the Access Token for subsequent use as the Bearer Token for Pharmanet API Calls. return(accessTokenResponse); }
public virtual void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; HttpResponse response = context.Response; //Read Json Masked Wallet Response Jwt StreamReader streamReader = new StreamReader(request.InputStream); String input; String json = ""; while ((input = streamReader.ReadLine()) != null) { Console.WriteLine(input); json += input; } Request req = JsonConvert.DeserializeObject <Request> (json); //Convert Masked Wallet Response Jwt to Masked Wallet Response object String jsonResponse = JsonWebToken.Decode(req.jwt, Config.getMerchantSecret(), false); JwtResponse jwtResponse = JsonConvert.DeserializeObject <JwtResponse> (jsonResponse); //Create Full Wallet Body WalletBody fwb = new WalletBody.FullWalletBuilder() .GoogleTransactionId(jwtResponse.response.googleTransactionId) .ClientId(Config.getOauthClientId()) .MerchantName(Config.getMerchantName()) .Origin(Config.getOrigin(request)) .Cart(req.cart) .Build(); //Create Full Wallet request object JwtRequest fwr = new JwtRequest(JwtRequest.FULL_WALLET, Config.getMerchantId(), fwb); //Set the expiration time - not necessary but a useful example fwr.exp = Convert.ToInt64(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds) + 60000L; //Convert the JwtRequest object to a string String mwrJwt = JsonWebToken.Encode(fwr, Config.getMerchantSecret(), JwtHashAlgorithm.HS256); response.Write(mwrJwt); }
public ActionResult UpdateAccount(FormCollection collection, User u) { try { var id = u.userId; Debug.WriteLine(id); Debug.WriteLine(u.email); Debug.WriteLine(u.name); Debug.WriteLine(u.sex); Debug.WriteLine(u.age); // TODO: Add update logic here var APIresponse = Client.PutAsJsonAsync <User>(baseAddress + "updateUser", u).GetAwaiter().GetResult(); if (APIresponse.IsSuccessStatusCode) { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; LoginController.TokenConnect = response.accessToken; LoginController.ConnectedName = response.username; LoginController.ConnectedId = response.id; LoginController.ConnectedRole = response.roles.ElementAt(0); Debug.WriteLine(u.name); Debug.WriteLine(u.userId); return(RedirectToAction("MyAccount")); } else { JwtResponse response = APIresponse.Content.ReadAsAsync <JwtResponse>().Result; TempData["message1"] = response.message; Debug.WriteLine(TempData["message1"].ToString()); return(RedirectToAction("UpdateAccount")); } } catch { return(View()); } }
public virtual void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; HttpResponse response = context.Response; //Read Json Masked Wallet Response Jwt StreamReader streamReader = new StreamReader(request.InputStream); String input; String json = ""; while ((input = streamReader.ReadLine()) != null) { Console.WriteLine(input); json += input; } //Convert Full Wallet Response Jwt to Full Wallet Response object Request req = JsonConvert.DeserializeObject <Request> (json); String jsonResponse = JsonWebToken.Decode(req.jwt, Config.getMerchantSecret(), false); JwtResponse jwtResponse = JsonConvert.DeserializeObject <JwtResponse> (jsonResponse); //Create Transaction Status Notification body WalletBody tsb = new WalletBody.TransactionStatusNotificationBuilder() .GoogleTransactionId(jwtResponse.response.googleTransactionId) .ClientId(Config.getOauthClientId()) .MerchantName(Config.getMerchantName()) .Origin(Config.getOrigin(request)) .Status(WalletBody.Status.SUCCESS) .Build(); //Create Transaction Status Notification object JwtRequest tsn = new JwtRequest(JwtRequest.FULL_WALLET, Config.getMerchantId(), tsb); tsn.exp = Convert.ToInt64(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds) + 60000L; //Convert the JwtRequest object to a string String mwrJwt = JsonWebToken.Encode(tsn, Config.getMerchantSecret(), JwtHashAlgorithm.HS256); response.Write(mwrJwt); }
public async Task <IActionResult> SignIn(UserLoginResource userLoginResource) { var user = _userManager.Users.SingleOrDefault(u => u.Email == userLoginResource.Email); if (user is null) { return(NotFound("User not found")); } var userSigninResult = await _userManager.CheckPasswordAsync(user, userLoginResource.Password); if (userSigninResult) { var roles = await _userManager.GetRolesAsync(user); JwtResponse response = new JwtResponse(GenerateJwt(user, roles), new UserDto(user.Id, user.Email, user.firstName, user.lastName)); return(Ok(response)); } return(BadRequest("Email or password incorrect.")); }
public JwtResponse Execute(CreateJwtOperationRequest request) { var claims = new[] { new Claim(ClaimTypes.Name, request.Email) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Secret)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expires = DateTime.Now.AddMinutes(_jwtSettings.AccessExpiration); var jwtToken = new JwtSecurityToken(_jwtSettings.Issuer, _jwtSettings.Audience, claims, expires: expires, signingCredentials: credentials); string token = new JwtSecurityTokenHandler().WriteToken(jwtToken); var result = new JwtResponse { Expires = expires, Token = token }; return(result); }
/// <summary> /// Generates the JWT token. /// </summary> /// <param name="loginResponse"></param> /// <returns></returns> public async Task <JwtResponse> GenerateJwtToken(LoginResponse loginResponse) { string jti = await this.jwtOptions.JtiGenerator(); var newClaims = new List <Claim> { new Claim(ClaimTypes.Name, loginResponse.UserName), new Claim(Constants.DatabaseFieldName, loginResponse.DBName), new Claim(Constants.ImageSourceName, loginResponse.ImageSource != null?loginResponse.ImageSource:string.Empty) }; if (loginResponse.IsAdmin.HasValue && loginResponse.IsAdmin.Value) { newClaims.Add(new Claim(ClaimTypes.Role, Constants.AdminFieldName)); } var claims = newClaims.Concat(loginResponse.Claims); var jwt = new JwtSecurityToken( issuer: this.jwtOptions.Issuer, audience: this.jwtOptions.Audience, claims: claims, notBefore: this.jwtOptions.NotBefore, expires: this.jwtOptions.Expiration, signingCredentials: this.jwtOptions.SigningCredentials ); string token = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new JwtResponse() { auth_token = token, expires_in = jwtOptions.ValidFor.TotalMinutes, Jti = jti }; return(await Task.FromResult(response)); }
public async Task <IActionResult> Login([FromBody] LoginViewModel parameters) { #region Parameters validation // Parameter hasn't been initialized. if (parameters == null) { parameters = new LoginViewModel(); TryValidateModel(parameters); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } #endregion #if !ALLOW_ANONYMOUS #region Search account // Find account with specific information in database. var condition = new SearchAccountViewModel(); // Email search condition. condition.Email = new TextSearch(); condition.Email.Mode = TextSearchMode.Equal; condition.Email.Value = parameters.Email; // Find account by password. condition.Password = new TextSearch(); condition.Password.Value = _encryptionService.Md5Hash(parameters.Password); condition.Password.Mode = TextSearchMode.EqualIgnoreCase; condition.Statuses = new[] { Statuses.Active }; // Find accounts with defined condition above. var accounts = _unitOfWork.RepositoryAccounts.Search(); accounts = _unitOfWork.RepositoryAccounts.Search(accounts, condition); // Find the first account in database. var account = await accounts.FirstOrDefaultAsync(); if (account == null) { return(NotFound(new HttpResponse(HttpMessages.AccountIsNotFound))); } #endregion #else var account = new Account(); account.Email = "*****@*****.**"; account.Nickname = "Linh Nguyen"; #endif // Find current time on the system. var systemTime = DateTime.Now; var jwtExpiration = systemTime.AddSeconds(_jwtConfiguration.LifeTime); // Claims initalization. var claims = new List <Claim>(); claims.Add(new Claim(JwtRegisteredClaimNames.Aud, _jwtConfiguration.Audience)); claims.Add(new Claim(JwtRegisteredClaimNames.Iss, _jwtConfiguration.Issuer)); claims.Add(new Claim(JwtRegisteredClaimNames.Email, account.Email)); claims.Add(new Claim(nameof(account.Nickname), account.Nickname)); // Write a security token. var jwtSecurityToken = new JwtSecurityToken(_jwtConfiguration.Issuer, _jwtConfiguration.Audience, claims, null, jwtExpiration, _jwtConfiguration.SigningCredentials); // Initiate token handler which is for generating token code. var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); jwtSecurityTokenHandler.WriteToken(jwtSecurityToken); #region Jwt initialization var jwt = new JwtResponse(); jwt.Code = jwtSecurityTokenHandler.WriteToken(jwtSecurityToken); jwt.LifeTime = _jwtConfiguration.LifeTime; jwt.Expiration = _systemTimeService.DateTimeUtcToUnix(jwtExpiration); #endregion return(Ok(jwt)); }