2017-10-25 1 views
6

"웹 응용 프로그램 (모델보기 컨트롤러)"템플릿과 ".Net"을 사용하여 VS17에 새로운 ASP.NET 핵심 웹 응용 프로그램 프로젝트를 만들었습니다. 프레임 워크 "+"ASP.NET Core 2 "를 구성으로 사용합니다. 인증 구성은 "개별 사용자 계정"으로 설정됩니다.동일한 끝점에 대해 쿠키와 무기명 인증을 결합한 ASP.NET Core 2.0

[Produces("application/json")] 
[Route("api/price")] 
[Authorize(Roles = "PriceViwer", AuthenticationSchemes = "Cookies,Bearer")] 
public class PriceController : Controller 
{ 

    public IActionResult Get() 
    { 
     return Ok(new Dictionary<string, string> { {"Galleon/Pound", 
                "999.999" }); 
    } 
} 

"Cookies,Bearer"CookieAuthenticationDefaults.AuthenticationSchemeJwtBearerDefaults.AuthenticationScheme을 연결하여 산출 :

나는 다음 샘플 엔드 포인트가 있습니다.

목표는 토큰 및 쿠키 인증 방법을 사용하여 액세스 할 수 있도록 끝점에 대한 인증을 구성 할 수 있도록하는 것입니다. 그래서

services.AddAuthentication() 
     .AddCookie(cfg => { cfg.SlidingExpiration = true;}) 
     .AddJwtBearer(cfg => { 
      cfg.RequireHttpsMetadata = false; 
      cfg.SaveToken = true; 
      cfg.TokenValidationParameters = new TokenValidationParameters() { 
                ValidIssuer = Configuration["Tokens:Issuer"], 
                ValidAudience = Configuration["Tokens:Issuer"], 
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])) 
               }; 
     }); 

, 나는 브라우저를 사용하여 엔드 포인트에 액세스하려고 할 때, 그리고

I get the 401 response with a blank html page. 내가 로그인하고 내가하려고하면 다음

내 Startup.cs에서 내가 인증에있는 설정입니다 엔드 포인트에 다시 액세스하려면 동일한 응답을 얻습니다.

그런 다음 베어러 토큰을 지정하여 끝점에 액세스하려고합니다. 어떤 결과를 그냥 기본 AspIdentity 로그인 페이지로 리디렉션하지 않는 이상 사용하지만 같은 베어러 토큰 방법 쿠키 인증 작품과 200을 반환 - 내가 [Authorize(AuthenticationSchemes = "Cookies,Bearer")] 제거하면 And that returns the desired result with the 200 response.

그래서 다음, 상황은 반대가된다 .

내가 여기에 두 가지 문제를 볼 수 있습니다

1) ASP.NET 핵심은 '결합'인증을 허용하지 않습니다. 2) '쿠키'는 유효한 스키마 이름이 아닙니다. 그렇다면 사용하기에 적합한 것은 무엇입니까?

알려 주시기 바랍니다. 고맙습니다.

+0

Idendity를 사용합니까? – Nikolaus

+0

aspnet core 1.0에서 동일한 쿠키 및 베어러를 사용하고 있습니다. 2.0으로 마이그레이션 할 때 동일한 문제가 발생할 것입니다 : ( – Ruchan

+0

조치에서 'AuthenticationScheme'을 전혀 언급하지 않아도된다면 좋을 것입니다. – Ruchan

답변

3

여러분의 컨트롤러에 AuthenticationScheme을 설정할 필요가 없다고 생각합니다. 다만이 같은 ConfigureServices에서 인증 된 사용자를 사용 :

// requires: using Microsoft.AspNetCore.Authorization; 
//   using Microsoft.AspNetCore.Mvc.Authorization; 
services.AddMvc(config => 
{ 
    var policy = new AuthorizationPolicyBuilder() 
        .RequireAuthenticatedUser() 
        .Build(); 
    config.Filters.Add(new AuthorizeFilter(policy)); 
}); 

을 내 소스 문서의 경우 : 파트에 registerAuthorizationHandlers

, 계획 - 키가 유효하지 여부, 당신은 사용, 보간 된 문자열을 사용할 수 있습니다 올바른 키 :

[Authorize(AuthenticationSchemes = $"{CookieAuthenticationDefaults.AuthenticationScheme},{JwtBearerDefaults.AuthenticationScheme}")] 

편집 : 를 그것은 두 구성표 또는 같은과 방법에 권한을 부여 할 수는 없지만 두 페이지를 사용할 수 있습니다 : 나는 더 많은 연구를했고, 다음과 같은 결론에 도달했다 ublic 메서드를 호출하여 다음과 같은 private 메서드를 호출하십시오.

//private method 
private IActionResult GetThingPrivate() 
{ 
    //your Code here 
} 

//Jwt-Method 
[Authorize(AuthenticationSchemes = $"{JwtBearerDefaults.AuthenticationScheme}")] 
[HttpGet("bearer")] 
public IActionResult GetByBearer() 
{ 
    return GetThingsPrivate(); 
} 

//Cookie-Method 
[Authorize(AuthenticationSchemes = $"{CookieAuthenticationDefaults.AuthenticationScheme}")] 
[HttpGet("cookie")] 
public IActionResult GetByCookie() 
{ 
    return GetThingsPrivate(); 
} 
+0

응답 해 주셔서 감사합니다! 불행히도 이것으로 문제가 해결되지 않습니다. 주석에서 config snippet을 사용하고 엔드 포인트 데코레이터에서 AuthenticationScheme을 제거하면 표준 쿠키 방법이 작동하지만 토큰 하나는 그렇지 않습니다. – maximiniini

+0

@maximiniini 주문을 취소 하시겠습니까? '[Authorize (AuthenticationSchemes = "Bearer, Cookies")]' – Nikolaus

+0

@maximiniini 답을 업데이트했습니다. 아마도 이것은 당신을 도울 수 있습니다. – Nikolaus

관련 문제