public string CreateToken() { WebToken token = Get(); var plainTextSecurityKey = "ABCD-12134-HAGS-JKSJA57"; var signingKey = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(plainTextSecurityKey)); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); //Saml Decrypt var claimsIdentity = new ClaimsIdentity(new List <Claim>() { new Claim(ClaimTypes.Name, "Pankaj"), new Claim(ClaimTypes.Email, "*****@*****.**"), new Claim("Authority", token.Authority), new Claim("Role", token.Role), new Claim("Team", token.Team) }, "Custom"); var securityTokenDescriptor = new SecurityTokenDescriptor() { AppliesToAddress = "http://my.website.com", TokenIssuerName = BaseURL, Subject = claimsIdentity, SigningCredentials = signingCredentials, Lifetime = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(2)), }; var tokenHandler = new JwtSecurityTokenHandler(); var plainToken = tokenHandler.CreateToken(securityTokenDescriptor); var signedAndEncodedToken = tokenHandler.WriteToken(plainToken); return(signedAndEncodedToken); }
protected string GenerateToken(AuthServerRequest authRequest, string issuer, IAdditionalClaimsProvider additionalClaimsProvider) { WebToken tokenObject = new WebToken(); tokenObject.Issuer = issuer; List <KeyValuePair <string, string> > additionalClaims = null; if (authRequest.GrantType == "password") { tokenObject.AddClaim(ClaimTypes.Name, authRequest.Username); if (!string.IsNullOrEmpty(authRequest.ClientId)) { tokenObject.AddClaim("ClientId", authRequest.ClientId); } additionalClaims = additionalClaimsProvider.GetAdditionalUserClaims(authRequest.Username); } else if (authRequest.GrantType == "client") { tokenObject.AddClaim("ClientId", authRequest.ClientId); additionalClaims = additionalClaimsProvider.GetAdditionalClientClaims(authRequest.ClientId); } if ((additionalClaims != null) && (additionalClaims.Count > 0)) { foreach (var kvp in additionalClaims) { tokenObject.AddClaim(kvp.Key, kvp.Value); } } return(tokenObject.GenerateToken(_crypter, _options.CryptionKey)); }
protected virtual WebToken ExtractSecurityTokenFromResponse(ProtocolResponse oauthResponse) { string lifetime = oauthResponse.BodyParameters["wrap_access_token_expires_in"]; string accessTokenString = oauthResponse.BodyParameters["wrap_access_token"]; var token = new WebToken(accessTokenString); token.Expiration.AddSeconds(int.Parse(lifetime)); return(token); }
public async Task <AuthenticatedUserDto> Handle(AuthWithRefreshToken request, CancellationToken cancellationToken) { if (request.Token == Guid.Empty) { throw new InvalidCredentialException("Invalid grant type"); } FilterDefinition <RefreshToken> filter = Builders <RefreshToken> .Filter .And(new FilterDefinition <RefreshToken>[] { Builders <RefreshToken> .Filter.Eq(x => x.Token, request.Token), Builders <RefreshToken> .Filter.Eq(x => x.IsActive, true), Builders <RefreshToken> .Filter.Lte(x => x.ExpirationDate, DateTime.UtcNow) }); RefreshToken refreshToken = await _refreshTokenRepository.Get(filter, cancellationToken); if (refreshToken == null) { throw new InvalidCredentialException("Invalid Credentials"); } User user = await _userRepository.Get(refreshToken.UserId, cancellationToken); if (user == null) { throw new InvalidCredentialException("Invalid Credentials"); } try { WebToken webToken = await _mediator.Send(new GenerateWebToken() { User = user }, cancellationToken); refreshToken.IsActive = false; await _refreshTokenRepository.Update(refreshToken, cancellationToken); await _refreshTokenRepository.Delete(Builders <RefreshToken> .Filter.Eq(x => x.IsActive, false), cancellationToken); return(new AuthenticatedUserDto { Token = webToken, User = _mapper.Map <UserDto>(user), }); } catch (Exception ex) { throw new InvalidCredentialException("", ex); } }
public static WebToken DecodeWebToken(string tokenString) { var jwtHandler = new JwtSecurityTokenHandler(); SecurityToken tokenString1 = jwtHandler.ReadToken(tokenString); string jsonCompactSerializedString = jwtHandler.WriteToken(tokenString1); string encodedPayload = jsonCompactSerializedString.Split('.')[1]; string decodedPayload = Base64UrlDecode(encodedPayload); WebToken jsonWebToken = WebToken.FromJson(decodedPayload); return(jsonWebToken); }
public WebToken Get() { //Web Service call; WebToken wt = new WebToken() { Authority = "Noida", Role = "ADMIN", Team = "NOIDA-ADMIN" }; return(wt); }
private string RequestAccessToken() { if (_cachedToken == null || _cachedToken.Expiration < DateTime.Now.AddMinutes(1)) { Dictionary <string, string> parameters = CreateAccessTokenRequestParameters(); ProtocolRequest oauthRequest = CreateProtocolRequest(parameters); ProtocolResponse oauthResponse = _httpClient.SendRequest(oauthRequest); _cachedToken = ExtractSecurityTokenFromResponse(oauthResponse); } return(_cachedToken.Token); }
public static void TestWebTokens() { Crypt crypt = new Crypt(); string key = "LL132-xzJ41-N11!"; WebToken token = new WebToken(); token.CreatedDate = DateTime.Now; token.Issuer = "Test Issuer"; token.AddClaim("username", "admin"); token.AddClaim("cityofbirth", "Parañaque"); string encryptedToken = token.GenerateToken(crypt, key); WebToken decryptedToken = WebToken.DecryptToken(encryptedToken, crypt, key); var dummy = 3; }
public async Task <AuthenticatedUserDto> Handle(Authenticate request, CancellationToken cancellationToken) { AuthenticateValidator validator = new AuthenticateValidator(); ValidationResult validationResult = await validator.ValidateAsync(request, cancellationToken); if (!validationResult.IsValid) { throw new EntityValidationException(nameof(User), request, validationResult.Errors); } User user = await _userRepository.Get(Builders <User> .Filter.Eq(x => x.Username, request.Username), cancellationToken); if (user == null) { throw new InvalidCredentialException("Invalid username or password"); } bool hasCorrectPassword = await _securityService.VerifyPassword(request.Password, user.Password); if (!hasCorrectPassword) { throw new InvalidCredentialException("Invalid username or password"); } try { WebToken webToken = await _mediator.Send(new GenerateWebToken() { User = user }, cancellationToken); return(new AuthenticatedUserDto { User = _mapper.Map <UserDto>(user), Token = webToken, }); } catch (EntityNotFoundException ex) { throw new InvalidCredentialException("", ex); } }
protected string RequestAccessToken() { if (_cachedToken == null || _cachedToken.Expiration < DateTime.Now.AddMinutes(1)) { Dictionary <string, string> bodyParameters = CreateAccessTokenRequestParameters(); UrlParts url = new UrlParts(TokenEndpoint) { Path = TokenEndpoint.AbsolutePath }; ProtocolRequest oauthRequest = CreateProtocolRequest(url, bodyParameters); ProtocolResponse oauthResponse = _httpClient.SendRequest(oauthRequest); _cachedToken = ExtractSecurityTokenFromResponse(oauthResponse); } return(_cachedToken.Token); }
public async Task <AuthenticatedUserDto> Handle(AuthenticateUser request, CancellationToken cancellationToken) { AuthenticateUserValidator validator = new AuthenticateUserValidator(); ValidationResult validationResult = await validator.ValidateAsync(request, cancellationToken); if (!validationResult.IsValid) { throw new EntityValidationException(nameof(AuthenticateUser), request, validationResult.Errors); } User user = await _mainDbContext.Users .AsNoTracking() .Where(u => u.Email == request.Email && !u.IsDeleted) .FirstOrDefaultAsync(cancellationToken); if (user.Equals(null)) { throw new InvalidCredentialException(); } string passwordHash = user.Password; bool isPasswordValid = BCrypt.Net.BCrypt.Verify(request.Password, passwordHash); if (!isPasswordValid) { throw new InvalidCredentialException(); } WebToken webToken = await _mediator.Send(new GenerateToken(), cancellationToken); return(new AuthenticatedUserDto { User = _mapper.Map <UserDto>(user), WebToken = webToken, }); }
public async Task Invoke(HttpContext context) { if (context.Request.Headers.ContainsKey("Authorization")) { string[] values = context.Request.Headers["Authorization"].ToString().Split(' '); if (values.Length != 2) { context.Response.StatusCode = StatusCodes.Status400BadRequest; context.Response.ContentType = "application/json;charset=utf-8"; await context.Response.WriteAsync($"[\"{ResourceServerMessages.InvalidAuthorizationHeader}\"]"); return; } if (values.First() != "Bearer") { context.Response.StatusCode = StatusCodes.Status400BadRequest; context.Response.ContentType = "application/json;charset=utf-8"; await context.Response.WriteAsync($"[\"{ResourceServerMessages.AuthorizationBearerRequired}\"]"); return; } try { string webTokenJsonString = _crypter.Decrypt(values[1], _resourceServerOptions.CryptionKey); WebToken webToken = JsonConvert.DeserializeObject <WebToken>(webTokenJsonString); if (webToken.Issuer != _resourceServerOptions.Issuer) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json;charset=utf-8"; await context.Response.WriteAsync($"[\"{ResourceServerMessages.IssuersDoNotMatch}\"]"); return; } DateTime tokenExpiration = webToken.CreatedDate.AddDays(_resourceServerOptions?.TokenDurationInDays ?? 14); if (DateTime.Now > tokenExpiration) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json;charset=utf-8"; await context.Response.WriteAsync($"[\"{ResourceServerMessages.TokenExpired}\"]"); return; } // Now, we have to write the claims to the ClaimsPrincipal! context.User = webToken.ConvertToClaimsPrincipal(); } catch (Exception e) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.ContentType = "application/json;charset=utf-8"; await context.Response.WriteAsync($"[\"{e.Message}\"]"); } } await _next.Invoke(context); }