Secure Web API with token c#

时间:2018-02-01 18:18:17

标签: c# asp.net-web-api2

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 个答案:

答案 0 :(得分:2)

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 => { });

答案 1 :(得分:1)

你不能“保存令牌”,因为API是无状态的,这意味着(除其他外)不应该跟踪正在调用的客户端及其相应的身份验证令牌(会话)。

也就是说,您需要每次都传递令牌,并在OWIN管道中定义授权中间件,以验证发送的令牌。这是使用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);
    }

来自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();
    }