public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } string audienceId = data.Properties.Dictionary.ContainsKey(AudiencePropertyKey) ? data.Properties.Dictionary[AudiencePropertyKey] : null; if (string.IsNullOrWhiteSpace(audienceId)) { throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience"); } Audience audience = AudiencesStore.FindAudience(audienceId); string symmetricKeyAsBase64 = audience.Base64Secret; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); var signingKey = new HmacSigningCredentials(keyByteArray); var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc; var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey); var handler = new JwtSecurityTokenHandler(); var jwt = handler.WriteToken(token); return(jwt); }
/// <summary> /// Validates Client /// </summary> /// <param name="context">Client Authenticatiocn Context</param> /// <returns></returns> public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId = string.Empty; string clientSecret = string.Empty; string symmetricKeyAsBase64 = string.Empty; if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { context.TryGetFormCredentials(out clientId, out clientSecret); } if (context.ClientId == null) { context.SetError("invalid_clientId", "client_Id is not set"); return(Task.FromResult <object>(null)); } var audience = AudiencesStore.FindAudience(context.ClientId); if (audience == null) { context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId)); return(Task.FromResult <object>(null)); } context.Validated(); return(Task.FromResult <object>(null)); }
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId = string.Empty; string clientSecret = string.Empty; if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { context.TryGetFormCredentials(out clientId, out clientSecret); } if (context.ClientId == null) { context.SetError(Constants.Constants.InvalidClientId, Constants.Constants.ClientIdIsNotSet); } var audience = AudiencesStore.FindAudience(context.ClientId); if (audience == null) { context.SetError(Constants.Constants.InvalidClientId, $"{Constants.Constants.InvalidClientId} '{context.ClientId}'"); return(Task.FromResult <object>(null)); } context.Validated(); return(Task.FromResult <object>(null)); }
public IHttpActionResult refreshToken() { var authHeader = Request.Headers.FirstOrDefault(h => h.Key.Equals("Authorization")); var bearJwtToken = authHeader.Value.FirstOrDefault(); if (string.IsNullOrEmpty(bearJwtToken)) { return(BadRequest("Authorization required")); } var arr = bearJwtToken.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (arr.Length < 2) { return(BadRequest("Invalid Token")); } var jwtTokenStr = arr[1]; var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.ReadToken(jwtTokenStr) as JwtSecurityToken; var appConfig = new AppConfig(); var audienceId = appConfig["clientId"]; var issuer = appConfig["issuer"]; var configExpire = appConfig["expireMinutes"]; var claims = jwtToken.Claims; var notBefore = DateTime.Now; double expireMinutes = 0; if (!double.TryParse(configExpire, out expireMinutes)) { expireMinutes = 30; } var expires = notBefore.AddMinutes(expireMinutes); Audience audience = AudiencesStore.FindAudience(audienceId); string symmetricKeyAsBase64 = audience.Base64Secret; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); var signingKey = new HmacSigningCredentials(keyByteArray); var newToken = new JwtSecurityToken(issuer, audienceId, claims, notBefore, expires, signingKey); var jwt = tokenHandler.WriteToken(newToken); return(Ok(jwt)); }
public void ConfigureOAuth(IAppBuilder app) { var audience = "199153c2315149bc9ecb3e85e03f1144"; Audience oAudience = AudiencesStore.FindAudience(audience); var issuer = "http://Chr.WebApi.Core"; var secret = TextEncodings.Base64Url.Decode(oAudience.Base64Secret); app.CreatePerOwinContext(() => new CSSUsersEntities()); //Server generacion del token OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/oauth2/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60), Provider = new CustomOAuthProvider(), AccessTokenFormat = new CustomJwtFormat(issuer) }; //Validacion del token por Controllador app.UseJwtBearerAuthentication( new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, AllowedAudiences = new[] { audience }, IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] { new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret) }, Provider = new OAuthBearerAuthenticationProvider { OnValidateIdentity = context => { //context.Ticket.Identity.AddClaim(new System.Security.Claims.Claim("newCustomClaim", "newValue")); return(Task.FromResult <object>(null)); } } }); // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); }
public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } string audienceId = data.Properties.Dictionary.ContainsKey(AudiencePropertyKey) ? data.Properties.Dictionary[AudiencePropertyKey] : null; if (string.IsNullOrWhiteSpace(audienceId)) { throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience"); } Audience audience = AudiencesStore.FindAudience(audienceId); string symmetricKeyAsBase64 = audience.Base64Secret; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); var signingKey = new SymmetricSecurityKey(keyByteArray); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc; //Optional: Map Identity Claims names to JWT names (using jwtClaims instead of 'data.Identity.Claims' in JwtSecurityToken constructor) var jwtClaims = new List <Claim>(); jwtClaims.Add(new Claim("sub", data.Identity.Name)); jwtClaims.AddRange(data.Identity.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => new Claim("roles", c.Value))); var token = new JwtSecurityToken(_issuer, audienceId, jwtClaims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials); var handler = new JwtSecurityTokenHandler(); var jwt = handler.WriteToken(token); return(jwt); }
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId = string.Empty; string clientSecret = string.Empty; string symmetricKeyAsBase64 = string.Empty; if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { context.TryGetFormCredentials(out clientId, out clientSecret); } if (context.ClientId == null) { context.SetError("invalid_clientId", "client_Id is not set"); return(Task.FromResult <object>(null)); } // TODO: crete AudiencesStore to database and mix with client entity and validation with AngularJSAuthentication.SimpleAuthorizationServerProvider var audience = AudiencesStore.FindAudience(context.ClientId); if (audience == null) { context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId)); return(Task.FromResult <object>(null)); } //using (AuthRepository _repo = new AuthRepository()) //{ // client = _repo.FindClient(context.ClientId); //} //if (client == null) //{ // context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId)); // return Task.FromResult<object>(null); //} //if (client.ApplicationType == Models.ApplicationTypes.NativeConfidential) //{ // if (string.IsNullOrWhiteSpace(clientSecret)) // { // context.SetError("invalid_clientId", "Client secret should be sent."); // return Task.FromResult<object>(null); // } // else // { // if (client.Secret != Helper.GetHash(clientSecret)) // { // context.SetError("invalid_clientId", "Client secret is invalid."); // return Task.FromResult<object>(null); // } // } //} //if (!client.Active) //{ // context.SetError("invalid_clientId", "Client is inactive."); // return Task.FromResult<object>(null); //} //context.OwinContext.Set<string>("as:clientAllowedOrigin", client.AllowedOrigin); //context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString()); context.Validated(); return(Task.FromResult <object>(null)); }
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { //without refresh tokens string clientId = string.Empty; string clientSecret = string.Empty; string symmetricKeyAsBase64 = string.Empty; if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { context.TryGetFormCredentials(out clientId, out clientSecret); } if (context.ClientId == null) { context.SetError("invalid_clientId", "client_Id is not set"); return(Task.FromResult <object>(null)); } var audience = AudiencesStore.FindAudience(context.ClientId); if (audience == null) { context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId)); return(Task.FromResult <object>(null)); } context.Validated(); return(Task.FromResult <object>(null)); //string clientId = string.Empty; //string clientSecret = string.Empty; //Client client = null; //if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) //{ // context.TryGetFormCredentials(out clientId, out clientSecret); //} //if (context.ClientId == null) //{ // //Remove the comments from the below line context.SetError, and invalidate context // //if you want to force sending clientId/secrects once obtain access tokens. // //context.Validated(); // context.SetError("invalid_clientId", "ClientId should be sent."); // return Task.FromResult<object>(null); //} //using (AuthRepository _repo = new AuthRepository()) //{ // client = _repo.FindClient(context.ClientId); //} //if (client == null) //{ // context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId)); // return Task.FromResult<object>(null); //} /* * set App Type * tharvanits 31/5/2016 * Set AppType For Admin Panel */ //AppType = client.ApplicationType; //if (client.ApplicationType == Models.ApplicationTypes.NativeConfidential) //{ // if (string.IsNullOrWhiteSpace(clientSecret)) // { // context.SetError("invalid_clientId", "Client secret should be sent."); // return Task.FromResult<object>(null); // } // else // { // if (client.Secret != clientSecret)//Helper.GetHash(clientSecret)) // { // context.SetError("invalid_clientId", "Client secret is invalid."); // return Task.FromResult<object>(null); // } // } //} //if (!client.Active) //{ // context.SetError("invalid_clientId", "Client is inactive."); // return Task.FromResult<object>(null); //} //var audience = AudiencesStore.FindAudience(context.ClientId); //if (audience == null) //{ // context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId)); // return Task.FromResult<object>(null); //} //context.Validated(); //return Task.FromResult<object>(null); }