I created a mobile app with Cordova, with 2 Login methods Facebook and Google. I after I authenticate the token (FB or Google) I want to use one of them to secure my Web API 2 and communicate with my APP, but I don’t know where to store it in the web API, I saved it to Thread.CurrentPrincipal but it returns null later.
This is my code:
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 secure is a complicated thing to me, I don’t know why, so I appreciate your help.
2
Answers
I use custom middlewares for tokens something like this:
It makes it easier for modifications. You can then have this in your startup:
You cannot “save the token”, since the API is stateless, this meaning (among other things) that should not keep track of the clients that are calling and their corresponding auth tokens (sessions).
That said, you need to pass the token every time, and have an authorization middleware defined in your OWIN pipeline, to validate the token sent. This is an example using IdentityServer
Additional example from MS Docs