我正在尝试使用自托管的OWIN进行WebApi / Entity Framework项目

我创建了启动类并使用UseOAuthBearerAuthentication和UseOAuthAuthorizationServer配置了OWIN和WebApi,并将Provider定义为从OAuthAuthorizationServerProvider派生的类

Provider = new ApplicationOAuthServerProvider() // :OAuthAuthorizationServerProvider

此类覆盖

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {}

验证用户创建一个ClaimsIdentity返回一个令牌,该令牌编码我的案例中的关联声明NameIdentifier,Name和Role(Role is“Admin”)

一切都按预期工作,并返回令牌 . 现在我想利用ApiController内部的相关声明 . 问题是User.Identityobject只有AuthentiationType isAuthenticated和Name属性所有相关的声明都没有,我对Name属性做不了多少 . 通过使用我看到了

[Authorize (Roles="Admin")]

我能够访问ApiController,因此角色声明在某处可用,但其他声明我无法访问;

有没有办法解决我的问题???

[Authorize (Roles="Admin")]
public class TestController : ApiController
{

    public async Task<Account> Get()
    {
        var principal = User.Identity;
        .... find and return data for user ID
    }
 }

这是我用过的课程

public class Startup
    {
    // This method is required.
    public void Configuration(IAppBuilder app)
    {
        // Use cors on server level
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        // Configure OWIN to authenticate incoming requests.
        ConfigureAuth(app);
        // Use the extension method provided by the WebApi.Owin library.
        app.UseWebApi(ConfigureWebApi());
    }

    private void ConfigureAuth(IAppBuilder app)
    {
        // Make sure a single instance of an EF context is created per OwinContext.
        app.CreatePerOwinContext<ApplicationDbContext>(ApplicationDbContext.Create);

        var OAuthOptions = new OAuthAuthorizationServerOptions{
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthServerProvider(), 
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // Debug Only
            AllowInsecureHttp = true
        };

        // The server is added to the options object, which specifies other configuration items, 
        // and which is then passed into the middleware pipeline.
        app.UseOAuthAuthorizationServer(OAuthOptions);

        // Indicate that we want to return Bearer Tokens 
        // passing the default implementation for OAuthBearerAuthenticationOptions,
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }

    private HttpConfiguration ConfigureWebApi()
    {
        var config = new HttpConfiguration();

        //Add JSON formetters

        // Configure api routes
        config.Routes.MapHttpRoute(
            "DefaultApi",
            "api/{controller}/{id}",
            new { id = RouteParameter.Optional });


        return config;
    }
}

ApplicationOAuthServerProvider类

public class ApplicationOAuthServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // This call is required...
        await Task.FromResult(context.Validated());
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {


        if (context.Password == "Password")
        {
            // Create or retrieve a ClaimsIdentity to represent the 
            // ClaimsIdentity is created to represent the user data, including any Claims the user should have. 
            ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "120"));
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

            // ClaimsIdentity is be encoded into an Access Token
            context.Validated(identity);  
        }
        else
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            context.Rejected();
        }

    }
}