如何在web api中获取经过身份验证的用户名(基于令牌的身份验证)

时间:2017-01-16 06:17:27

标签: angularjs authentication asp.net-web-api asp.net-web-api2 token

我已经实现了基于令牌的web api身份验证。

现在,在web api方面,我需要获取经过身份验证的用户名,但无法获取。

当我尝试使用using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.Office.Interop.Excel; using System.Windows.Forms; using System.Runtime.InteropServices; namespace CNTExcelUpdate_Invisible { class Program { static string path = System.Reflection.Assembly.GetEntryAssembly().Location; static void Main(string[] args) { path = Path.GetDirectoryName(path); updateDirectory(path); Environment.Exit(0); } public static void updateDirectory(string path) { int amount = 0; string[] files; files = Directory.GetFiles(path, "*.xlsx", SearchOption.AllDirectories); amount += files.Count(); int counter = 0; try { foreach (var file in Directory.EnumerateFiles(path, "*.xlsx", SearchOption.AllDirectories)) { string fileName = Path.GetFileName(file); if (fileName.Substring(0, 2).Equals("GK")) { Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(file, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); excelApp.DisplayAlerts = false; excelWorkbook.RefreshAll(); System.Threading.Thread.Sleep(1000); excelApp.Quit(); excelApp = null; excelWorkbook.SaveAs(file, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing); //excelWorkbook.Close(); Marshal.ReleaseComObject(excelWorkbook); excelWorkbook = null; } counter++; Console.Write(counter.ToString() + "/" + amount.ToString() + " Dateien verarbeitet"); Console.SetCursorPosition(0,0); } } catch (Exception e) { MessageBox.Show("Fehler bei der Verbindung: \r\n" + e.ToString()); } } } } 进行访问时,它会显示RequestContext.Principal.Identity.Name值。

在最坏的情况下,我需要在每次请求时从angualrjs传递用户名。如果从web api本身检索它将是最好的。

任何人都可以帮忙,我如何从网络API端获取经过身份验证的用户。

感谢

1 个答案:

答案 0 :(得分:0)

您需要设置要声明的用户名。

 var claim = ((ClaimsIdentity)identity).FindFirst("sub");
    string username = claim.Value