Why is my ClaimsIdentity IsAuthenticated always false (for web api Authorize filter)?

后端 未结 2 1662
时光说笑
时光说笑 2020-12-01 01:41

In a Web API project I am overriding the normal authentication process to check tokens instead. The code looks something like this:



        
2条回答
  •  孤街浪徒
    2020-12-01 02:28

    While the provided answer has some validity in it, it is not entirely correct. You can't assume that just adding any string will magically work. As stated in one of the comment, this string must match one of the AuthenticationTypes enumeration which in turn must match the one specified in the OWIN authentication/authorization middleware....for example...

    public void ConfigureOAuth(IAppBuilder app)
            {
                app.UseCors(CorsOptions.AllowAll);
    
                OAuthAuthorizationServerOptions serverOptions = new OAuthAuthorizationServerOptions()
                {
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new Microsoft.Owin.PathString("/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                    AuthenticationType = AuthenticationTypes.Password,
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                    Provider = new AppAuthServerProvider()
                };
    
    
                app.UseOAuthAuthorizationServer(serverOptions);
                app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
                    {
                        AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                        AuthenticationType = AuthenticationTypes.Password
                    });            
            }
    

    However, in the above scenario it wouldn't matter much. But, if you are using more authentication/authorization levels the claims will be associated to the one that matches the same AuthenticationType...another example is when you use cookie authentication...

    public void Configuration(IAppBuilder app)
            {
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = "ApplicationCookie",
                    LoginPath = new PathString("/auth/login")
                });
            }
    

    where AuthenticationType describes the name of the cookie, since your app may have obtained other cookies from other providers it is important that you set the AuthenticationType when instantiating the claims in order to associate then to the correct cookie

提交回复
热议问题