ASP.NET Core 2.1 Jwt настройка пользовательских утверждений - PullRequest
0 голосов
/ 13 ноября 2018

У меня есть этот код, который должен устанавливать претензии для пользователя. Он отлично работает, когда я использую личность и логин по умолчанию. Однако, когда я использую jwt в качестве аутентификации в другом приложении, у меня нет ApplicationUser, поскольку мой ApplicationUser хранится в другом приложении, которое аутентифицирует пользователя. Как я могу настроить этот код так, чтобы он работал с jwt?

private readonly SignInManager<TIdentityUser> _signInManager;

public CustomClaimsCookieSignInHelper(SignInManager<TIdentityUser> signInManager)
{
    _signInManager = signInManager;
}

public async Task SignInUserAsync(TIdentityUser user, bool isPersistent, IEnumerable<Claim> customClaims)
{
    var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
    var identity = claimsPrincipal.Identity as ClaimsIdentity;
    var claims = (from c in claimsPrincipal.Claims select c).ToList();
    var savedClaims = claims;
    if (customClaims != null)
    {
        identity.AddClaims(customClaims);
    }
    await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme,
        claimsPrincipal,
        new AuthenticationProperties { IsPersistent = isPersistent });
}

Полагаю, что мое основное намерение состоит в том, чтобы устанавливать заявки пользователей в httpcontext, а не в cookie, и я хочу сделать это без использования идентификатора.

РЕДАКТИРОВАТЬ:

Моя структура приложения

AuthenticationApp (сервер)

  • Ответственный за аутентификацию пользователей
  • Генерирует и декодирует JWT
  • Проверяет, есть ли у пользователя соответствующие роли, и возвращает true / false через rest api

MainApp (клиент)

  • делает вызов API для AuthenticationApp
  • Не использует личность вообще
  • Отправляет Jwt каждый раз, когда мне нужно проверить роль пользователя

Я понимаю, что смогу декодировать клиентскую часть jwt. Тем не менее, я не знаю, где я могу хранить декодированные детали JWT, чтобы я мог использовать его в представлении. Моя первоначальная идея состояла в том, чтобы использовать Httpcontext как обычные приложения, которые идентифицируют пользователя. Однако я застрял с кодом выше.

1 Ответ

0 голосов
/ 14 ноября 2018

Для обмена информацией об идентичности между Controller и View вы можете подписать информацию о пользователе с помощью HttpContext.SignInAsync.

Попробуйте выполнить нижеприведенные шаги, чтобы выполнить ваше требование:

  • Действие контроллера

        public async Task<IActionResult> Index()
    {
        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "edward"));
        identity.AddClaim(new Claim(ClaimTypes.Name, "edward zhou"));
        //add your own claims from jwt token
        var principal = new ClaimsPrincipal(identity);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });            
        return View();
    }
    
  • Просмотр

    @foreach (var item in Context.User.Claims)
    {
       <p>@item.Value</p> 
    };
    
  • Для работы вышеуказанного кода зарегистрируйте Аутентификацию в Startup.cs

    public class Startup
    {
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    
    public IConfiguration Configuration { get; }
    
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {   
         //your rest code     
    
    
         services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
    }
    
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //your rest code
        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    

    } ​​

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...