R4nc1d R4nc1d - 6 months ago 55
C# Question

MVC with Owin JWT Identity

I am trying to figure out how to get the claim out of my token.
I will try an keep the explanation short


  • I have an HTML page that does a post to my web api, does and auth
    check and returns an JWT token

  • when i get the token back i want to send it to different url, and the way i am doing it is using a querystring. I know i can use cookies but for this app we dont want to use them. So if my url looks like this
    http://somedomain/checkout/?token=bearer token comes here



I am using
Owin
middleware
and this is what i have so far

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
Provider = new ApplicationOAuthBearerAuthenticationProvider(),
});

public class ApplicationOAuthBearerAuthenticationProvider
: OAuthBearerAuthenticationProvider
{

public override Task RequestToken(OAuthRequestTokenContext context)
{
if (context == null)
throw new ArgumentNullException("context");

var token = HttpContext.Current.Request.QueryString["token"];
if (!string.IsNullOrEmpty(token))
context.Token = token;
return Task.FromResult<object>(null);
}
}


But how do i get the
Claims
out of the
Token
or just check the
IsAuthenticated


I tried the Following inside my
controller
just to check, but the
IsAuthenticated
is always
false


var identity = (ClaimsIdentity) HttpContext.Current.GetOwinContext().Authentication.User.Identity;
if (!identity.IsAuthenticated)
return;

var id = identity.FindFirst(ClaimTypes.NameIdentifier);

Answer Source

OK so I managed to figure it out. The above code that I had is all working well but I needed to add the UseJwtBearerAuthentication middle ware.

One thing I did end up changing from my original code was i changed the context.Token = token; to context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });

So my startup class looks like this...

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                Provider = new ApplicationOAuthBearerAuthenticationProvider(),
            });
            app.UseJwtBearerAuthentication(JwtOptions());

            ConfigureAuth(app);
        }


        private static JwtBearerAuthenticationOptions JwtOptions()
        {
            var key = Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["auth:key"]);
            var jwt = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = Some Audience,
                    ValidIssuer = Some Issuer,
                    IssuerSigningToken = new BinarySecretSecurityToken(key),
                    RequireExpirationTime = false,
                    ValidateLifetime = false
                }
            };
            return jwt;
        }

        public class ApplicationOAuthBearerAuthenticationProvider
            : OAuthBearerAuthenticationProvider
        {

            public override Task RequestToken(OAuthRequestTokenContext context)
            {
                if (context == null)
                    throw new ArgumentNullException("context");

                var token = HttpContext.Current.Request.QueryString["token"];
                if (!string.IsNullOrEmpty(token))
                    context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });
                return Task.FromResult<object>(null);
            }
        }
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download