Problem with Oauth2 JWT in Webapi2

Asked

Viewed 107 times

1

Basically all code is working, I can generate my token, I can do everything, but I’m not able to validate the token.

My code is like this when I call the api. What happens is: I’m sending the request with the token, but it still doesn’t validate, the token is in the header but it can’t validate.

(I’ve already added the Claims, startup part 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 wearing this one 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)
        });
    }
}
  • When you try to access this endpoint it gives authorization error?

  • {&#xA; "message": "Authorization has been denied for this request."&#xA;} Request header: Accept:application/json Content-Type:application/json Authorization:Bearer eyJ0eXAiOJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbSIsInVzZXIiOiJhZG0iLCJyb2xlIjoiYWRtaW4iLCJpc3MiOiJodHRwOi8vbG9jWxob3N0LyIsImV4cCIMTQ4MTkwMTEyOSwiJmIjoxNDgxDk5MzI5fQ.ddh33ynUqZZZyKvth586abvw-Zvepxxdrvetu

  • You didn’t have to post the entire payload, just confirm =) You have to post the code that works with the token (generates/receives/sends) and not the code of the controller, we only need the signature and the Attributes. Does authentication already work elsewhere? Are you using Webapi 2?

  • The code that works with the token is the same as the one in the tutorial, not the authentication is not working. I thought it might be a problem with the Onauthorization method, I tried to make a new filter for the authorization, but it doesn’t even enter the method. public class FilterConfig&#xA; {&#xA; public static void RegisterGlobalFilters(GlobalFilterCollection filters)&#xA; { filters.Add(new ValidateUserRoles());}&#xA; }&#xA;&#xA; public class ValidateUserRoles : FilterAttribute, IAuthorizationFilter&#xA; {&#xA; public void OnAuthorization(AuthorizationContext filterContext)&#xA; {}}}

  • sorry for the bad indentation

  • You [Dit] the question and add that information to it. Comments don’t quite fit that

  • Yes, I’m using webAPI 2, I’m sure I’m sinning on something simple and I’m not noticing :(

  • That’s why it takes your code for us to understand what you’re doing... We can’t help you without knowing what’s going on.

  • I added the code =)

  • I managed to solve my problem, as soon as I finish my code I will post here =D

  • Guilherme the question is still open. Did you solve it? If so, add the answer.

Show 6 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.