private void CreateAuthenticationCode(AuthenticationTokenCreateContext context) { context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n")); _authenticationCodes[context.Token] = context.SerializeTicket(); }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddHours(_hours); context.SetToken(context.SerializeTicket()); }
public static void CreateRefreshToken(AuthenticationTokenCreateContext context) { context.SetToken(context.SerializeTicket()); }
public override void Create(AuthenticationTokenCreateContext context) { context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.UtcNow.AddYears(1)); context.SetToken(context.SerializeTicket()); }
private async Task InvokeTokenEndpointAsync() { DateTimeOffset currentUtc = Options.SystemClock.UtcNow; // remove milliseconds in case they don't round-trip currentUtc = currentUtc.Subtract(TimeSpan.FromMilliseconds(currentUtc.Millisecond)); IFormCollection form = await Request.ReadFormAsync(); var clientContext = new OAuthValidateClientAuthenticationContext( Context, Options, form); await Options.Provider.ValidateClientAuthentication(clientContext); if (!clientContext.IsValidated) { _logger.WriteError("clientID is not valid."); if (!clientContext.HasError) { clientContext.SetError(Constants.Errors.InvalidClient); } await SendErrorAsJsonAsync(clientContext); return; } var tokenEndpointRequest = new TokenEndpointRequest(form); var validatingContext = new OAuthValidateTokenRequestContext(Context, Options, tokenEndpointRequest, clientContext); AuthenticationTicket ticket = null; if (tokenEndpointRequest.IsAuthorizationCodeGrantType) { // Authorization Code Grant http://tools.ietf.org/html/rfc6749#section-4.1 // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.1.3 ticket = await InvokeTokenEndpointAuthorizationCodeGrantAsync(validatingContext, currentUtc); } else if (tokenEndpointRequest.IsResourceOwnerPasswordCredentialsGrantType) { // Resource Owner Password Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.3 // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.3.2 ticket = await InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync(validatingContext, currentUtc); } else if (tokenEndpointRequest.IsClientCredentialsGrantType) { // Client Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.4 // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.4.2 ticket = await InvokeTokenEndpointClientCredentialsGrantAsync(validatingContext, currentUtc); } else if (tokenEndpointRequest.IsRefreshTokenGrantType) { // Refreshing an Access Token // http://tools.ietf.org/html/rfc6749#section-6 ticket = await InvokeTokenEndpointRefreshTokenGrantAsync(validatingContext, currentUtc); } else if (tokenEndpointRequest.IsCustomExtensionGrantType) { // Defining New Authorization Grant Types // http://tools.ietf.org/html/rfc6749#section-8.3 ticket = await InvokeTokenEndpointCustomGrantAsync(validatingContext, currentUtc); } else { // Error Response http://tools.ietf.org/html/rfc6749#section-5.2 // The authorization grant type is not supported by the // authorization server. _logger.WriteError("grant type is not recognized"); validatingContext.SetError(Constants.Errors.UnsupportedGrantType); } if (ticket == null) { await SendErrorAsJsonAsync(validatingContext); return; } ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan); var tokenEndpointContext = new OAuthTokenEndpointContext( Context, Options, ticket, tokenEndpointRequest); await Options.Provider.TokenEndpoint(tokenEndpointContext); if (tokenEndpointContext.TokenIssued) { ticket = new AuthenticationTicket( tokenEndpointContext.Identity, tokenEndpointContext.Properties); } else { _logger.WriteError("Token was not issued to tokenEndpointContext"); validatingContext.SetError(Constants.Errors.InvalidGrant); await SendErrorAsJsonAsync(validatingContext); return; } var accessTokenContext = new AuthenticationTokenCreateContext( Context, Options.AccessTokenFormat, ticket); await Options.AccessTokenProvider.CreateAsync(accessTokenContext); string accessToken = accessTokenContext.Token; if (string.IsNullOrEmpty(accessToken)) { accessToken = accessTokenContext.SerializeTicket(); } DateTimeOffset?accessTokenExpiresUtc = ticket.Properties.ExpiresUtc; var refreshTokenCreateContext = new AuthenticationTokenCreateContext( Context, Options.RefreshTokenFormat, accessTokenContext.Ticket); await Options.RefreshTokenProvider.CreateAsync(refreshTokenCreateContext); string refreshToken = refreshTokenCreateContext.Token; var memory = new MemoryStream(); byte[] body; using (var writer = new JsonTextWriter(new StreamWriter(memory))) { writer.WriteStartObject(); writer.WritePropertyName(Constants.Parameters.AccessToken); writer.WriteValue(accessToken); writer.WritePropertyName(Constants.Parameters.TokenType); writer.WriteValue(Constants.TokenTypes.Bearer); if (accessTokenExpiresUtc.HasValue) { TimeSpan?expiresTimeSpan = accessTokenExpiresUtc - currentUtc; var expiresIn = (long)expiresTimeSpan.Value.TotalSeconds; if (expiresIn > 0) { writer.WritePropertyName(Constants.Parameters.ExpiresIn); writer.WriteValue(expiresIn); } } if (!String.IsNullOrEmpty(refreshToken)) { writer.WritePropertyName(Constants.Parameters.RefreshToken); writer.WriteValue(refreshToken); } foreach (var additionalResponseParameter in tokenEndpointContext.AdditionalResponseParameters) { writer.WritePropertyName(additionalResponseParameter.Key); writer.WriteValue(additionalResponseParameter.Value); } writer.WriteEndObject(); writer.Flush(); body = memory.ToArray(); } Response.ContentType = "application/json;charset=UTF-8"; Response.Headers.Set("Cache-Control", "no-cache"); Response.Headers.Set("Pragma", "no-cache"); Response.Headers.Set("Expires", "-1"); Response.ContentLength = memory.ToArray().Length; await Response.WriteAsync(body, Request.CallCancelled); }
private void CreateRefreshToken(AuthenticationTokenCreateContext obj) { obj.SetToken(obj.SerializeTicket()); }
/// <summary> /// 建立 AuthenticationTokenCreateContext /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task CreateAsync(AuthenticationTokenCreateContext context) { var clientid = context.Ticket.Properties.Dictionary["as:client_id"]; if (string.IsNullOrEmpty(clientid)) { return; } //產成的新Token的唯一標別碼,在此使用Guid(有需要再改其它演算法) var refreshTokenId = Guid.NewGuid().ToString("n"); //更新Token的生存時間值,該值將被用於確定新Token有多長的有效期 using (AuthBLL _auth = new AuthBLL()) { var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime"); //有值延長為2倍,若為null則預設60分鐘 double doubleRefreshTokenLifeTime = 60; bool isDoubleRefreshTokenLifeTime = double.TryParse(refreshTokenLifeTime, out doubleRefreshTokenLifeTime); if (!isDoubleRefreshTokenLifeTime) { doubleRefreshTokenLifeTime = 60; } else { doubleRefreshTokenLifeTime = doubleRefreshTokenLifeTime * 2; } var token = new RefreshToken() { Id = Helper.GetHash(refreshTokenId), ClientId = clientid, Subject = context.Ticket.Identity.Name, IssuedUtc = DateTime.UtcNow, //有效期限(分鐘,有需要再改) ExpiresUtc = DateTime.UtcNow.AddMinutes(doubleRefreshTokenLifeTime) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; //在資料庫中以序列化形式儲存 token.ProtectedTicket = context.SerializeTicket(); //儲存到RefreshTokens資料表中 var result = await _auth.AddRefreshToken(token); if (result) { //建立暫存refreshToken用 var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary) { IssuedUtc = context.Ticket.Properties.IssuedUtc, ExpiresUtc = DateTime.UtcNow.AddMinutes(doubleRefreshTokenLifeTime) }; var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties); _refreshTokens.TryAdd(refreshTokenId, refreshTokenTicket); //回傳新的Token context.SetToken(refreshTokenId); } } }
public override async Task CreateAsync(AuthenticationTokenCreateContext context) { if (context.OwinContext == null) { return; } var properties = context.Ticket?.Properties; if (properties == null) { return; } var identity = context.Ticket.Identity; if (identity == null) { return; } if (!Guid.TryParse(identity.FindFirst(IntersectClaimTypes.ClientId)?.Value, out var clientId)) { Log.Diagnostic( "Received invalid client id '{0}'.", identity.FindFirst(IntersectClaimTypes.UserId)?.Value ); } var identifier = identity.FindFirst(IntersectClaimTypes.UserId)?.Value; if (!Guid.TryParse(identifier, out var userId)) { return; } var userName = identity.FindFirst(IntersectClaimTypes.UserName)?.Value; var issued = DateTime.UtcNow; var expires = issued.AddMinutes(Configuration.RefreshTokenLifetime); var ticketId = context.OwinContext.Get <Guid>("ticket_id"); if (ticketId == Guid.Empty) { identity.FindAll(IntersectClaimTypes.TicketId) ?.ToList() .ForEach( claim => { if (!Guid.TryParse(claim?.Value, out var guid) || guid == Guid.Empty) { identity.TryRemoveClaim(claim); } } ); var ticketIdClaim = identity.FindFirst(IntersectClaimTypes.TicketId); if (ticketIdClaim == null || !Guid.TryParse(ticketIdClaim.Value, out ticketId)) { ticketId = Guid.NewGuid(); identity.AddClaim(new Claim(IntersectClaimTypes.TicketId, ticketId.ToString())); } } var token = new RefreshToken { UserId = userId, ClientId = clientId, Subject = userName, Issued = issued, Expires = expires, TicketId = ticketId }; properties.IssuedUtc = issued; properties.ExpiresUtc = expires; token.Ticket = context.SerializeTicket(); if (await RefreshToken.Add(token, true)) { context.SetToken(token.Id.ToString()); } }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { var clientid = context.Ticket.Properties.Dictionary["as:client_id"]; if (string.IsNullOrEmpty(clientid)) { return; } //string hashedTokenId = Helper.GetHash(context.Token); // var refreshToken = await _repo.FindRefreshToken(hashedTokenId); var refreshTokenId = Guid.NewGuid().ToString("n"); using (AuthRepository _repo = new AuthRepository()) { var rfToken = await _repo.FindRefreshTokenByName(context.Ticket.Identity.Name); if (rfToken == null || string.IsNullOrEmpty(rfToken.Token)) { var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime"); var token = new RefreshToken() { Id = Helper.GetHash(refreshTokenId), ClientId = clientid, Subject = context.Ticket.Identity.Name, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)), Token = Helper.Encrypt(refreshTokenId, "punnel") }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; token.ProtectedTicket = context.SerializeTicket(); var result = await _repo.AddRefreshToken(token); if (result) { context.SetToken(refreshTokenId); } } else { refreshTokenId = Helper.Decrypt(rfToken.Token, "punnel"); var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime"); var token = new RefreshToken() { Id = rfToken.Id, ClientId = clientid, Subject = context.Ticket.Identity.Name, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; token.ProtectedTicket = context.SerializeTicket(); var result = await _repo.AddRefreshToken(token); if (result) { context.SetToken(refreshTokenId); } } } }
/// <summary> /// 生成 authorization_code /// </summary> public override void Create(AuthenticationTokenCreateContext context) { context.SetToken(Guid.NewGuid().ToString("N")); _authenticationCodes[context.Token] = context.SerializeTicket(); }
private void CreateRefreshToken(AuthenticationTokenCreateContext context) { context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddHours(ExampleCommon.Constants.REFRESH_TOKEN_EXPIRED_HOURS)); context.SetToken(context.SerializeTicket()); }
public override void Create(AuthenticationTokenCreateContext context) { // Expiration time in seconds context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(2592000)); context.SetToken(context.SerializeTicket()); }
public void Create(AuthenticationTokenCreateContext context) { context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddMinutes(int.Parse(System.Configuration.ConfigurationManager.AppSettings["OAuth_Refresh_Token_TimeSpan"])); context.SetToken(context.SerializeTicket()); }
public override System.Threading.Tasks.Task CreateAsync(AuthenticationTokenCreateContext context) { context.SetToken(context.SerializeTicket());//可以重写token算法 return(base.CreateAsync(context)); }
private static void CreateRefreshToken(AuthenticationTokenCreateContext obj) { // throw new NotImplementedException(); obj.SetToken(obj.SerializeTicket()); }
public void Create(AuthenticationTokenCreateContext context) { context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n")); _refreshTokens[context.Token] = context.SerializeTicket(); }
public override Task CreateAsync(AuthenticationTokenCreateContext context) { //生成的刷新Token可以存储到数据库 context.SetToken(context.SerializeTicket()); return(Task.FromResult(0)); }
protected override async Task ApplyResponseGrantAsync() { // only successful results of an authorize request are altered if (_clientContext == null || _authorizeEndpointRequest == null || Response.StatusCode != 200) { return; } // only apply with signin of matching authentication type AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType); if (signin == null) { return; } string location = _clientContext.RedirectUri; if (_authorizeEndpointRequest.IsAuthorizationCodeGrantType) { DateTimeOffset currentUtc = Options.SystemClock.UtcNow; signin.Properties.IssuedUtc = currentUtc; signin.Properties.ExpiresUtc = currentUtc.Add(Options.AuthorizationCodeExpireTimeSpan); // associate client_id with all subsequent tickets signin.Properties.Dictionary[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId; if (!string.IsNullOrEmpty(_authorizeEndpointRequest.RedirectUri)) { // keep original request parameter for later comparison signin.Properties.Dictionary[Constants.Extra.RedirectUri] = _authorizeEndpointRequest.RedirectUri; } var context = new AuthenticationTokenCreateContext( Context, Options.AuthorizationCodeFormat, new AuthenticationTicket(signin.Identity, signin.Properties)); await Options.AuthorizationCodeProvider.CreateAsync(context); string code = context.Token; if (string.IsNullOrEmpty(code)) { _logger.WriteError("response_type code requires an Options.AuthorizationCodeProvider implementing a single-use token."); var errorContext = new OAuthValidateAuthorizeRequestContext(Context, Options, _authorizeEndpointRequest, _clientContext); errorContext.SetError(Constants.Errors.UnsupportedResponseType); await SendErrorRedirectAsync(_clientContext, errorContext); } location = WebUtilities.AddQueryString(location, Constants.Parameters.Code, code); if (!String.IsNullOrEmpty(_authorizeEndpointRequest.State)) { location = WebUtilities.AddQueryString(location, Constants.Parameters.State, _authorizeEndpointRequest.State); } Response.Redirect(location); } else if (_authorizeEndpointRequest.IsImplicitGrantType) { DateTimeOffset currentUtc = Options.SystemClock.UtcNow; signin.Properties.IssuedUtc = currentUtc; signin.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan); // associate client_id with access token signin.Properties.Dictionary[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId; var accessTokenContext = new AuthenticationTokenCreateContext( Context, Options.AccessTokenFormat, new AuthenticationTicket(signin.Identity, signin.Properties)); await Options.AccessTokenProvider.CreateAsync(accessTokenContext); string accessToken = accessTokenContext.Token; if (string.IsNullOrEmpty(accessToken)) { accessToken = accessTokenContext.SerializeTicket(); } DateTimeOffset?accessTokenExpiresUtc = accessTokenContext.Ticket.Properties.ExpiresUtc; var appender = new Appender(location, '#'); appender .Append(Constants.Parameters.AccessToken, accessToken) .Append(Constants.Parameters.TokenType, Constants.TokenTypes.Bearer); if (accessTokenExpiresUtc.HasValue) { TimeSpan?expiresTimeSpan = accessTokenExpiresUtc - currentUtc; var expiresIn = (long)(expiresTimeSpan.Value.TotalSeconds + .5); appender.Append(Constants.Parameters.ExpiresIn, expiresIn.ToString(CultureInfo.InvariantCulture)); } if (!String.IsNullOrEmpty(_authorizeEndpointRequest.State)) { appender.Append(Constants.Parameters.State, _authorizeEndpointRequest.State); } Response.Redirect(appender.ToString()); } }
public override async System.Threading.Tasks.Task CreateAsync(AuthenticationTokenCreateContext context) { // refresh tokens don't expire context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddYears(100); context.SetToken(context.SerializeTicket()); }
public void CreateAuthenticationCode(AuthenticationTokenCreateContext context) { // 產出驗證碼 context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n")); this._authenticationCodes[context.Token] = context.SerializeTicket(); }
public override async System.Threading.Tasks.Task CreateAsync(AuthenticationTokenCreateContext context) { context.SetToken(context.SerializeTicket()); }
private void CreateAuthenticationCode(AuthenticationTokenCreateContext obj) { obj.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n")); _authenticationCodes[obj.Token] = obj.SerializeTicket(); }
public Task CreateAsync(AuthenticationTokenCreateContext context) { context.SetToken(context.SerializeTicket()); return(Task.FromResult <object>(null)); }
private void CreateAccessToken(AuthenticationTokenCreateContext context) { context.SetToken(context.SerializeTicket()); }
public override void Create(AuthenticationTokenCreateContext context) { context.SetToken(context.SerializeTicket()); }
private void CreateAuthenticationCode(AuthenticationTokenCreateContext context) { context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n")); RockCache.AddOrUpdate(context.Token, context.SerializeTicket()); }
public override async Task CreateAsync(AuthenticationTokenCreateContext context) { context.SetToken(context.SerializeTicket()); }
/// <summary>CreateAuthenticationCode</summary> /// <param name="context">AuthenticationTokenCreateContext</param> private void CreateAuthenticationCode(AuthenticationTokenCreateContext context) { context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n")); Dictionary <string, string> temp = new Dictionary <string, string>(); NameValueCollection queryString = HttpUtility.ParseQueryString(context.Request.QueryString.Value); // 標準(標準方式は、今のところ、残しておく) temp.Add("ticket", context.SerializeTicket()); // 有効期限が無効なtokenのペイロードだけ作成 AccessTokenFormatJwt accessTokenFormatJwt = new AccessTokenFormatJwt(); string access_token_payload = OidcTokenEditor.CreateAccessTokenPayloadFromAuthenticationTicket(context.Ticket); temp.Add("access_token_payload", access_token_payload); // OAuth PKCE 対応 temp.Add(OAuth2AndOIDCConst.code_challenge, queryString[OAuth2AndOIDCConst.code_challenge]); temp.Add(OAuth2AndOIDCConst.code_challenge_method, queryString[OAuth2AndOIDCConst.code_challenge_method]); // Hybrid Flow対応 // OAuthAuthorizationServerHandler経由での呼び出しができず、 // AuthenticationTokenXXXXContextを取得できないため、抜け道。 // サイズ大き過ぎるので根本の方式を修正。 //temp.Add("claims", CustomEncode.ToBase64String(BinarySerialize.ObjectToBytes(context.Ticket.Identity))); //temp.Add("properties", CustomEncode.ToBase64String(BinarySerialize.ObjectToBytes(context.Ticket.Properties.Dictionary))); string value = JsonConvert.SerializeObject(temp); switch (ASPNETIdentityConfig.UserStoreType) { case EnumUserStoreType.Memory: _authenticationCodes[context.Token] = value; break; case EnumUserStoreType.SqlServer: case EnumUserStoreType.ODPManagedDriver: case EnumUserStoreType.PostgreSQL: // DMBMS using (IDbConnection cnn = DataAccess.CreateConnection()) { cnn.Open(); switch (ASPNETIdentityConfig.UserStoreType) { case EnumUserStoreType.SqlServer: cnn.Execute( "INSERT INTO [AuthenticationCodeDictionary] ([Key], [Value], [CreatedDate]) VALUES (@Key, @Value, @CreatedDate)", new { Key = context.Token, Value = value, CreatedDate = DateTime.Now }); break; case EnumUserStoreType.ODPManagedDriver: cnn.Execute( "INSERT INTO \"AuthenticationCodeDictionary\" (\"Key\", \"Value\", \"CreatedDate\") VALUES (:Key, :Value, :CreatedDate)", new { Key = context.Token, Value = value, CreatedDate = DateTime.Now }); break; case EnumUserStoreType.PostgreSQL: cnn.Execute( "INSERT INTO \"authenticationcodedictionary\" (\"key\", \"value\", \"createddate\") VALUES (@Key, @Value, @CreatedDate)", new { Key = context.Token, Value = value, CreatedDate = DateTime.Now }); break; } } break; } }
public override void Create(AuthenticationTokenCreateContext context) { context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.UtcNow.AddHours(2 * NumericConstants.TokenExpirationTimeInHours)); context.SetToken(context.SerializeTicket()); }