BearerTokenRealm extends AuthenticatingRealm { @Override protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) { checkNotNull(token); final PrincipalCollection principals = keyStore.getPrincipals(format, (char[]) token.getCredentials()); if (null != principals) { try { if (anonymousAndSupported(principals) || principalsHelper.getUserStatus(principals).isActive()) { ((NexusApiKeyAuthenticationToken) token).setPrincipal(principals.getPrimaryPrincipal()); if (requestProvider != null) { requestProvider.get().setAttribute(IS_TOKEN_AUTH_KEY, Boolean.TRUE); } return new SimpleAuthenticationInfo(principals, token.getCredentials()); } } catch (final UserNotFoundException e) { log.debug("Realm did not find user", e); keyStore.deleteApiKeys(principals); } } return null; } BearerTokenRealm(final ApiKeyStore keyStore,
                          final UserPrincipalsHelper principalsHelper,
                          final String format); @Override boolean supports(final AuthenticationToken token); static final String IS_TOKEN_AUTH_KEY; }
@Test public void getAuthInfoWhenActive() throws Exception { AuthenticationInfo authenticationInfo = underTest.doGetAuthenticationInfo(token); assertThat(authenticationInfo.getPrincipals(), is(notNullValue())); verify(token).setPrincipal(principal); }
@Test public void getAuthInfoWhenAnonymousAndSupported() throws Exception { when(principalCollection.getPrimaryPrincipal()).thenReturn(ANONYMOUS_USER); when(principalsHelper.getUserStatus(principalCollection)).thenReturn(UserStatus.disabled); underTest = new BearerTokenRealm(keyStore, principalsHelper, FORMAT) { @Override protected boolean isAnonymousSupported() { return true; } }; AuthenticationInfo authenticationInfo = underTest.doGetAuthenticationInfo(token); assertThat(authenticationInfo.getPrincipals(), is(notNullValue())); verify(token).setPrincipal("anonymous"); }
@Test public void nullWhenAnonymousButNotSupported() throws Exception { when(principalsHelper.getUserStatus(principalCollection)).thenReturn(UserStatus.disabled); when(principalCollection.getPrimaryPrincipal()).thenReturn(ANONYMOUS_USER); assertThat(underTest.doGetAuthenticationInfo(token), is(nullValue())); }
@Test public void deleteKeysOnUserNotFoundException() throws Exception { when(principalsHelper.getUserStatus(principalCollection)).thenThrow(new UserNotFoundException("userid")); assertThat(underTest.doGetAuthenticationInfo(token), is(nullValue())); verify(keyStore).deleteApiKeys(principalCollection); }
@Test public void nullAuthInfoWhenPrincipalsNull() throws Exception { when(keyStore.getPrincipals(any(), any())).thenReturn(null); assertThat(underTest.doGetAuthenticationInfo(token), is(nullValue())); }
@Test public void nullAuthInfoWhenUserNotActive() throws Exception { when(principalsHelper.getUserStatus(principalCollection)).thenReturn(UserStatus.disabled); assertThat(underTest.doGetAuthenticationInfo(token), is(nullValue())); }