c# – Owin承载令牌不适用于WebApi

前端之家收集整理的这篇文章主要介绍了c# – Owin承载令牌不适用于WebApi前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经经历了大量的文档,我的谷歌搜索显示我已经访问了第一页上的所有链接

问题
令牌代工作正常.我使用自定义提供程序配置它:

public void ConfigureOAuth(IAppBuilder app)
    {
        var usermanager = NinjectContainer.Resolve<UserManager>(); 
        app.USEOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,TokenEndpointPath = new PathString("/token"),AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),Provider = new AppOAuthProvider(usermanager)
        });
        app.USEOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }

但是当我调用受保护的URL并传递承载令牌时,我总是得到:

如何诊断或解决问题.如果可能,我该如何进行令牌验证

UPDATE
这是我的AppOAuthProvider.当我尝试创建一个令牌时调用这两个方法,但是当我尝试访问受保护的资源时,这两个方法都会被调用

public class AppOAuthProvider : OAuthAuthorizationServerProvider
{
    private UserManager _user;
    public AppOAuthProvider(UserManager user)
    {
        _user = user;
    }
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",new[] { "*" });

        //Get User Information
        var getUser = _user.FindUser(context.UserName);
        if (getUser.Status == StatusCode.Failed)
        {
            context.SetError("invalid_grant","The user name or password is incorrect.");
            return Task.FromResult<object>(null);
        }

        var user = getUser.Result;

        //Get Roles for User
        var getRoles = _user.GetRoles(user.UserID);
        if (getRoles.Status == StatusCode.Failed)
        {
            context.SetError("invalid_grant","Could not determine Roles for the Specified User");
        }

        var roles = getRoles.Result;

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("UserID",user.UserID.ToString()));
        identity.AddClaim(new Claim("UserName",user.UserName));

        foreach (var role in roles)
        {
            identity.AddClaim(new Claim(ClaimTypes.Role,role));
        }

        context.Validated(identity);

        return Task.FromResult<object>(null);
    }
}

更新2:
这是我的帐号控制器

[RoutePrefix("api/auth/account")]
public class AccountController : ApiController
{
    private UserManager _user;
    public AccountController(UserManager user)
    {
        _user = user;
    }

    [Authorize]
    [HttpGet]
    [Route("secret")]
    public IHttpActionResult Secret()
    {
        return Ok("Yay! Achievement Unlocked");
    }
}

更新3:
这是我的Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseNinjectMiddleware(NinjectContainer.CreateKernel);
        app.UseNinjectWebApi(GlobalConfiguration.Configuration);
        GlobalConfiguration.Configure(WebApiConfig.Register);
        ConfigureOAuth(app);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(GlobalConfiguration.Configuration);
        app.UseWelcomePage();
    }
}

解决方法

在IAppBuilder上调用UseWebApi之前,必须先配置OAuth授权服务器和OAuth承载认证.以下是我的程序.
public void Configuration(IAppBuilder app)
    {
        app.UseFileServer(new FileServerOptions()
        {
            RequestPath = PathString.Empty,FileSystem = new PhysicalFileSystem(@".\files")
        });

        // set the default page
        app.UseWelcomePage(@"/index.html");

        ConfigureAuth(app);

        HttpConfiguration config = new HttpConfiguration();

        config.Routes.MapHttpRoute
        (
            name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional } 
        );

        config.Formatters.Clear();
        config.Formatters.Add(new JsonMediaTypeFormatter());
        config.Formatters.JsonFormatter.SerializerSettings =
        new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };

        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(config);


    }

    public void ConfigureAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,Provider = new YourApplicationOAuthProvider()
        };

        app.USEOAuthAuthorizationServer(oAuthServerOptions);
        app.USEOAuthBearerAuthentication
        (
            new OAuthBearerAuthenticationOptions 
            {
                Provider = new OAuthBearerAuthenticationProvider()
            }
        );
    }
原文链接:https://www.f2er.com/csharp/96174.html

猜你在找的C#相关文章