private JwtSecurityToken GetAuthenticationTokenForUser(string userId) => AppServiceLoginHandler.CreateToken( GetClaims(userId), Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY"), _siteUrl, _siteUrl, _accessTokenLifetime);
public IHttpActionResult Post([FromBody] UserModel body) { if (body == null || body.Email == null || body.Password == null || body.Email.Length == 0 || body.Password.Length == 0) { return(BadRequest()); } if (!IsValidUser(body)) { return(Unauthorized()); } var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, body.Email) }; JwtSecurityToken token = AppServiceLoginHandler.CreateToken( claims, signingKey, audience, issuer, TimeSpan.FromDays(30)); this.notificationsProvider.AddTagToRegistration(body.Installation, body.Email); return(Ok(new LoginResult() { AuthenticationToken = token.RawData, User = new LoginResultUser { UserId = body.Email } })); }
public HttpResponseMessage Post(LoginRequest loginRequest) { if (string.IsNullOrEmpty(loginRequest.Login) || string.IsNullOrEmpty(loginRequest.Password)) { return(Request.CreateBadRequestResponse("Login and Password should not be null")); } var context = new AptkAmaContext(); var account = context.Accounts.SingleOrDefault(a => a.Login == loginRequest.Login); if (account != null) { var incoming = CustomLoginProviderUtils.Hash(loginRequest.Password, account.Salt); if (CustomLoginProviderUtils.SlowEquals(incoming, account.SaltedAndHashedPassword)) { var token = AppServiceLoginHandler.CreateToken(new[] { new Claim(JwtRegisteredClaimNames.Sub, loginRequest.Login) }, GetSigningKey(), _host, _host, TimeSpan.FromHours(24)); var customLoginResult = new JObject { { "userId", account.Id }, { "mobileServiceAuthenticationToken", token.RawData } }; return(this.Request.CreateResponse(HttpStatusCode.OK, customLoginResult)); } } return(this.Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid username or password")); }
public string Protect(AuthenticationTicket data) { //original implementation here: http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/ if (data == null) { throw new ArgumentNullException("data"); } string audience = GetHost(); string issuer = GetHost(); string appSignKey = GetSigningKey(); JwtSecurityToken token = AppServiceLoginHandler.CreateToken( data.Identity.Claims, appSignKey, audience, issuer, TimeSpan.FromHours(24) ); var handler = new JwtSecurityTokenHandler(); var jwt = handler.WriteToken(token); return(jwt); }
private JwtSecurityToken GetAuthenticationTokenForUser(string username) { var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, username), new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.NameIdentifier, username), }; var thisUrl = string.Format("https://{0}/", Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")); var signingKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY"); var audience = thisUrl; // audience must match the url of the site var issuer = thisUrl; // audience must match the url of the site JwtSecurityToken token = AppServiceLoginHandler.CreateToken( claims, signingKey, audience, issuer, TimeSpan.FromHours(tokenLifetimeExceptionHours) ); return(token); }
/// <summary> /// /// </summary> /// <param name="appUser"></param> /// <returns></returns> private async Task <LoginResult> ConstructLoginResult(ApplicationUser appUser) { var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, appUser.Email), new Claim(JwtRegisteredClaimNames.GivenName, appUser.FullName), new Claim(ClaimTypes.PrimarySid, appUser.Id) }; var userRoles = await UserManager.GetRolesAsync(appUser.Id); foreach (var userRole in userRoles) { claims.Add(new Claim(ClaimTypes.Role, userRole)); } var token = AppServiceLoginHandler.CreateToken(claims, _signingKey, _audience, _issuer, TimeSpan.FromHours(_jwtTokenExpirationTimeInHours)); var user = DbContext.Set <User>().Find(appUser.Id); return(new LoginResult() { AuthenticationToken = token.RawData, User = user }); }
public IHttpActionResult Post([FromBody] User body) { if (body == null || body.Username == null || body.Password == null || body.Username.Length == 0 || body.Password.Length == 0) { return(BadRequest());; } if (!IsValidUser(body)) { return(Unauthorized()); } var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, body.Username) }; JwtSecurityToken token = AppServiceLoginHandler.CreateToken( claims, signingKey, audience, issuer, TimeSpan.FromDays(30)); return(Ok(new LoginResult() { AuthenticationToken = token.RawData, User = new LoginResultUser { UserId = body.Username } })); }
public IHttpActionResult Post([FromBody] LoginRequest loginRequest) { if (ModelState.IsValid) { var userBusinessObject = _userServiceManager.Authenticate(Mapper.Map <LoginBusinessObject>(loginRequest)); if (userBusinessObject != null) // user-defined function, checks against a database { var token = AppServiceLoginHandler.CreateToken( new[] { new Claim(JwtRegisteredClaimNames.Sub, loginRequest.UserName) }, Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY"), ConfigurationManager.AppSettings["ValidAudience"], ConfigurationManager.AppSettings["ValidIssuer"], TimeSpan.FromHours(24)); UserModel userModel = null; userModel = Mapper.Map <UserModel>(userBusinessObject); return(Ok(new LoginRepsponse { AuthenticationToken = token.RawData, User = userModel, IsSuccessful = true })); } } // user authentication was not successfull return(Unauthorized()); }
public IHttpActionResult Login([FromBody] JObject assertion) { var user = ValidateLogin((string)assertion.GetValue("userName"), (string)assertion.GetValue("password")); if (user != null) // user-defined function, checks against a database { JwtSecurityToken token = AppServiceLoginHandler.CreateToken(new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, (string)assertion["userName"]) }, Constants.SigningKey, Constants.AppURL, Constants.AppURL, TimeSpan.FromHours(24)); return(Ok(new LoginResult() { IsAuthorized = true, AuthenticationToken = token.RawData, User = user })); } else // user assertion was not valid { return(Ok(new LoginResult() { IsAuthorized = false })); } }
private JwtSecurityToken GetAuthenticationTokenForUser(string email) { var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, email.Split('@')[0]), new Claim(JwtRegisteredClaimNames.Email, email), }; // The WEBSITE_AUTH_SIGNING_KEY variable will be only available when // you enable App Service Authentication in your App Service from the Azure back end https: //azure.microsoft.com/en-us/documentation/articles/app-service-mobile-dotnet-backend-how-to-use-server-sdk/#how-to-work-with-authentication var signingKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY"); var audience = UsersController.JWT_SECURITY_TOKEN_AUDIENCE; var issuer = UsersController.JWT_SECURITY_TOKEN_ISSUER; var token = AppServiceLoginHandler.CreateToken( claims, signingKey, audience, issuer, TimeSpan.FromDays(UsersController.AUTH_TOKEN_MAX_DURATION) ); return(token); }
public async Task <IHttpActionResult> Post(LoginViewModel model) { var user = await userManager.FindAsync(model.UserName, model.Password); if (user == null) { return(BadRequest("Invalid User and Password")); } var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, user.Id), new Claim("UserName", user.UserName), new Claim("UserId", user.Id) }; JwtSecurityToken token = AppServiceLoginHandler.CreateToken( claims, EnvironmentVariables.SigningKey, EnvironmentVariables.Website, EnvironmentVariables.Website, TimeSpan.FromDays(7)); return(Ok(new { AuthenticationToken = token.RawData, User = new { UserId = user.Id, UserName = user.UserName } })); }
private static NotificationInstallationsController InitializeAuthenticatedController() { string signingKey = "6523e58bc0eec42c31b9635d5e0dfc23b6d119b73e633bf3a5284c79bb4a1ede"; // SHA256 hash of 'secret_key' HttpConfiguration config = new HttpConfiguration(); AppServiceTokenHandler handler = new AppServiceTokenHandler(config); string url = "http://localhost"; Claim[] claims = new Claim[] { new Claim("sub", "my:userid") }; // Create a token the same way as App Service Authentication JwtSecurityToken token = AppServiceLoginHandler.CreateToken(claims, signingKey, url, url, TimeSpan.FromDays(10)); // Validate that token and parse it into a ClaimsPrincipal the same way as App Service Authentication ClaimsPrincipal user = null; string[] validIssAud = new[] { url }; handler.TryValidateLoginToken(token.RawData, signingKey, validIssAud, validIssAud, out user); NotificationInstallationsController controller = new NotificationInstallationsController(); controller.Configuration = config; controller.Request = new HttpRequestMessage(); controller.User = user; return(controller); }
public IHttpActionResult Post([FromBody] JObject assertion) { var userId = Guid.NewGuid().ToString(); var cred = assertion.ToObject <AnonymousUserCredentials>(); if (!string.IsNullOrEmpty(cred.AnonymousUserId)) { Guid impersonate; if (Guid.TryParse(cred.AnonymousUserId, out impersonate)) { userId = impersonate.ToString(); } } IEnumerable <Claim> claims = GetAccountClaims(userId); string websiteUri = $"https://{WebsiteHostName}/"; JwtSecurityToken token = AppServiceLoginHandler.CreateToken(claims, TokenSigningKey, websiteUri, websiteUri, TimeSpan.FromDays(10)); return(Ok(new LoginResult { RawToken = token.RawData, User = new User { UserId = userId } })); }
private JwtSecurityToken GetJwtSecurityToken(User user) { IEnumerable <Claim> claims = GetAccountClaims(user); string websiteUri = $"https://{WebsiteHostName}/"; return(AppServiceLoginHandler .CreateToken(claims, TokenSigningKey, websiteUri, websiteUri, TimeSpan.FromDays(30))); }
public void CreateToken_Throws_IfClaimsNull() { Claim[] claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, UserId) }; ArgumentNullException ex = Assert.Throws <ArgumentNullException>(() => AppServiceLoginHandler.CreateToken(null, SigningKey, Audience, Issuer, TimeSpan.FromDays(10))); }
private static JwtSecurityToken GetTestToken() { Claim[] claims = new Claim[] { new Claim("sub", "Facebook:1234") }; JwtSecurityToken token = AppServiceLoginHandler.CreateToken(claims, SigningKey, TestWebsiteUrl, TestWebsiteUrl, TimeSpan.FromDays(30)); return(token); }
public static string CreateToken(string accountId) { var token = AppServiceLoginHandler.CreateToken(new[] { new Claim(JwtRegisteredClaimNames.Sub, accountId) }, ConfigurationManager.AppSettings["SigningKey"], ConfigurationManager.AppSettings["ValidAudience"], ConfigurationManager.AppSettings["ValidIssuer"], TimeSpan.FromHours(24)); return(token.RawData); }
public async Task <string> CreateTokenMSCLient(UserAccount assertion) { var token = AppServiceLoginHandler.CreateToken( await GetValidClaims(assertion), _signingKey, _audience, _issuer, TimeSpan); return(token.RawData); }
public void TryValidateLoginToken_RejectsTokensSignedWithWrongKey() { JwtSecurityToken token = AppServiceLoginHandler.CreateToken(DefaultClaims, this.testSecretKey, this.testWebsiteUrls[0], this.testWebsiteUrls[0], null); ClaimsPrincipal claimsPrincipal = null; string anotherKey = "f12aca0581d81554852c5cb1314ee230395b349bdf828bb3e1ce8d556cfd4c5a"; // SHA256 hash of 'another_key' bool isValid = this.tokenHandler.TryValidateLoginToken(token.RawData, anotherKey, this.testWebsiteUrls, this.testWebsiteUrls, out claimsPrincipal); Assert.False(isValid); Assert.Null(claimsPrincipal); }
public async Task <IHttpActionResult> Get() { var creds = await User.GetAppServiceIdentityAsync <AzureActiveDirectoryCredentials>(Request); var sid = ((ClaimsPrincipal)User).FindFirst(ClaimTypes.NameIdentifier).Value; string name, email; try { email = creds.UserId; name = creds.UserClaims.FirstOrDefault(claim => claim.Type.Equals("name")).Value; } catch (Exception) { return(BadRequest("Email or Name is not present")); } try { // Insert the record information into the database User user = new User() { Id = sid, Name = name, EmailAddress = email }; dbContext.Users.AddOrUpdate(user); dbContext.SaveChanges(); } catch (DbUpdateException ex) { return(InternalServerError(ex)); } // Mind a new token based on the old one plus the new information var newClaims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, sid), new Claim(JwtRegisteredClaimNames.Email, email), new Claim("name", name) }; JwtSecurityToken token = AppServiceLoginHandler.CreateToken( newClaims, SigningKey, Audience, Issuer, TimeSpan.FromDays(30)); // Return the token and user ID to the client return(Ok(new LoginResult() { AuthenticationToken = token.RawData, UserId = sid })); }
/// <summary> /// Makes a test token out of the specified claims, or a set of default claims if claims is unspecified. /// </summary> /// <param name="claims">The claims identity to make a token. Issuer and Audience in the claims will not be changed.</param> /// <param name="options">The <see cref="AppServiceAuthenticationOptions"/> object that wraps the signing key.</param> /// <param name="audience">The accepted valid audience used if claims is unspecified.</param> /// <param name="issuer">The accepted valid issuer used if claims is unspecified.</param> /// <returns></returns> private static JwtSecurityToken GetTestToken(string signingKey = SigningKeyAlpha, string audience = TestWebsiteUrl, string issuer = TestWebsiteUrl, List <Claim> claims = null) { if (claims == null || claims.Count == 0) { claims = new List <Claim>(); claims.Add(new Claim("sub", "Facebook:1234")); claims.Add(new Claim(ClaimTypes.GivenName, "Frank")); claims.Add(new Claim(ClaimTypes.Surname, "Miller")); claims.Add(new Claim(ClaimTypes.Role, "Admin")); claims.Add(new Claim("my_custom_claim", "MyClaimValue")); } return(AppServiceLoginHandler.CreateToken(claims, signingKey, audience, issuer, TimeSpan.FromDays(10))); }
public IHttpActionResult Post([FromBody] User body) { //Checking if the incoming request has missing data if (body == null || body.Email == null || body.Password == null || body.Email.Length == 0 || body.Password.Length == 0) { return(BadRequest());; } //Checking if the user is valid and exists if (!IsValidUser(body)) { return(Unauthorized()); } //Checking if the user Email is confirmed if (!IsEmailConfirmed(body)) { throw new Exception(); } //Creating debugging session in the backend to detect execution issues var telemetry = new TelemetryClient(); try { //Checking the claims combined with the HTTP request to create token var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, body.Email) }; JwtSecurityToken token = AppServiceLoginHandler.CreateToken( claims, signingKey, audience, issuer, TimeSpan.FromDays(30)); //Returning the authentication token return(Ok(new LoginResult() { AuthenticationToken = token.RawData, User = new LoginResultUser { UserId = body.Email } })); } catch (Exception ex) { telemetry.TrackException(ex); return(InternalServerError()); } }
public void CreateTokenInfo_AndValidateLoginToken_Works() { AppServiceAuthenticationOptions options = this.CreateTestOptions(); Claim[] claims = new Claim[] { new Claim("sub", this.credentials.UserId), }; // Create a login token for the provider JwtSecurityToken token = AppServiceLoginHandler.CreateToken(claims, this.testSecretKey, this.testWebsiteUrls[0], this.testWebsiteUrls[0], Lifetime); this.ValidateLoginToken(token.RawData, options); }
// POST api/CustomLogin public IHttpActionResult Post([FromBody] LoginRequest loginRequest) { if (loginRequest == null || loginRequest.Username == null || loginRequest.Password == null || loginRequest.Username.Length == 0 || loginRequest.Password.Length == 0) { return(BadRequest());; } // TODO: This should also contain a brute-force detection strategy. // TODO: Inject this in the constructor var context = new dev_sbpcoveragetoolContext(); // Check to see that the user exists var account = context.Accounts.Where(a => a.Username == loginRequest.Username).OrderBy(a => a.CreatedAt).FirstOrDefault(); if (account == null) { return(Unauthorized()); } var incoming = CustomLoginProviderUtils.Hash(loginRequest.Password, account.Salt); if (!CustomLoginProviderUtils.SlowEquals(incoming, account.SaltedAndHashedPassword)) { return(Unauthorized()); } var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, loginRequest.Username), new Claim(JwtRegisteredClaimNames.Exp, TimeSpan.FromDays(30).ToString()), new Claim(JwtRegisteredClaimNames.Email, account.Email), new Claim(JwtRegisteredClaimNames.GivenName, account.FirstName), new Claim(JwtRegisteredClaimNames.FamilyName, account.LastName) }; var token = AppServiceLoginHandler.CreateToken( claims, _signingKey, _audience, _issuer, TimeSpan.FromDays(30)); return(Ok(new LoginResult() { AuthenticationToken = token.RawData, User = new LoginResultUser { UserId = loginRequest.Username } })); }
public JwtSecurityToken GetTestToken(string secretKey, string audience, string issuer) { Claim[] claims = new Claim[] { new Claim("sub", "Facebook:1234"), new Claim("custom_claim_1", "CustomClaimValue1"), new Claim("custom_claim_2", "CustomClaimValue2"), new Claim("aud", audience), new Claim("iss", issuer), }; JwtSecurityToken token = AppServiceLoginHandler.CreateToken(claims, secretKey, audience, issuer, TimeSpan.FromDays(30)); Assert.Equal(8, token.Claims.Count()); return(token); }
public LoginUser GetDummyUserToken() { Claim[] claims = new Claim[] { new Claim("sub", "Facebook:[email protected]") }; string host = this.Request.RequestUri.GetLeftPart(UriPartial.Authority) + "/"; var token = AppServiceLoginHandler.CreateToken(claims, GetSigningKey(), host, host, TimeSpan.FromDays(30)); return(new LoginUser() { UserId = token.Subject, AuthenticationToken = token.RawData }); }
public async Task <IHttpActionResult> Post([FromBody] JObject assertion) { SealegsAuthResponse authResult = AuthenticateCredentials(assertion.ToObject <SealegsCredentials>()); if (!authResult.Success) { return(Unauthorized()); } IEnumerable <Claim> claims = GetAccountClaims(authResult.User); string websiteUri = $"https://{WebsiteHostName}/"; JwtSecurityToken token = AppServiceLoginHandler.CreateToken(claims, TokenSigningKey, websiteUri, websiteUri, TimeSpan.FromDays(10)); return(await Task.FromResult(Ok(new LoginResult { RawToken = token.RawData, User = authResult.User }))); }
/// <summary> /// Create a test user /// </summary> private ClaimsPrincipal CreateTestUser() { AppServiceAuthenticationOptions options = CreateTestOptions(); Claim[] claims = new Claim[] { new Claim("sub", this.facebookCredentials.UserId) }; JwtSecurityToken token = AppServiceLoginHandler.CreateToken(claims, TestSigningKey, TestLocalhostUrl, TestLocalhostUrl, TimeSpan.FromDays(10)); ClaimsPrincipal user = null; string[] validIssAud = new[] { TestLocalhostUrl }; this.tokenHandler.TryValidateLoginToken(token.RawData, options.SigningKey, validIssAud, validIssAud, out user); return(user); }
public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } // Get Signing Key and send x-zumo-auth token from claims string signingKey = GetSigningKey(); var tokenInfo = AppServiceLoginHandler.CreateToken( data.Identity.Claims, signingKey, GetHost(), GetHost(), TimeSpan.FromHours(24)); return(tokenInfo.RawData); }
public IHttpActionResult Post([FromBody] Auth0User body) { if (body == null || body.access_token == null || body.access_token.Length == 0) { return(BadRequest()); } try { var token = (JwtSecurityToken)tokenHandler.ReadToken(body.access_token); if (!IsValidUser(token)) { return(Unauthorized()); } var subject = token.Claims.FirstOrDefault(c => c.Type.Equals("sub"))?.Value; var email = token.Claims.FirstOrDefault(c => c.Type.Equals("email"))?.Value; if (subject == null || email == null) { return(BadRequest()); } var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, subject), new Claim(JwtRegisteredClaimNames.Email, email) }; JwtSecurityToken zumoToken = AppServiceLoginHandler.CreateToken( claims, signingKey, audience, issuer, TimeSpan.FromDays(30)); return(Ok(new LoginResult() { AuthenticationToken = zumoToken.RawData, User = new LoginResultUser { UserId = email } })); } catch (Exception ex) { Debug.WriteLine($"Auth0 JWT Exception = {ex.Message}"); throw ex; } }