我用 Cordova 创建了一个移动应用程序,有 2 种登录方法 Facebook 和 Google。我验证 token (FB 或 Google)后,我想使用其中之一来保护我的 Web API 2 并与我的应用程序通信,但我不知道将它存储在 Web API 中的什么位置,我将它保存到 Thread .CurrentPrincipal 但稍后返回 null。
这是我的代码:
public bool UserExist(Credentials credentials,ISQLDB socialDB,IEncrypt encrypt)
{
bool exist = false;
//IPrincipal principal;
if (credentials.fb_access_Token != "")
exist =CheckFB(credentials.fb_access_Token);
else if (credentials.Google_token != "")
exist= CheckGoogle(credentials.Google_token);
if(exist==true)
{
var identity = new GenericIdentity(credentials.Token);
SetPrincipal(new GenericPrincipal(identity, null));
return true;
}
else
return false;
}
private void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
安全的 Web API 对我来说是一件复杂的事情,我不知道为什么,所以我感谢你的帮助。
请您参考如下方法:
我为 token 使用自定义中间件,如下所示:
public class TokenAuthenticationOptions : AuthenticationSchemeOptions
{
}
public class TokenAuthentication : AuthenticationHandler<TokenAuthenticationOptions>
{
public const string SchemeName = "TokenAuth";
public TokenAuthentication(IOptionsMonitor<TokenAuthenticationOptions> options,
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
return Task.Run(() => Authenticate());
}
private AuthenticateResult Authenticate()
{
string token = Context.Request.Query["token"];
if (token == null) return AuthenticateResult.Fail("No JWT token provided");
try
{
var principal = LoginControl.Validate(token);
return AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName));
}
catch (Exception)
{
return AuthenticateResult.Fail("Failed to validate token");
}
}
}
它使修改更容易。然后你可以在你的启动中使用它:
services.AddAuthentication(TokenAuthentication.SchemeName)
.AddScheme<TokenAuthenticationOptions, TokenAuthentication>
(TokenAuthentication.SchemeName, o => { });
