public static ClaimsPrincipal GetPrincipal(string token) { try { JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtToken = (JwtSecurityToken)tokenHandler.ReadToken(token); if (jwtToken == null) { return(null); } byte[] key = Convert.FromBase64String(Secret); TokenValidationParameters parameters = new TokenValidationParameters() { RequireExpirationTime = true, ValidateIssuer = false, ValidateAudience = false, IssuerSigningKey = new SymmetricSecurityKey(key) }; SecurityToken securityToken; ClaimsPrincipal principal = tokenHandler.ValidateToken(token, parameters, out securityToken); return(principal); } catch { return(null); } }
/// <summary> /// Returns Claims in token for token decode /// </summary> public virtual ClaimsPrincipal GetPrincipalForAccessToken(string token) { try { JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtToken = (JwtSecurityToken)tokenHandler.ReadToken(token); if (jwtToken == null) { return(null); } //_tokenManagement => appsettings.json dosyasını okur TokenValidationParameters parameters = new TokenValidationParameters() { RequireExpirationTime = true, ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateAudience = true, ValidIssuer = _tokenManagement.Issuer, ValidAudience = _tokenManagement.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_tokenManagement.Secret)) }; SecurityToken securityToken; ClaimsPrincipal principal = tokenHandler.ValidateToken(token, parameters, out securityToken); return(principal);//Token içindeki gerekli bilgiler döndürülür } catch (Exception) { return(null); } }
public void Login_UserNameGoodPasswordGood_ReturnsGoodToken() { LoginDTO loginCredentials = new LoginDTO { UserName = "******", Password = "******" }; string pw = Crypto.HashPassword("password"); _userRepository.Setup(x => x.FindUserByUserName(It.IsAny <string>())) .Returns(new User { UserID = "guid", UserName = loginCredentials.UserName, Password = pw }); _userRepository.Setup(x => x.GetUserLabelsByUserID(It.IsAny <string>())).Returns(new List <string> { "User", "Student" }); var res = _authenticationService.Login(loginCredentials); JwtSecurityTokenHandler r = new JwtSecurityTokenHandler(); var token = r.ReadToken(res); Assert.NotNull(res); Assert.IsType <JwtSecurityToken>(token); }
public static Usuario TokenToUser(string token) { var handler = new JwtSecurityTokenHandler(); var jwtToken = handler.ReadToken(token) as JwtSecurityToken; int id = Convert.ToInt32(jwtToken.Claims.First(claim => claim.Type == "jti").Value); try { HttpClient client = Utils.getClient; HttpResponseMessage response = client.GetAsync("Usuarios/" + id).Result; if (response.IsSuccessStatusCode) { string json = response.Content.ReadAsStringAsync().Result; return(JsonConvert.DeserializeObject <Usuario>(json)); } return(null); } catch (Exception e) { Console.WriteLine(e.Message); return(null); } }
private bool AuthorizeRequest(HttpActionContext actionContext) { try { var token = actionContext.Request.Headers.Authorization.ToString().Split()[1]; var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken; if (jwtToken == null) { return(false); } var symmetricKey = Convert.FromBase64String("db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw=="); var validationParameters = new TokenValidationParameters() { RequireExpirationTime = true, ValidateIssuer = false, ValidateAudience = false, IssuerSigningKey = new SymmetricSecurityKey(symmetricKey) }; SecurityToken securityToken; var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken); actionContext.RequestContext.Principal = principal; return(true); } catch (Exception) { //should write log return(false); } }
private ClaimsPrincipal SetUserPrincipal(HttpContext context) { var Claims = new List <Claim>(); try { if (!string.IsNullOrEmpty(context.Request.Headers["Authorization"].ToString())) { var token = context.Request.Headers["Authorization"].ToString().StartsWith("Bearer ") ? context.Request.Headers["Authorization"].ToString().Substring(7) : context.Request.Headers["Authorization"].ToString(); JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtToken = (JwtSecurityToken)tokenHandler.ReadToken(token); TokenValidationParameters parameters = new TokenValidationParameters() { ValidateIssuerSigningKey = true, ValidateIssuer = true, ValidateAudience = false, ValidIssuer = jwtToken.Issuer, IssuerSigningKey = new X509SecurityKey(GetCertificate("BTSOneIdentityServer")) }; var claimsPrincipal = tokenHandler.ValidateToken(token, parameters, out SecurityToken securityToken); return(claimsPrincipal); } return(null); } catch (Exception) { throw; } }
public async Task <ActionResult> DoneJob(int id) { var job = _context.Jobs.Find(id); if (job == null) { return(NotFound()); } String jwt = Request.Headers["Authorization"]; jwt = jwt.Substring(7); //Decode jwt and get payload var stream = jwt; var handler = new JwtSecurityTokenHandler(); var jsonToken = handler.ReadToken(stream); var tokenS = jsonToken as JwtSecurityToken; //I can get Claims using: var email = tokenS.Claims.First(claim => claim.Type == "email").Value; var renter = await _context.Accounts .SingleOrDefaultAsync(p => p.Email == email); if (job.RenterId != renter.Id) { return(BadRequest(new { message = "You dont have this permission" })); } if (job.Status != "Request finish") { return(BadRequest()); } job.Status = "Done"; _context.Entry(job).State = EntityState.Modified; await _context.SaveChangesAsync(); return(Ok()); }
public async Task GetToken_ResourceOwner() { //Arrange var keyValues = new List <KeyValuePair <string, string> >(); keyValues.Add(new KeyValuePair <string, string>("username", "Bob")); keyValues.Add(new KeyValuePair <string, string>("password", "Mallo")); keyValues.Add(new KeyValuePair <string, string>("client_id", "ticketingtestapp")); keyValues.Add(new KeyValuePair <string, string>("client_secret", "secret")); keyValues.Add(new KeyValuePair <string, string>("grant_type", "password")); keyValues.Add(new KeyValuePair <string, string>("scope", "api://ticketing-core")); var content = new FormUrlEncodedContent(keyValues); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var request = new HttpRequestMessage(new HttpMethod("POST"), "/connect/token"); request.Content = content; //Act var response = await _httpClient.SendAsync(request); //Assert response.StatusCode.Should().Be(HttpStatusCode.OK); var idpResponse = JObject.Parse(response.Content.ReadAsStringAsync().Result); var accessToken = idpResponse["access_token"].ToString(); accessToken.Should().NotBeNullOrEmpty(); var handler = new JwtSecurityTokenHandler(); var jwtSecurityToken = handler.ReadToken(accessToken) as JwtSecurityToken; // Audience should be the API and not the user jwtSecurityToken.Audiences.Should().Contain("api://ticketing-core"); jwtSecurityToken.Issuer.Should().Contain("localhost"); }
public Guid?GetCurrentUserId() { if (_contextAccessor?.HttpContext?.Request?.Headers == null) { return(null); } var authenticationBearer = _contextAccessor.HttpContext.Request.Headers.ToList().FirstOrDefault(h => h.Key == "Authorization").Value.ToString(); if (string.IsNullOrEmpty(authenticationBearer) || authenticationBearer.Split("Bearer ").Length != 2) { return(null); } var authCode = authenticationBearer.Split("Bearer ")[1]; var handler = new JwtSecurityTokenHandler(); var tokenS = (JwtSecurityToken)handler.ReadToken(authCode); if (tokenS == null) { return(null); } Guid.TryParse(tokenS.Subject, out var userId); return(userId); }
private async void Signin_OnClick(object sender, RoutedEventArgs e) { try { _adfsTokenService.Init(); var token = await _adfsTokenService.GetTokenAsync(); if (string.IsNullOrEmpty(token)) { return; } var handler = new JwtSecurityTokenHandler(); var securityToken = handler.ReadToken(token); ResultText.Text = securityToken.ToString() !; } catch (Exception exception) { ResultText.Text = exception.Message; } }
public async Task <ActionResult <IEnumerable <Api.Models.Service> > > GetServicesadmin() { String jwt = Request.Headers["Authorization"]; jwt = jwt.Substring(7); //Decode jwt and get payload var stream = jwt; var handler = new JwtSecurityTokenHandler(); var jsonToken = handler.ReadToken(stream); var tokenS = jsonToken as JwtSecurityToken; //I can get Claims using: var email = tokenS.Claims.First(claim => claim.Type == "email").Value; var admin = await _context.Accounts.SingleOrDefaultAsync(p => p.Email == email && p.RoleId == 1); if (admin == null) { return(BadRequest()); } return(await _context.Services .Select(p => new Api.Models.Service() { Id = p.Id, Name = p.Name, IsActive = p.IsActive }).ToListAsync()); }
public static ClaimsPrincipal GetPrincipal(string token) { try { //just check var token1 = new JwtSecurityToken(jwtEncodedString: token); Console.WriteLine("email => " + token1.Claims.First(c => c.Type.ToLower() == "email").Value); //just check JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtToken = (JwtSecurityToken)tokenHandler.ReadToken(token); if (jwtToken == null) { return(null); } byte[] key = Convert.FromBase64String(Secret); TokenValidationParameters parameters = new TokenValidationParameters() { RequireExpirationTime = true, ValidateIssuer = false, ValidateAudience = false, IssuerSigningKey = new SymmetricSecurityKey(key) }; SecurityToken securityToken; ClaimsPrincipal principal = tokenHandler.ValidateToken(token, parameters, out securityToken); return(principal); } catch (Exception e) { return(null); } }
public string GetAgeToken() { string token = HttpContext.Request.Headers["Authorization"]; if (AuthenticationHeaderValue.TryParse(token, out var headerValue)) { // we have a valid AuthenticationHeaderValue that has the following details: var scheme = headerValue.Scheme; var parameter = headerValue.Parameter; // scheme will be "Bearer" // parmameter will be the token itself. var stream = parameter; var handler = new JwtSecurityTokenHandler(); var jsonToken = handler.ReadToken(stream); var tokenS = jsonToken as JwtSecurityToken; var jti = tokenS.Claims.First(claim => claim.Type == "Age").Value; string word = "The Age is : "; var result = word + jti; return(result); } return("Error"); }
public void OnAuthorization(AuthorizationFilterContext context) { var authorization = context.HttpContext.Request.Headers["Authorization"]; if (string.IsNullOrEmpty(authorization) || authorization.ToString().Split(" ")[0].ToLower() != "bearer" || string.IsNullOrEmpty(authorization.ToString().Split(" ")[1])) { throw new Exception("Debe ingresar un token válido para realizar esta operación."); } string token = authorization.ToString().Split(" ")[1]; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); JwtSecurityToken tokenS = handler.ReadToken(token) as JwtSecurityToken; DateTime fin = tokenS.Payload.ValidTo; var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value; var roles = tokenS.Claims.Where(r => r.Type == ClaimTypes.Role).ToList(); if (DateTime.Now > fin) { throw new Exception("El token ha expirado."); } }
//Token kontrol eder. public async Task <ApplicationUser> TokenUser(string oldToken) { var validations = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, ValidateIssuerSigningKey = true, RequireExpirationTime = false, ValidateLifetime = true, ValidIssuer = Configuration["JwtIssuerOptions:Issuer"], ValidAudience = Configuration["JwtIssuerOptions:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AuthSettings:SecretKey"])), ClockSkew = TimeSpan.Zero // remove delay of token when expire }; var tokenHandle = new JwtSecurityTokenHandler(); var tokenRead = tokenHandle.ReadToken(oldToken) as SecurityToken; var s = tokenHandle.ValidateToken(oldToken, validations, out tokenRead); var cl = s.Claims.SingleOrDefault(c => c.Type == "email")?.Value; var user = await userManager.FindByEmailAsync(cl); return(user); }
public async Task <ActionResult <IEnumerable <JobForListResponse> > > Getjobfreelancers(int id) { String jwt = Request.Headers["Authorization"]; jwt = jwt.Substring(7); //Decode jwt and get payload var stream = jwt; var handler = new JwtSecurityTokenHandler(); var jsonToken = handler.ReadToken(stream); var tokenS = jsonToken as JwtSecurityToken; //I can get Claims using: var email = tokenS.Claims.First(claim => claim.Type == "email").Value; var account = await _context.Accounts .Include(p => p.JobFreelancers).ThenInclude(p => p.Renter) .SingleOrDefaultAsync(p => p.Id == id && p.Email == email); if (account == null) { return(NotFound()); } var jobFreelancers = account.JobFreelancers.Select(p => new JobForListResponse(p)).ToList(); return(jobFreelancers); }
public static ClaimsPrincipal GetPrincipal(string token, string jwtSecretKey, bool requireExpiryTime) { var claims = new ClaimsPrincipal(); try { if (!string.IsNullOrEmpty(token)) { IdentityModelEventSource.ShowPII = true; var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.ReadToken(token) as SecurityToken; if (jwtToken != null) { var symmetricKey = Encoding.ASCII.GetBytes(jwtSecretKey); var validationParameters = new TokenValidationParameters() { RequireExpirationTime = requireExpiryTime, ValidateIssuer = false, ValidateAudience = false, IssuerSigningKey = new SymmetricSecurityKey(symmetricKey) }; claims = tokenHandler.ValidateToken(token, validationParameters, out jwtToken); } } } catch (Exception) { throw; } return(claims); }
public Usuario GetUserByToken(string token) { try { var tokenS = handler.ReadToken(token) as JwtSecurityToken; var user = tokenS.Claims.First(claim => claim.Type == "NombreUsuario").Value; var passValue = tokenS.Claims.First(claim => claim.Type == "Contrasena").Value; return(new Usuario { NombreUsuario = user, Contrasena = passValue }); } catch (Exception) { return(new Usuario { NombreUsuario = string.Empty, Contrasena = string.Empty }); } }
private ClaimsPrincipal GetPrincipal(string token) { try { var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken; if (jwtToken == null) { return(null); } string secretKey = _configuration.GetSection("TokenConfiguration")["SecretKey"].ToString(); SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); var validationParameters = new TokenValidationParameters() { RequireExpirationTime = true, ValidateIssuer = false, ValidateAudience = false, IssuerSigningKey = signingKey }; SecurityToken securityToken; var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken); return(principal); } catch (Exception ex) { //should write log string exception = ex.Message; return(null); } }
public void CanDeleteOwnClaims() { HttpResponseMessage response = null !; "When deleting user claims".x( async() => { var request = new HttpRequestMessage { Method = HttpMethod.Delete, RequestUri = new Uri( _fixture.Server.BaseAddress + "resource_owners/claims?type=acceptance_test") }; request.Headers.Authorization = new AuthenticationHeaderValue( "Bearer", _administratorToken.AccessToken); response = await _fixture.Client().SendAsync(request).ConfigureAwait(false); }); "Then is ok request".x(() => { Assert.Equal(HttpStatusCode.OK, response.StatusCode); }); "Then resource owner no longer has claim".x( async() => { var result = await _tokenClient .GetToken(TokenRequest.FromPassword("administrator", "password", new[] { "manager" })) .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result; Assert.NotNull(result.Item); var handler = new JwtSecurityTokenHandler(); var token = (JwtSecurityToken)handler.ReadToken(result.Item.AccessToken); Assert.DoesNotContain(token.Claims, c => c.Type == "acceptance_test"); }); }
public static ClaimsPrincipal GetPrincipal(ref string token) { try { var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken; if (jwtToken == null) { return(null); } var symmetricKey = Convert.FromBase64String(Secret); var validationParameters = new TokenValidationParameters() { RequireExpirationTime = true, ValidateIssuer = true, ValidIssuer = "POCLACC", ValidateAudience = true, ValidAudience = "SGC_POC", IssuerSigningKey = new SymmetricSecurityKey(symmetricKey), ValidateLifetime = true, LifetimeValidator = CustomLifeTimeValidator, }; return(tokenHandler.ValidateToken(token, validationParameters, out SecurityToken securityToken)); } catch (Exception ex) { System.Diagnostics.Debug.Print(ex.Message); return(null); } }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { string code = null; string state = null; IReadableStringCollection query = Request.Query; IList <string> values = query.GetValues("code"); if (values != null && values.Count == 1) { code = values[0]; } values = query.GetValues("state"); if (values != null && values.Count == 1) { state = values[0]; } properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(null); } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(Options.CookieManager, properties, _logger)) { return(new AuthenticationTicket(null, properties)); } string requestPrefix = Request.Scheme + "://" + Request.Host; string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath; // Build up the body for the token request var body = new List <KeyValuePair <string, string> >(); body.Add(new KeyValuePair <string, string>("grant_type", "authorization_code")); body.Add(new KeyValuePair <string, string>("code", code)); body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri)); body.Add(new KeyValuePair <string, string>("client_id", Options.ClientId)); body.Add(new KeyValuePair <string, string>("client_secret", Options.ClientSecret)); // Request the token HttpResponseMessage tokenResponse = await _httpClient.PostAsync(Options.TokenEndpoint, new FormUrlEncodedContent(body)); tokenResponse.EnsureSuccessStatusCode(); string text = await tokenResponse.Content.ReadAsStringAsync(); // Deserializes the token response JObject response = JObject.Parse(text); string idToken = response.Value <string>("id_token"); if (string.IsNullOrWhiteSpace(idToken)) { _logger.WriteWarning("Id token was not found"); return(new AuthenticationTicket(null, properties)); } string accessToken = response.Value <string>("access_token"); if (string.IsNullOrWhiteSpace(accessToken)) { _logger.WriteWarning("Access token was not found"); return(new AuthenticationTicket(null, properties)); } string refreshToken = response.Value <string>("refresh_token"); if (string.IsNullOrWhiteSpace(refreshToken)) { _logger.WriteWarning("Refresh token was not found"); return(new AuthenticationTicket(null, properties)); } int expiresIn = response.Value <int>("expires_in"); //open up id_token var handler = new JwtSecurityTokenHandler(); var token = handler.ReadToken(idToken) as JwtSecurityToken; var id = token.Claims.First(c => c.Type == "sub").Value; var email = token.Claims.First(c => c.Type == "email").Value; var context = new NortonAuthenticatedContext(Context, id, email, idToken, accessToken, refreshToken, expiresIn); context.Identity = new ClaimsIdentity( Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); if (!string.IsNullOrEmpty(context.Id)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, ClaimValueTypes.String, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Email)) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, ClaimValueTypes.String, Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return(new AuthenticationTicket(context.Identity, context.Properties)); } catch (Exception ex) { _logger.WriteError("Authentication failed", ex); return(new AuthenticationTicket(null, properties)); } }
public JwtSecurityToken Decode(string token) { var handler = new JwtSecurityTokenHandler(); return(handler.ReadToken(token) as JwtSecurityToken); }
public HttpResponseMessage AddNewResource([FromBody] Resources model) { var authHeader = this.Request.Headers.GetValues("Authorization").FirstOrDefault(); var token = authHeader.Substring("Bearer ".Length); var handler = new JwtSecurityTokenHandler(); var jsonToken = handler.ReadToken(token); var tokenS = handler.ReadToken(token) as JwtSecurityToken; var UserName = tokenS.Claims.First(claim => claim.Type == "UserName").Value; if (model.AccessLimited == true) { model.EnableStart = model.ESDate.Add(model.ESTime); model.EnableEnd = model.EEDate.Add(model.EETime); } var r = RBL.AddNewResource(model, UserName); if (r > 0) { #region Email Resources Res = RBL.ResourceDetails(r); MailAddressCollection emailtoBCC = new MailAddressCollection(); List <Users> Subscribers = USBL.Subscribers(r, false); if (Subscribers.Count() > 0) { foreach (var item in Subscribers) { emailtoBCC.Add(item.Email); } } string body = string.Empty; using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/Views/EmailTemplates/NewResource.html"))) { body = reader.ReadToEnd(); } body = body.Replace("{ResourceTypeID}", Res.ResourceTypeID.ToString()); body = body.Replace("{TypeName}", Res.TypeName); body = body.Replace("{FileName}", Res.FileName); body = body.Replace("{Description}", Res.Description); Emails Email = new Emails() { FromEmail = ConfigurationManager.AppSettings["AdminEmail"].ToString(), ToEmail = ConfigurationManager.AppSettings["Subscribers"].ToString(), SubjectEmail = "Oasis Alajuela ha subido un Recurso", BodyEmail = body }; MailMessage mm = new MailMessage(Email.FromEmail, Email.ToEmail) { Subject = Email.SubjectEmail, Body = Email.BodyEmail, IsBodyHtml = true, BodyEncoding = Encoding.GetEncoding("utf-8") }; if (Subscribers.Count() > 0) { mm.Bcc.Add(emailtoBCC.ToString()); } SmtpClient smtp = new SmtpClient(); smtp.Send(mm); #endregion return(this.Request.CreateResponse(HttpStatusCode.OK, true)); } else { return(this.Request.CreateResponse(HttpStatusCode.InternalServerError)); } }
private async Task <Token> RequisitarToken() { using var client = new HttpClient(); var disco = await client.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest { Address = _urlAutenticacao, Policy = new DiscoveryPolicy { RequireHttps = _urlAutenticacao.ToLower().StartsWith("https") } }); if (disco.IsError) { throw disco.Exception; } if (!string.IsNullOrEmpty(_loginUsuario) && _claims != null) { var responseToken = await client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = disco.TokenEndpoint, ClientId = _clienteId, ClientSecret = _clienteSenha, Scope = _escopo, UserName = _loginUsuario, Password = _senhaUsuario, Parameters = _claims }); if (responseToken.IsError) { throw new UnauthorizedAccessException(); } var handler = new JwtSecurityTokenHandler(); var securityToken = handler.ReadToken(responseToken.AccessToken) as JwtSecurityToken; return(new Token { Access = responseToken.AccessToken, Claims = securityToken.Payload.SerializeToJson() }); } var response = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = _clienteId, ClientSecret = _clienteSenha, Scope = _escopo, }); return(new Token { Access = response.AccessToken }); }
public async Task <ApiResponse <UserProfileDetailsApiModel> > RefreshToken( [FromBody] TokenModel tokenModel) { // TODO: Localize all strings // The message when we fail to login var invalidErrorMessage = "Nie możemy odnowić sesji!"; var invalidErrorMessage2 = "Coś poszło nie tak"; var invalidErrorMessage3 = "Prosimy o ponowne zalogowanie"; // The error response for a failed login var errorResponse = new ApiResponse <UserProfileDetailsApiModel> { // Set error message ErrorMessage = invalidErrorMessage }; var errorResponse2 = new ApiResponse <UserProfileDetailsApiModel> { // Set error message ErrorMessage = invalidErrorMessage2 }; var errorResponse3 = new ApiResponse <UserProfileDetailsApiModel> { // Set error message ErrorMessage = invalidErrorMessage3 }; // Make sure we have a user name if (tokenModel.Token == null) { // Return error message to user return(errorResponse); } // Validate if the user credentials are correct... // Is it an email? var handler = new JwtSecurityTokenHandler(); var handleraccessToken = handler.ReadToken(tokenModel.Token) as JwtSecurityToken; if (handleraccessToken == null) { return(errorResponse2); } var username = handleraccessToken.Claims.First(claim => claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value; var tokenExpirationDate = handleraccessToken.ValidTo; var user = await mUserManager.FindByNameAsync(username); if (user == null) { return(errorResponse2); } if (user.RefreshToken == null) { return(errorResponse3); } var refreshToken = user.RefreshToken; var handlerRefreshToken = handler.ReadToken(refreshToken) as JwtSecurityToken; if (handlerRefreshToken == null) { return(errorResponse2); } var refreshTokenExpirationDate = handlerRefreshToken.ValidTo; var roles = await mUserManager.GetRolesAsync(user); string role = ""; foreach (var r in roles) { role = r; } //var refreshToken = mContext.UserAccount.Where() if (tokenExpirationDate < DateTime.Now) { if (refreshTokenExpirationDate < DateTime.Now) { return(errorResponse3); } return(new ApiResponse <UserProfileDetailsApiModel> { // Pass back the user details and the token Response = new UserProfileDetailsApiModel { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, Username = user.UserName, Token = user.GenerateJwtToken(role), } }); } return(errorResponse2); }
public async Task <IActionResult> OnPostAsync(string returnURL = "/index") { if (!ModelState.IsValid) { return(Page()); } var values = new Dictionary <string, string> { { "username", Username }, { "password", Password } }; HttpClient client = new HttpClient(); var content = new StringContent("{\"username\":\"" + Username + "\",\"password\": \"" + Password + "\"}", Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://api-gateway-343.herokuapp.com/auth/login", content); var responseString = await response.Content.ReadAsStringAsync(); try { Response resp = JsonConvert.DeserializeObject <Response>(responseString); if (!resp.Status) { Error = "Username or Password is incorrect. Please try again"; return(Page()); } else { var jwt = resp.Token; string[] parts = jwt.Split(".".ToCharArray()); var header = parts[0]; var payload = parts[1]; var signature = parts[2];//Base64UrlEncoded signature from the token byte[] bytesToSign = Encoding.UTF8.GetBytes(string.Join(".", header, payload)); byte[] secret = Encoding.UTF8.GetBytes("secretkey"); var alg = new HMACSHA256(secret); var hash = alg.ComputeHash(bytesToSign); var computedSignature = Base64UrlEncode(hash); if (signature != computedSignature) { Error = "Something went wrong. Please try again."; return(Page()); } var handler = new JwtSecurityTokenHandler(); var token = handler.ReadToken(jwt) as JwtSecurityToken; var userID = token.Claims.First(claim => claim.Type == "id").Value; var userType = token.Claims.First(claim => claim.Type == "accountType").Value; if (userType != "employee") { Error = "Username or Password is incorrect. Please try again"; return(Page()); } EmployeeUtil empUtil = new EmployeeUtil(_context); EmployeeAPIDAO userEmployee = empUtil.GetEmployeeByUserId(Convert.ToInt32(userID)); var userRole = userEmployee.RoleName; // var role = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value; var claims = new List <Claim> { new Claim(ClaimTypes.Name, Username), new Claim(ClaimTypes.Name, jwt), new Claim(ClaimTypes.Role, userRole), new Claim(ClaimTypes.PrimarySid, Convert.ToString(userEmployee.Id)) }; var userIdentity = new ClaimsIdentity(claims, "login"); ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return(Redirect(returnURL)); } } catch (JsonReaderException) { Error = "Username or Password is incorrect. Please try again"; return(Page()); } }
public void CreateAndValidateTokens_JsonClaims() { List <string> errors = new List <string>(); string issuer = "http://www.GotJWT.com"; string claimSources = "_claim_sources"; string claimNames = "_claim_names"; JwtPayload jwtPayloadClaimSources = new JwtPayload(); jwtPayloadClaimSources.Add(claimSources, JsonClaims.ClaimSources); jwtPayloadClaimSources.Add(claimNames, JsonClaims.ClaimNames); JwtSecurityToken jwtClaimSources = new JwtSecurityToken( new JwtHeader(), jwtPayloadClaimSources); JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler(); string encodedJwt = jwtHandler.WriteToken(jwtClaimSources); var validationParameters = new TokenValidationParameters { IssuerValidator = (s, st, tvp) => { return(issuer); }, RequireSignedTokens = false, ValidateAudience = false, ValidateLifetime = false, }; SecurityToken validatedJwt = null; var claimsPrincipal = jwtHandler.ValidateToken(encodedJwt, validationParameters, out validatedJwt); if (!IdentityComparer.AreEqual (claimsPrincipal.Identity as ClaimsIdentity, JsonClaims.ClaimsIdentityDistributedClaims(issuer, TokenValidationParameters.DefaultAuthenticationType, JsonClaims.ClaimSources, JsonClaims.ClaimNames))) { errors.Add("JsonClaims.ClaimSources, JsonClaims.ClaimNames: test failed"); } ; Claim c = claimsPrincipal.FindFirst(claimSources); if (!c.Properties.ContainsKey(JwtSecurityTokenHandler.JsonClaimTypeProperty)) { errors.Add(claimSources + " claim, did not have json property: " + JwtSecurityTokenHandler.JsonClaimTypeProperty); } else { if (!string.Equals(c.Properties[JwtSecurityTokenHandler.JsonClaimTypeProperty], typeof(IDictionary <string, object>).ToString(), StringComparison.Ordinal)) { errors.Add("!string.Equals(c.Properties[JwtSecurityTokenHandler.JsonClaimTypeProperty], typeof(IDictionary<string, object>).ToString(), StringComparison.Ordinal)" + "value is: " + c.Properties[JwtSecurityTokenHandler.JsonClaimTypeProperty]); } } JwtSecurityToken jwtWithEntity = new JwtSecurityToken( new JwtHeader(), new JwtPayload(claims: ClaimSets.EntityAsJsonClaim(issuer, issuer))); encodedJwt = jwtHandler.WriteToken(jwtWithEntity); JwtSecurityToken jwtRead = jwtHandler.ReadToken(encodedJwt) as JwtSecurityToken; SecurityToken validatedToken; var cp = jwtHandler.ValidateToken(jwtRead.RawData, validationParameters, out validatedToken); Claim jsonClaim = cp.FindFirst(typeof(Entity).ToString()); if (jsonClaim == null) { errors.Add("Did not find Jsonclaims. Looking for claim of type: '" + typeof(Entity).ToString() + "'"); } ; string jsString = JsonExtensions.SerializeToJson(Entity.Default); if (!string.Equals(jsString, jsonClaim.Value, StringComparison.Ordinal)) { errors.Add(string.Format(CultureInfo.InvariantCulture, "Find Jsonclaims of type: '{0}', but they weren't equal.\nExpecting:\n'{1}'.\nReceived:\n'{2}'", typeof(Entity).ToString(), jsString, jsonClaim.Value)); } TestUtilities.AssertFailIfErrors(MethodInfo.GetCurrentMethod().Name, errors); }
public static JwtPayload Parse(string token) { var jwt = _handler.ReadToken(token) as JwtSecurityToken; return(jwt.Payload); }
protected void Page_Load(object sender, EventArgs e) { if (Request.IsAuthenticated) { ImageButton1.Enabled = true; itokenStr = string.Empty; atokenStr = string.Empty; //extract the id token and access token from the claims sent back from the sign-in widget var claimsList = HttpContext.Current.GetOwinContext().Authentication.User.Claims.ToList(); foreach (var claimItem in claimsList) { if (claimItem.Type == "id_token") { itokenStr = claimItem.Value; } else if (claimItem.Type == "access_token") { atokenStr = claimItem.Value; } if ((itokenStr.Length > 0) && (atokenStr.Length > 0)) { break; } } //display id token claims in a table if (itokenStr != string.Empty) { var ihandler = new JwtSecurityTokenHandler(); var ijsonToken = ihandler.ReadToken(itokenStr); var itokenS = ihandler.ReadToken(itokenStr) as JwtSecurityToken; GridViewID.DataSource = itokenS.Claims.Select(x => new { Name = x.Type, Value = x.Value }); GridViewID.DataBind(); } //display access token claims in a table if (atokenStr != string.Empty) { var ahandler = new JwtSecurityTokenHandler(); var ajsonToken = ahandler.ReadToken(atokenStr); var atokenS = ahandler.ReadToken(atokenStr) as JwtSecurityToken; GridViewAccess.DataSource = atokenS.Claims.Select(x => new { Name = x.Type, Value = x.Value }); GridViewAccess.DataBind(); var tokenList = atokenS.Claims.ToList(); foreach (var tokenItem in tokenList) { if (tokenItem.Type == "ssn") { ssnValue = tokenItem.Value; break; } } } Label3.Visible = true; Label4.Visible = true; } else { Label1.Text = "Please authenticate to get to your data."; } }