Problem with OAuth2 JWT in WebApi2

1

I'm trying to get the token in the form of a token, but I'm not able to validate the token.

My code looks like this when I'm going to call api. What happens is: I am sending the request with the token, but it still does not validate, the token is in the header but it can not validate.

(I already added the claims, part of startup and startup.auth is set up the same as the site, if necessary put the rest of the code.)

[Authorize(Roles ="user")]
[HttpGet]
[Route("api/testeToken")]
public HttpResponseMessage testeToken()
{
    var user = User.Identity;
    HttpResponseMessage responseMessage = new HttpResponseMessage()
    {
        Content = new StringContent("{\"message\":\"asdasd\", \"payload\":\"\",\"response\":\"2123\"}")
    };

    return responseMessage;
}

I'm using this tutorial

FilterConfig.cs:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ValidateUserRoles());
        filters.Add(new HandleErrorAttribute());
    }
}

public class ValidateUserRoles : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
           //
        }

    }
}

CustomOAuthProvider.cs:

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

            IdentityUser novo = new IdentityUser(context.UserName);

            var ticket = new AuthenticationTicket(SetClaimsIdentity(context, novo), new AuthenticationProperties());
            context.Validated(ticket);

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

        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult<object>(null);
        }

        private static ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context, IdentityUser user)
        {
            var identity = new ClaimsIdentity("JWT");
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("user", context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role,"user"));

            return identity;
        }
    }

CustomJwtFormat.cs:

public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
    {
        private static readonly byte[] _secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);
        private readonly string _issuer;

        public CustomJwtFormat(string issuer)
        {
            _issuer = issuer;
        }

        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            var signingKey = new HmacSigningCredentials(_secret);
            var issued = data.Properties.IssuedUtc;
            var expires = data.Properties.ExpiresUtc;

            return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(_issuer, null, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey));
        }

        public AuthenticationTicket Unprotect(string protectedText)
        {
            throw new NotImplementedException();
        }
    }

Startup.cs:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
    }
}

Startup.Auth.cs:

public partial class Startup
{
    public void ConfigureOAuth(IAppBuilder app)
    {

        var issuer = ConfigurationManager.AppSettings["issuer"];
        var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);


        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new[] { "Any" },
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
}
        });


        app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/oauth2/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = new CustomOAuthProvider(),
            AccessTokenFormat = new CustomJwtFormat(issuer)
        });
    }
}
    
asked by anonymous 16.12.2016 / 15:35

0 answers