skip to Main Content

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


  1. I use custom middlewares for tokens something like this:

       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");
            }
    
        }
    }
    

    It makes it easier for modifications. You can then have this in your startup:

    services.AddAuthentication(TokenAuthentication.SchemeName)
        .AddScheme<TokenAuthenticationOptions, TokenAuthentication>
                    (TokenAuthentication.SchemeName, o => { });
    
    Login or Signup to reply.
  2. 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

    public void Configuration(IAppBuilder app)
            {
                // accept access tokens from identityserver and require a scope of 'api1'
                app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
                    {
                        Authority = "http://localhost:5000",
                        ValidationMode = ValidationMode.ValidationEndpoint,
                    RequiredScopes = new[] { "api1" }
                });
    
            // configure web api
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
    
            // require authentication for all controllers
            config.Filters.Add(new AuthorizeAttribute());
    
            app.UseWebApi(config);
        }
    

    Additional example from MS Docs

    public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use cookies to authenticate users
            app.UseCookieAuthentication(CookieOptions);
    
            // Enable the application to use a cookie to store temporary information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(ExternalCookieAuthenticationType);
    
            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions, ExternalOAuthAuthenticationType);
    
            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");
    
            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");
    
            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");
    
            //app.UseGoogleAuthentication();
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search