0

I am migrating my older app written in (VS2013) MVC5 with Angular 1 to (VS2015) MVC 6 with Angular 2. In my MVC 5 app, I used to recieve a token from the client in a post action method on the Web UI side which I used to then store to session using the following lines of code :

 //Store token details
 [HttpPost]
 public void EvaluateToken(string token)
 {
    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
    SecurityToken st = tokenHandler.ReadToken(token);
    var tokenData = ((JwtSecurityToken)st);
    var claims = tokenData.Claims.Where(t => t.Type.Equals(" ")).ToList();

    ClaimsIdentity cIdentity = new ClaimsIdentity(DefaultAuthenticationTypes.ExternalBearer);
    ci.AddClaims(claims);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, cIdentity );

    string user = "//get username from token";

    ClaimsPrincipal cPrincipal = new ClaimsPrincipal (cIdentity);

    //write to cookie
    SessionSecurityToken sst = new SessionSecurityToken(cPrincipal , TimeSpan.FromMinutes(20));
    sst.IsReferenceMode = true; 
    SessionAuthenticationModule ssm = FederatedAuthentication.SessionAuthenticationModule;
    ssm.WriteSessionTokenToCookie(sst);
 }

The code above works well for non-aspnetcore projects and I am able to retrieve the claims from the Authorization Context using the following lines of code where action contains the claim set on the attribute over the respective action method being called and val contains a bool true or false of the specified claim exists or not in the context.Principal.

public class CustomClaimsAuthorizationManager: ClaimsAuthorizationManager
{

    public override bool CheckAccess(AuthorizationContext context)
    {
        var action = context.Action.First().Value;
        bool val= context.Principal.HasClaim(" ", action);
        return val;
    }
}

However, when moving to a core project, I get this error:

ID1061: HttpContext.Current is null. This code path is only valid when in the execution context of ASP.NET.

on this line of code in my EvaluateToken method:

SessionAuthenticationModule ssm = FederatedAuthentication.SessionAuthenticationModule;

I need this line to work so that when I try to access an action method that has my custom claim attribute, I should be able to evaluate if the claim in the token exists or not. If there is no way to move this as-is to aspnet core, then I want to know how in aspnet core can I use a token to authorize access to a particular view having only the passed in token and the audience, issuer and secret key used to generate the token. The documentation specifies adding custom policies and seems to take a different path. I'm not sure how to use that kind of logic to store the claims in a principal object on the UI side so it can be used when moving between views on the UI side.

This is what I have in my startup.cs file on the aspnet core web project in the Configure method:

var issuer = "localhost";
var aud = "localhost";
var secret = "SecretValueHere";

var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret));

            var jwtBearerOptions = new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                Audience = aud ,
                ClaimsIssuer = issuer,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = signingKey,
                    ValidateIssuer = true,
                    ValidIssuer = issuer,
                    ValidateAudience = true,
                    ValidAudience = aud ,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                    RequireExpirationTime = true  
                }
            };

            app.UseJwtBearerAuthentication(jwtBearerOptions);
user20358
  • 14,182
  • 36
  • 114
  • 186

1 Answers1

0

ID1061: HttpContext.Current is null. This code path is only valid when in the execution context of ASP.NET.

HttpContext.Current is not available in Aspnet Core. See Access HttpContext.Current .

I need this line to work so that when I try to access an action method that has my custom claim attribute, I should be able to evaluate if the claim in the token exists or not

You just need(i assume claims are stored in token):

  1. JWT authentication middleware(you already tried it)
  2. Claims Based Authorization.

If you need additional claims not stored in token then you can use Claims Transformation or OnTokenValidated event of jwt authentication middleware.

Community
  • 1
  • 1
adem caglin
  • 22,700
  • 10
  • 58
  • 78
  • I am using `ClaimsPrinciplePermission` attribute and not the `Authorize` attribute. Is there a way to do it with `ClaimsPrinciplePermission` in aspnet core? or do I have to move all that to Authorize? – user20358 Oct 27 '16 at 15:12
  • Is there a special reason to use ClaimsPrinciplePermission for your case? If not i would use authorize attribute. – adem caglin Oct 27 '16 at 16:56
  • I am migrating legacy code over into aspnet core. There would be a lot of rework to do that. On a related note, I have tried what you mentioned, using this example here to do a login ( http://andrewlock.net/introduction-to-authentication-with-asp-net-core/ ) and this example ( https://docs.asp.net/en/latest/security/authorization/policies.html ) to evaluate incoming claims. However, the list of claims in the `AuthorizationHandlerContext context` property yeilds no result. Why is this? – user20358 Oct 27 '16 at 17:16
  • Make sure jwt bearer authentication works correctly and sets principal claims. You can look User.Claims to check. Also could you post code you try. – adem caglin Oct 27 '16 at 17:41