0

I'm experimenting with self hosted OWIN for a WebApi/Entity Framework project

I've created the Startup Class and configured both OWIN and WebApi using UseOAuthBearerAuthentication and UseOAuthAuthorizationServer with Provider defined to a Class deriving from OAuthAuthorizationServerProvider

 Provider = new ApplicationOAuthServerProvider() // :OAuthAuthorizationServerProvider

this Class overrides

 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {}

validate the user creates a ClaimsIdentity returning a token encoding the associated claims in my case NameIdentifier, Name and Role (Role is "Admin")

Everything works as expected and token is returned. Now I'd like to take advantage of the associated claims from inside an ApiController. Problem is User.Identityobject has only AuthentiationType isAuthenticated and Name properties all associated Claims are not there and I can't do much with Name property. I see that by using

[Authorize (Roles="Admin")]

I'm able to access the ApiController so the Role Claim is available somewhere but the other claims I'm not able to access;

is there a way to solve my issue???

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

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

Here are the Classes I've used

    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 Class

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

    }
}
Gavello
  • 1,399
  • 2
  • 13
  • 25
  • 1
    This looks like a duplicate of [Thread1][1] and [Thread2][2]. Have you checked these? [1]: http://stackoverflow.com/questions/23926205/mvc-5-with-asp-net-identity-get-claims-when-user-logs-in [2]: http://stackoverflow.com/questions/21404935/mvc-5-access-claims-identity-user-data – rll Jul 22 '15 at 13:42
  • found my answare inside the mentioned threads thx – Gavello Jul 23 '15 at 13:18

0 Answers0