/// <summary> /// Creates an instance of authorization server options with default values. /// </summary> public OAuthAuthorizationServerOptions() : base(OAuthDefaults.AuthenticationType) { AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(5); AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20); SystemClock = new SystemClock(); }
public IHttpActionResult Token(LoginViewModel login) { Log.DebugFormat("Entering Token(): User={0}", login.UserName); if (!ModelState.IsValid) { Log.Debug("Leaving Token(): Bad request"); return this.BadRequestError(ModelState); } ClaimsIdentity identity; if (!_loginProvider.ValidateCredentials(login.UserName, login.Password, out identity)) { Log.Debug("Leaving Token(): Incorrect user or password"); return BadRequest("Incorrect user or password"); } var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30)); Log.Debug("Leaving Token()"); return Ok(new LoginAccessViewModel { UserName = login.UserName, AccessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket) }); }
public IHttpActionResult GetProfile() { ClaimsIdentity identity = (ClaimsIdentity)User.Identity; if (!loginProvider.RevalidateUser(identity.Name)) return BadRequest("Expired or invalidated user authentication token."); if (Boolean.Parse(identity.FindFirst(ClaimTypes.IsPersistent).Value)) { var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(2)); dynamic userData = JsonConvert.DeserializeObject(identity.FindFirst(ClaimTypes.UserData).Value); return Ok(new { Username = identity.Name, DisplayName = userData.DisplayName, FirstName = userData.FirstName, LastName = userData.LastName, UserID = userData.UserID, Role = identity.FindFirst(ClaimTypes.Role).Value, AccessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket) }); } return Ok(new { Username = identity.Name, DisplayName = identity.FindFirst(ClaimTypes.Name).Value, UserID = identity.FindFirst(ClaimTypes.UserData).Value, Role = identity.FindFirst(ClaimTypes.Role).Value }); }
public async Task <string> ImpersonateUserAsync(string userName, OAuthAuthorizationServerOptions serverAuthOptions, ClaimsPrincipal principal) { var originalUsername = principal.Claims.Any(c => c.Type == DataLayerConstants.ClaimUserImpersonation && c.Value == true.ToString()) ? principal.Claims.First(c => c.Type == DataLayerConstants.ClaimOriginalUsername).Value : principal.Identity.Name; var impersonatedUser = await _userManager.FindByNameAsync(userName); var impersonatedIdentity = await _userManager.CreateIdentityAsync(impersonatedUser, OAuthDefaults.AuthenticationType); if (impersonatedUser.UserName != originalUsername) { if (impersonatedIdentity.Claims.Any(c => c.Type == DataLayerConstants.ClaimUserImpersonation && c.Value == true.ToString())) { var primarySidClaim = impersonatedIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.PrimarySid); impersonatedIdentity.RemoveClaim(primarySidClaim); impersonatedIdentity.AddClaim(new Claim(ClaimTypes.PrimarySid, string.Empty)); } else { impersonatedIdentity.AddClaim(new Claim(DataLayerConstants.ClaimUserImpersonation, true.ToString())); impersonatedIdentity.AddClaim(new Claim(DataLayerConstants.ClaimOriginalUsername, originalUsername)); impersonatedIdentity.AddClaim(new Claim(ClaimTypes.PrimarySid, string.Empty)); } } var ticket = new AuthenticationTicket(impersonatedIdentity, new AuthenticationProperties()); var currentUtc = new OwinDate.SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(serverAuthOptions.AccessTokenExpireTimeSpan); return(serverAuthOptions.AccessTokenFormat.Protect(ticket)); }
public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context) { var identity = new ClaimsIdentity(AuthenticationType.Anonymous); var systemUtc = new SystemClock().UtcNow; var ticket = new AuthenticationTicket(identity, new AuthenticationProperties { IssuedUtc = systemUtc, ExpiresUtc = systemUtc.AddMinutes(20) }); context.Validated(ticket); return base.GrantClientCredentials(context); }
public FormsAuthenticationOptions() : base(FormsAuthenticationDefaults.AuthenticationType) { CookieName = FormsAuthenticationDefaults.CookiePrefix + FormsAuthenticationDefaults.AuthenticationType; CookiePath = "/"; ExpireTimeSpan = TimeSpan.FromDays(14); SlidingExpiration = true; CookieHttpOnly = true; CookieSecure = CookieSecureOption.SameAsRequest; SystemClock = new SystemClock(); }
/// <summary> /// Create an instance of the options initialized with the default values /// </summary> public CookieAuthenticationOptions() : base(CookieAuthenticationDefaults.AuthenticationType) { ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter; CookiePath = "/"; ExpireTimeSpan = TimeSpan.FromDays(14); SlidingExpiration = true; CookieHttpOnly = true; CookieSecure = CookieSecureOption.SameAsRequest; SystemClock = new SystemClock(); Provider = new CookieAuthenticationProvider(); }
public async Task<AjaxResponse> Authenticate(LoginModel loginModel) { CheckModelState(); var loginResult = await GetLoginResultAsync(loginModel.UsernameOrEmailAddress, loginModel.Password, loginModel.TenancyName); var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30)); return new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket)); }
public virtual async Task<AjaxResponse> Authenticate(AuthenticationModel loginModel) { CheckModelState(); var user = await _userManager.GetByClientIdAsnyc(loginModel.ClientId, loginModel.ClientSecret); var ident1= await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalBearer); var ticket = new AuthenticationTicket(ident1, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30)); return new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket)); }
public async Task <string> RevertImpersonationAsync(string originalUserName, OAuthAuthorizationServerOptions serverAuthOptions) { var originalUser = await _userManager.FindByNameAsync(originalUserName); var impersonatedIdentity = await _userManager.CreateIdentityAsync(originalUser, OAuthDefaults.AuthenticationType); impersonatedIdentity.AddClaim(new Claim(ClaimTypes.PrimarySid, string.Empty)); var ticket = new AuthenticationTicket(impersonatedIdentity, new AuthenticationProperties()); var currentUtc = new OwinDate.SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(serverAuthOptions.AccessTokenExpireTimeSpan); return(serverAuthOptions.AccessTokenFormat.Protect(ticket)); }
public String Authenticate(string user, string password) { if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(password)) return "failed"; var userIdentity = UserManager.FindAsync(user, password).Result; if (userIdentity != null) { var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id)); AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30)); string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket); return AccessToken; } return "failed"; }
public ApiResponse<IdentityToken> UserToken(Admin admin) { var user = Context.Admins.FirstOrDefault(x => x.LoginName == admin.LoginName && x.Password == admin.Password && x.IsActive); if (user == null) { throw new UnauthorizedAccessException(""); } ClaimsIdentity oAuthIdentity = new ApplicationIdentityUser().GenerateUserIdentity(user, "Jwt"); var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.AddDays(1); var token = AuthConfig.OAuthServerOptions.AccessTokenFormat.Protect(ticket); return new ApiResponse<IdentityToken>(new IdentityToken() { AccessToken = token, ExpiresIn = (long)AuthConfig.OAuthServerOptions.AuthorizationCodeExpireTimeSpan.TotalSeconds, TokenType = AuthConfig.OAuthServerOptions.AuthenticationType}); }
public async Task<AjaxResponse> Authenticate(string username, string password) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { return new AjaxResponse(new ErrorInfo("username and password can not be empty")); } var userIdentity = await _userManager.FindAsync(username, password); if (userIdentity == null) { return new AjaxResponse(new ErrorInfo("Invalid user name or password.")); } var identity = await _userManager.CreateIdentityAsync(userIdentity, OAuthBearerOptions.AuthenticationType); var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30)); return new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket)); }
public async Task<ActionResult> Token() { // ApplicationUser var applicationUser = await this.UserManager.FindByIdAsync(User.Identity.GetUserId()); if (applicationUser == null) throw new InvalidOperationException(); // ClaimsIdentity var claimsIdentity = await applicationUser.GenerateUserIdentityAsync(this.UserManager, OAuthDefaults.AuthenticationType); if (claimsIdentity == null) throw new InvalidOperationException(); // Ticket var currentUtcNow = new SystemClock().UtcNow; AuthenticationTicket ticket = new AuthenticationTicket(claimsIdentity, new AuthenticationProperties()); ticket.Properties.IssuedUtc = currentUtcNow; ticket.Properties.ExpiresUtc = currentUtcNow.Add(TimeSpan.FromMinutes(30)); // AccessToken string accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket); if (string.IsNullOrEmpty(accessToken) == true) throw new InvalidOperationException(); // Return return View(new TokenViewModel { AccessToken = accessToken }); }
public async Task<IHttpActionResult> Login(LoginBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } ApplicationUser user = await UserManager.FindAsync(model.Username, model.Password); if (user != null) { var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365)); return Ok(new BearerTokenModel { Token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket), Username = model.Username }); } return BadRequest("User with specified credentials doesn't exist."); }
/// <summary> /// Creates an instance of bearer authentication options with default values. /// </summary> public OAuthBearerAuthenticationOptions() : base(OAuthDefaults.AuthenticationType) { SystemClock = new SystemClock(); }
/// <summary> /// POST to STS to get a Bearer Token /// </summary> /// <returns>An OAuth2 Bearer Token</returns> public async Task<HttpResponseMessage> Post() { try { var requestContext = this.Request.Properties[STSConstants.STSRequestContext] as ITokenServiceRequestContext; if (requestContext == null) { throw new HttpResponseException(ServiceResponseMessage.BadRequest("STS Context is null")); } // Create Identity and Set Claims var authType = OwinStartUp.OAuthBearerOptions.AuthenticationType; var identity = new ClaimsIdentity(authType); /// LEFTOFF - make this code cleaner, create type by version (type converter). Also take authprovider, /// start building simple factory and inject providers if (requestContext.Version == 1.0) { // push auth rules to plug ins and take a provider/default provider and pass provider in request var body = requestContext.TokenRequestBody as TokenRequestV1; // TODO: validate the parts identity.AddClaim(new Claim(ClaimTypes.Name, body.UserName)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())); identity.AddClaim(new Claim(ClaimTypes.Email, body.Email)); identity.AddClaim(new Claim(ClaimTypes.MobilePhone, body.MobilePhone)); identity.AddClaim(new Claim(ClaimTypes.Authentication, "Partial")); } var properties = new AuthenticationProperties { IsPersistent = false }; var ticket = new AuthenticationTicket(identity, properties); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; // Set expiration ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30)); // TODO: ticket needs to be signed with a certificate. Create new signing cert and use that same cert of other services. return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(OwinStartUp.OAuthBearerOptions.AccessTokenFormat.Protect(ticket)) }; } catch (Exception ex) { // Test all of these exceptions return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ex.Message) }; } finally { // Log event } }
public IHttpActionResult PostLogin(LoginViewModel login) { if (!ModelState.IsValid) { return BadRequest(ModelState); } ClaimsIdentity identity; if (!loginProvider.ValidateCredentials(login.Username, login.Password, out identity)) { return BadRequest("Incorrect user or password."); } identity.AddClaim(new Claim(ClaimTypes.IsPersistent, login.RememberMe.ToString())); var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; if (login.RememberMe) ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(2)); else ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30)); dynamic userData = JsonConvert.DeserializeObject(identity.FindFirst(ClaimTypes.UserData).Value); return Ok(new { Username = login.Username, DisplayName = userData.DisplayName, FirstName = userData.FirstName, LastName = userData.LastName, UserID = userData.UserID, Role = identity.FindFirst(ClaimTypes.Role).Value, AccessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket) }); }
public HttpResponseMessage Token(LoginBindingModel login) { using (new TraceLogicalScope(_traceSource, "UserController:Token")) { Guard.Against<ArgumentException>(login == null, "login cannot be empty be null"); var et = new EventTelemetry("API:Users/Login"); et.Properties.Add("username", login.UserName); _telemetry.TrackEvent(et); var user = _userService.FindUser(login.UserName, login.Password); if (user != null && user.IsActive()) { //_userService.HideSensitiveData(user); var identity = _userService.CreateIdentity(user, Startup.OAuthBearerOptions.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, login.UserName)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(1440)); _traceSource.Warn("login success"); return new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent<object>(new { UserName = identity.GetUserName(), AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket), Issued = DateTime.UtcNow, Expires = ticket.Properties.ExpiresUtc }, Configuration.Formatters.JsonFormatter) }; } _traceSource.Warn("login failed"); return new HttpResponseMessage(HttpStatusCode.Unauthorized); } }
public static string Token(string userName, int userId, int providerId) { var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie); identity.AddClaim(new Claim(ClaimTypes.Name, userName)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId.ToString())); identity.AddClaim(new Claim("provider", providerId.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, "LoggedIn")); //Maybe use something like this //identity.AddClaim(new Claim(ClaimTypes.Role, userTypeId.ToString() == "0" ? "NonAdmin" : "Admin")); var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; // Set hard expiration to 24 hours, stored in web.config as 23:59:59 to make the time format easily understandable // by people who read the config. See #2909 https://www.assembla.com/spaces/snap-md/tickets/2909 ticket.Properties.ExpiresUtc = currentUtc.Add(Settings.Default.TokenHardExpiration); var token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket); return token; }