2016-10-26 1 views
0

Angular 1을 사용하여 (VS2013) MVC5로 작성된 구형 응용 프로그램을 Angular 2와 (VS2015) MVC 6으로 마이그레이션합니다. MVC 5 응용 프로그램에서 그때 다음 코드 줄을 사용하여 세션에 저장하는 데 사용되는 웹 UI 측에 포스트 액션 메소드에서 클라이언트에서 토큰을받을 : 위의 코드는 비 aspnetcore 프로젝트와 내가 잘 작동 Angular에서 보낸 Aspnet 코어 1.0 웹 사이트에 JWT 사용

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

다음 코드 행을 사용하여 권한 부여 컨텍스트에서 클레임을 검색 할 수 있습니다. action은 호출중인 해당 조치 메소드에 대한 속성에 대한 클레임 세트를 포함하고 있으며, 지정된 클레임의 참 또는 거짓 bool이 있는지 여부를 나타냅니다. n은 context.Principal입니다. 내 EvaluateToken 방법에

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

코드 줄에 : 핵심 프로젝트로 이동할 때

public class CustomClaimsAuthorizationManager: ClaimsAuthorizationManager 
{ 

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

그러나, 나는이 오류가

SessionAuthenticationModule ssm = FederatedAuthentication.SessionAuthenticationModule; 

나는이 라인이 필요 내 사용자 지정 클레임 특성이있는 작업 메서드에 액세스하려고 할 때 토큰의 클레임이 존재하는지 여부를 평가할 수 있어야합니다. 있는 그대로 aspnet 코어로 옮길 방법이 없다면 aspnet core에서 토큰을 사용하여 전달 된 토큰과 청취자, 발급자 및 비밀 키만 갖는 특정보기에 대한 액세스 권한을 부여하는 방법을 알고 싶습니다 토큰을 생성하는 데 사용됩니다. 설명서에서 사용자 지정 정책을 추가하도록 지정하고 다른 경로를 사용하는 것으로 보입니다. UI 측면에서 주 객체에 클레임을 저장하는 로직을 사용하는 방법을 잘 모르겠습니다. 따라서 UI 측면에서 뷰간에 이동할 때 사용할 수 있습니다.

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

답변

0

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

HttpContext.Current가 ASPNET 코어에서 사용할 수 없습니다 :

이 내 startup.cs이 구성 방법에 ASPNET 코어 웹 프로젝트 파일에 내가 가지고있는 것입니다. 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

은 (내가 주장이 토큰에 저장되어 가정) :

  1. JWT 인증 미들웨어 (당신이 이미 그것을 시도)
  2. Claims Based Authorization.

당신이 다음 JWT 인증 미들웨어의 Claims Transformation 또는 OnTokenValidated 이벤트를 사용할 수있는 토큰에 저장되지 않은 추가 요구를해야하는 경우.

+0

나는'Authorize' 속성이 아닌'ClaimsPrinciplePermission' 속성을 사용하고 있습니다. aspnet 코어에서'ClaimsPrinciplePermission'으로이 작업을 수행 할 수 있습니까? 아니면 모든 권한을 승인해야합니까? – user20358

+0

귀하의 사례에 대해 ClaimsPrinciplePermission을 사용해야하는 특별한 이유가 있습니까? 그렇지 않으면 authorize 특성을 사용합니다. –

+0

레거시 코드를 aspnet 코어로 마이그레이션하려고합니다. 그렇게하기 위해서는 많은 재 작업이 필요합니다. 관련 메모에서 나는 로그인 (http://andrewlock.net/introduction-to-authentication-with-asp-net-core/) 및이 예제 (https : //docs.asp.net/en/latest/security/authorization/policies.html)을 참조하십시오. 그러나,'AuthorizationHandlerContext context' 프로퍼티의 클레임리스트는 결과가 없습니다. 왜 이런거야? – user20358