2017-03-06 12 views
0

ミドルウェア経由でASP NETコアアプリケーションでユーザー名を設定する方法はありますか?ASP NETコア:HttpContextのユーザー名を上書きする

私はAnonymousUserMiddlewareを作成しました:

public AnonymousUserMiddleware(RequestDelegate next, HttpContextCurrentClaimsPrincipalAccessor currentClaimsPrincipalAccessor, ILogger<AnonymousUserMiddleware> logger) 
    { 
     _next = next; 
     _currentClaimsPrincipalAccessor = currentClaimsPrincipalAccessor; 
     _logger = logger; 
    } 

    public async Task Invoke(HttpContext context) 
    { 
     try 
     { 
      _currentClaimsPrincipalAccessor?.Current?.Identity?.Name = "anonymous"; 
      await _next.Invoke(context); 
     } 
     catch (Exception ex) 
     { 
      _logger.LogError(1, ex, "Exception"); 
      throw ex; 
     } 
    } 

しかし、これは動作しません、Nameが読み取り専用フィールドであるため。

デベロッパーモードのときにStartup.csに電話して、リクエスト中にユーザー名が常に「匿名」になるようにします。

これを行う方法はありますか?

答えて

1

独自のClaimsPrincipalを作成し、そのインスタンスをHttpContextに割り当てることができます。例:

public async Task Invoke(HttpContext context) 
{ 
    try 
    { 
     var identity = new ClaimsIdentity(); 
     identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "anonymous", "http://www.w3.org/2001/XMLSchema#string")); 

     var principal = new ClaimsPrincipal(); 
     principal.AddIdentity(identity); 

     context.User = principal; 

     await _next.Invoke(context); 
    } 
    catch (Exception ex) 
    { 
     _logger.LogError(1, ex, "Exception"); 
     throw ex; 
    } 
} 
関連する問題