C# 使用令牌c保护Web API#

C# 使用令牌c保护Web API#,c#,asp.net-web-api2,C#,Asp.net Web Api2,我用Cordova创建了一个移动应用程序,有两种登录方式Facebook和Google。我在验证令牌(FB或Google)后,我想使用其中一个令牌来保护我的Web API 2并与我的应用程序通信,但我不知道在Web API中存储它的位置,我将它保存到Thread.CurrentPrincipal,但稍后它返回null 这是我的代码: public bool UserExist(Credentials credentials,ISQLDB socialDB,IEncrypt encrypt

我用Cordova创建了一个移动应用程序,有两种登录方式Facebook和Google。我在验证令牌(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安全对我来说是一件复杂的事情,我不知道为什么,所以我感谢你的帮助

我对代币使用自定义中间件,如下所示:

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

    }
}
公共类TokenAuthenticationOptions:AuthenticationSchemeOptions
{
}
公共类令牌身份验证:AuthenticationHandler
{
public const string SchemeName=“TokenAuth”;
公共令牌身份验证(IOptionsMonitor选项,
iLogger(出厂记录器、URLCoder编码器、ISystemClock时钟)
:基本(选项、记录器、编码器、时钟)
{
}
受保护的覆盖任务handleAuthenticateAync()
{
返回任务。运行(()=>Authenticate());
}
私有AuthenticateResult Authenticate()
{
string token=Context.Request.Query[“token”];
if(token==null)返回AuthenticateResult.Fail(“未提供JWT令牌”);
尝试
{
var principal=LoginControl.Validate(令牌);
返回AuthenticateResult.Success(新的AuthenticationTicket(主体,SchemeName));
}
捕获(例外)
{
返回AuthenticateResult.Fail(“验证令牌失败”);
}
}
}
它使修改更容易。然后,您可以在启动时使用:

services.AddAuthentication(TokenAuthentication.SchemeName)
    .AddScheme<TokenAuthenticationOptions, TokenAuthentication>
                (TokenAuthentication.SchemeName, o => { });
services.AddAuthentication(TokenAuthentication.SchemeName)
.AddScheme
(TokenAuthentication.SchemeName,o=>{});
您不能“保存令牌”,因为API是无状态的,这意味着(除其他外)不应跟踪正在调用的客户端及其相应的身份验证令牌(会话)

也就是说,您需要每次传递令牌,并在OWIN管道中定义授权中间件,以验证发送的令牌。这是一个使用

来自的附加示例


您可能想考虑在令牌认证上使用中间件,难道您不想使用JWT中间件吗?谢谢,但我不使用Login控件。如何从我的web api调用这个类?我喜欢你的代码。我将在几个月后编写我的自定义令牌,也许我可以看看这段代码。你们分享了所有关于cutom令牌的信息吗?哦,登录控件是我自己的类。我的意思是给你看源代码。忘了吧@MuratCanOĞUZHAN我计划用一个完整的令牌示例来完成上面共享的git。几个月后,它应该准备好了,你可以参考GitThreak@NevilleNazerane
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);
    }
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();
    }