Как я могу включать модульные тесты в блок знатока?

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

Вот код для отправки ролей пользователя вместе с токеном. что было моим требованием. можно изменить код для отправки необходимых данных.

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        using (UserManager<ApplicationUser> userManager = _userManagerFactory())
        {
            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                context.Options.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                CookieAuthenticationDefaults.AuthenticationType);
            List<Claim> roles = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
            AuthenticationProperties properties = CreateProperties(user.UserName, Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x=>x.Value)));

            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
    }


 public static AuthenticationProperties CreateProperties(string userName, string Roles)
    {
        IDictionary<string, string> data = new Dictionary<string, string>
        {
            { "userName", userName },
            {"roles",Roles}
        };
        return new AuthenticationProperties(data);
    }

. Это вернет мне вывод

`{"access_token":"Vn2kwVz...",
 "token_type":"bearer",
 "expires_in":1209599,
 "userName":"username",
 ".issued":"Sat, 07 Jun 2014 10:43:05 GMT",
 ".expires":"Sat, 21 Jun 2014 10:43:05 GMT"
 "roles"=["Role1","Role2"] }`

. Надеюсь, эта информация кому-нибудь пригодится. :)

10
задан starblue 19 June 2009 в 20:36
поделиться

1 ответ

Есть два шага:

  1. Упаковать тесты в jar вместе с основным кодом.
  2. Зависит от этого jar-файла "-tests" в модуле, который производит сборку.

Чтобы упаковать тесты, нужно убрать цель jar: test-jar . например

<build>
  <plugins>
    <plugin>
      <artifactId>maven-jar-plugin</artifactId>
      <executions>
        <execution>
          <id>test-jar</id>
          <phase>package</phase>
          <goals>
            <goal>test-jar</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

Тогда в модуле сборки вы можете зависеть от результирующего артефакта.

<dependencies>
  <dependency>
    <groupid>${project.groupId}</groupId>
    <artifactId>some-artifact</artifactId>
    <version>${project.version}</version>
    <classifier>tests</classifier>
  </dependency>
</dependencies>

Ключевой бит - это «классификатор».

10
ответ дан 3 December 2019 в 23:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: