private string GenerateToken(RestToken restToken) { var token = new JwtSecurityToken( claims: new Claim[] { new Claim("userId", restToken.UserId.ToString()), }, notBefore: new DateTimeOffset(DateTime.Now).DateTime, expires: new DateTimeOffset(DateTime.Now.AddMinutes(60)).DateTime, signingCredentials: new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256) ); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public static string CreateToken(RestToken restToken, int?expiringDurationInSeconds = null) { var now = DateTime.UtcNow; var jwtClaims = new List <Claim> { new(JwtRegisteredClaimNames.Iat, now.ToTimestamp().ToString()) }; var issuerKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(restToken.IssuerSigningKey)); var signingCredentials = new SigningCredentials(issuerKey, SecurityAlgorithms.HmacSha256); var expires = now.AddSeconds(expiringDurationInSeconds ?? ExpiredDurationInSeconds); var jwt = new JwtSecurityToken(restToken.Issuer, restToken.Audience, jwtClaims, now, expires, signingCredentials); return(new JwtSecurityTokenHandler().WriteToken(jwt)); }
private RestToken CreateRestToken(LoginResult loginResult) { var identity = GetIdentity(loginResult); var now = DateTime.Now; var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new RestToken { AccessToken = encodedJwt, ExpiresIn = 10000 }; return(response); }
private bool TryLexRest(string part, int lineIndex, ref int charIndex) { var match = RestRegex.Match(part); if (!match.Success) { return(false); } var groups = match.Groups; var numeratorGroup = groups[2]; var denominatorGroup = groups[4]; var numerator = (numeratorGroup.Success) ? int.Parse(numeratorGroup.Value) : 1; var denominator = (denominatorGroup.Success) ? int.Parse(denominatorGroup.Value) : 1; if (groups[1].Value == "X" || groups[1].Value == "Z") { numerator = numerator * TimeSignature.Meter.Denominator; denominator = denominator * TimeSignature.Meter.Numerator; } var token = new RestToken() { Char = charIndex, Length = new Fraction(numerator, denominator), Line = lineIndex, Text = match.Value, Symbol = match.Value }; Tokens.Add(token); if (HasPendingDots) { token.Dotify(PendingDots, "right"); PendingDots = null; } charIndex += token.Text.Length; return(true); }
public RestToken MakeRequest2(string requestUrl) { try { HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RestToken)); RestToken jsonResponse = jsonSerializer.ReadObject(response.GetResponseStream()) as RestToken; //Stream dataStream = response.GetResponseStream(); //StreamReader reader = new StreamReader(dataStream); //string responseFromServer = reader.ReadToEnd(); ////Console.WriteLine(responseFromServer); //reader.Close(); //response.Close(); return(jsonResponse); } } catch (Exception e) { Console.WriteLine(e.Message); //throw new Exception(e.StackTrace); //Response.Redirect("~/Default.aspx?error=" + e.Message); return(null); } }
protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { var uri = navigationManager.ToAbsoluteUri(navigationManager.Uri); var uri_query = uri.Query; //?access_token = RTfP0OK99U3kbRtHOjjLmjbOn45PjL & token_type = Bearer & expires_in = 604800 & scope = identify & state = 15773059ghq9183habn if (QueryHelpers.ParseQuery(uri.Fragment.TrimStart('#')).TryGetValue("access_token", out var token)) { await DiscordRestClient.LoginAsync(TokenType.Bearer, token); //this can give you an exception if the token is expired! User = DiscordRestClient.CurrentUser; StateHasChanged(); } if (QueryHelpers.ParseQuery(uri.Query.TrimStart('?')).TryGetValue("code", out var code)) { RestToken = await DiscordRestClient.GetTokenAsync(TokenType.Code, code, navigationManager.BaseUri, new List <string> { "identify" }); //this can give you an exception if the token is expired! await DiscordRestClient.LoginAsync(TokenType.Bearer, RestToken.Token); User = DiscordRestClient.CurrentUser; StateHasChanged(); } if (QueryHelpers.ParseQuery(uri.Query.TrimStart('?')).TryGetValue("refresh_token", out var refreshToken)) { RestToken = await DiscordRestClient.GetTokenAsync(TokenType.Refresh, refreshToken, navigationManager.BaseUri, new List <string> { "identify" }); //this can give you an exception if the token is expired! await DiscordRestClient.LoginAsync(TokenType.Bearer, RestToken.Token); User = DiscordRestClient.CurrentUser; StateHasChanged(); } } }
protected void Login1_LoggedIn(object sender, EventArgs e) { AgolToken ar = null; RestToken rt = null; Session["username"] = Login1.UserName; String[] roles = Roles.GetRolesForUser(Login1.UserName); MembershipUser mu = Membership.GetUser(Login1.UserName); if (roles.Length > 0) { //shufan added codes 08082014====== try { string strSQLConn = System.Configuration.ConfigurationManager.AppSettings["SQLConString"].Trim(); //insert log information string[] strParas = new string[2]; strParas[0] = Login1.UserName; strParas[1] = DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss"); clsStoreProcedureAccess clsInsertLog = new clsStoreProcedureAccess("InsertLogRec", strSQLConn); clsInsertLog.fnExecuteSP(strParas); } catch (Exception ex) { throw ex; }//Shufan added codes end if (Roles.GetRolesForUser(mu.UserName).Contains("pending") == false) { string url = "https://www.arcgis.com/sharing/oauth2/token?" + "client_id=" + ConfigurationManager.AppSettings["client_id"] + "&client_secret=" + ConfigurationManager.AppSettings["client_secret"] + "&grant_type=client_credentials"; ar = MakeRequest(url); if (ar != null) { Session["agol_token"] = ar.access_token; } //url = "https://www.arcgis.com/sharing/generateToken?f=json&" + // "&token=" + ar.access_token + // "&serverUrl=http://analysis.arcgis.com"; url = "https://www.arcgis.com/sharing/generateToken?f=json&" + "&username="******"agol_user"] + "&password="******"agol_password"] + "&referer=https://www.scarchsite.org"; rt = MakeRequest2(url); if (rt != null) { Session["agol_analysis_token"] = rt.token; } Session["rolename"] = roles[0]; Session["DISPLAYNAME"] = ""; Session["AFFILIATION"] = ""; SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "[dbo].[aspnet_GetUserInfo]"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn; cmd.Parameters.Add("@username", SqlDbType.NVarChar, 256).Value = Login1.UserName; SqlCommand iCmd = new SqlCommand(); iCmd.CommandText = "[dbo].[aspnet_InsertUserToken]"; iCmd.CommandType = CommandType.StoredProcedure; iCmd.Connection = conn; iCmd.Parameters.Add("@username", SqlDbType.NVarChar, 256).Value = Login1.UserName; iCmd.Parameters.Add("@token", SqlDbType.NVarChar, 256).Value = ar.access_token; System.TimeSpan duration = new System.TimeSpan(0, 0, 0, ar.expires_in); iCmd.Parameters.Add("@expired", SqlDbType.DateTime).Value = DateTime.Now.Add(duration); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { String name = ""; if (!(reader["FIRSTNAME"] is System.DBNull)) { name += reader["FIRSTNAME"].ToString(); } if (!(reader["LASTNAME"] is System.DBNull)) { name += " " + reader["LASTNAME"].ToString(); } Session["DISPLAYNAME"] = name; String affil = ""; if (!(reader["AFFILIATION"] is System.DBNull)) { affil = reader["AFFILIATION"].ToString(); } Session["AFFILIATION"] = affil; } } //Insert the token iCmd.ExecuteNonQuery(); conn.Close(); } } if (mu.Comment == "cp") { Response.Redirect("ChangePassword.aspx"); } else if (Roles.GetRolesForUser(mu.UserName)[0].Equals("admin")) { Response.Redirect("~/ManagementTool.aspx"); } else if (Roles.GetRolesForUser(mu.UserName).Contains("pending") == false) { Response.Redirect("~/Map/Map.aspx"); } else { Response.Redirect("~/PublicView.aspx"); } }