org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken Java Examples
The following examples show how to use
org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DirectAccessGrantUserDetailsAuthenticationProvider.java From smartling-keycloak-extras with Apache License 2.0 | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) super.authenticate(authentication); String username; UserDetails userDetails; if (token == null) { return null; } username = this.resolveUsername(token); userDetails = userDetailsService.loadUserByUsername(username); return new KeycloakUserDetailsAuthenticationToken(userDetails, token.getAccount(), token.getAuthorities()); }
Example #2
Source File: KeycloakUserDetailsAuthenticationProviderTest.java From smartling-keycloak-extras with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); Set<UserDetails> users = new HashSet<>(); user = new User(KNOWN_USERNAME, "password", Arrays.asList(new SimpleGrantedAuthority("user"))); users.add(user); userDetailsService = new InMemoryUserDetailsManager(Collections.unmodifiableCollection(users)); provider = new KeycloakUserDetailsAuthenticationProvider(); provider.setUserDetailsService(userDetailsService); when(principal.getName()).thenReturn(KNOWN_USERNAME); when(account.getPrincipal()).thenReturn(principal); token = new KeycloakAuthenticationToken(account); }
Example #3
Source File: KeycloakAuthenticationProcessingFilter.java From keycloak with Apache License 2.0 | 6 votes |
@Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { if (authResult instanceof KeycloakAuthenticationToken && ((KeycloakAuthenticationToken) authResult).isInteractive()) { super.successfulAuthentication(request, response, chain, authResult); return; } if (log.isDebugEnabled()) { log.debug("Authentication success using bearer token/basic authentication. Updating SecurityContextHolder to contain: {}", authResult); } SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authResult); SecurityContextHolder.setContext(context); try { // Fire event if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); } chain.doFilter(request, response); } finally { SecurityContextHolder.clearContext(); } }
Example #4
Source File: KeycloakAuthenticationProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) authentication; List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for (String role : token.getAccount().getRoles()) { grantedAuthorities.add(new KeycloakRole(role)); } return new KeycloakAuthenticationToken(token.getAccount(), token.isInteractive(), mapAuthorities(grantedAuthorities)); }
Example #5
Source File: KeycloakAuthenticationProcessingFilterTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void testSuccessfulAuthenticationBasicAuth() throws Exception { Authentication authentication = new KeycloakAuthenticationToken(keycloakAccount, false, authorities); this.setBasicAuthHeader(request); filter.successfulAuthentication(request, response, chain, authentication); verify(chain).doFilter(eq(request), eq(response)); verify(successHandler, never()).onAuthenticationSuccess(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); }
Example #6
Source File: KeycloakAuthenticationProcessingFilterTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void testSuccessfulAuthenticationBearer() throws Exception { Authentication authentication = new KeycloakAuthenticationToken(keycloakAccount, false, authorities); this.setBearerAuthHeader(request); filter.successfulAuthentication(request, response, chain, authentication); verify(chain).doFilter(eq(request), eq(response)); verify(successHandler, never()).onAuthenticationSuccess(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); }
Example #7
Source File: KeycloakAuthenticationProcessingFilterTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void testSuccessfulAuthenticationInteractive() throws Exception { request.setRequestURI("http://host" + KeycloakAuthenticationEntryPoint.DEFAULT_LOGIN_URI + "?query"); Authentication authentication = new KeycloakAuthenticationToken(keycloakAccount, true, authorities); filter.successfulAuthentication(request, response, chain, authentication); verify(successHandler).onAuthenticationSuccess(eq(request), eq(response), eq(authentication)); verify(chain, never()).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); }
Example #8
Source File: SimpleHttpFacadeTest.java From keycloak with Apache License 2.0 | 5 votes |
@Before public void setup() { SecurityContext springSecurityContext = SecurityContextHolder.createEmptyContext(); SecurityContextHolder.setContext(springSecurityContext); Set<String> roles = Sets.newSet("user"); Principal principal = mock(Principal.class); RefreshableKeycloakSecurityContext keycloakSecurityContext = mock(RefreshableKeycloakSecurityContext.class); KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, keycloakSecurityContext); KeycloakAuthenticationToken token = new KeycloakAuthenticationToken(account, false); springSecurityContext.setAuthentication(token); }
Example #9
Source File: KeycloakAuthenticationProviderTest.java From keycloak with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { Principal principal = mock(Principal.class); RefreshableKeycloakSecurityContext securityContext = mock(RefreshableKeycloakSecurityContext.class); KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, securityContext); token = new KeycloakAuthenticationToken(account, false); interactiveToken = new KeycloakAuthenticationToken(account, true); }
Example #10
Source File: KeycloakLogoutHandlerTest.java From keycloak with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); keycloakAuthenticationToken = mock(KeycloakAuthenticationToken.class); keycloakLogoutHandler = new KeycloakLogoutHandler(adapterDeploymentContext); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); when(adapterDeploymentContext.resolveDeployment(any(HttpFacade.class))).thenReturn(keycloakDeployment); when(keycloakAuthenticationToken.getAccount()).thenReturn(keycloakAccount); when(keycloakAccount.getKeycloakSecurityContext()).thenReturn(session); }
Example #11
Source File: SpringSecurityRequestAuthenticatorTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void testCompleteBearerAuthentication() throws Exception { authenticator.completeBearerAuthentication(principal, "foo"); verify(request).setAttribute(eq(KeycloakSecurityContext.class.getName()), eq(refreshableKeycloakSecurityContext)); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); assertTrue(KeycloakAuthenticationToken.class.isAssignableFrom(SecurityContextHolder.getContext().getAuthentication().getClass())); }
Example #12
Source File: SimpleHttpFacade.java From keycloak with Apache License 2.0 | 5 votes |
@Override public KeycloakSecurityContext getSecurityContext() { SecurityContext context = SecurityContextHolder.getContext(); if (context != null && context.getAuthentication() != null) { KeycloakAuthenticationToken authentication = (KeycloakAuthenticationToken) context.getAuthentication(); return authentication.getAccount().getKeycloakSecurityContext(); } return null; }
Example #13
Source File: SpringSecurityRequestAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
@Override protected void completeBearerAuthentication(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal, String method) { RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext(); Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext); final KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, securityContext); logger.debug("Completing bearer authentication. Bearer roles: {} ",roles); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(new KeycloakAuthenticationToken(account, false)); SecurityContextHolder.setContext(context); request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext); }
Example #14
Source File: KeycloakDirectAccessGrantAuthenticationProvider.java From teiid-spring-boot with Apache License 2.0 | 5 votes |
protected Authentication postTokenVerification(String tokenString, AccessToken token) { RefreshableKeycloakSecurityContext skSession = new RefreshableKeycloakSecurityContext(deployment, null, tokenString, token, null, null, null); String principalName = AdapterUtils.getPrincipalName(deployment, token); final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(principalName, skSession); final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(skSession); final KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, skSession); KeycloakAuthenticationToken newAuth = new KeycloakAuthenticationToken(account, false); //call to the super logic to map authorities return super.authenticate(newAuth); }
Example #15
Source File: KeycloakLogoutHandler.java From keycloak with Apache License 2.0 | 5 votes |
protected void handleSingleSignOut(HttpServletRequest request, HttpServletResponse response, KeycloakAuthenticationToken authenticationToken) { HttpFacade facade = new SimpleHttpFacade(request, response); KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade); adapterTokenStoreFactory.createAdapterTokenStore(deployment, request, response).logout(); RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) authenticationToken.getAccount().getKeycloakSecurityContext(); session.logout(deployment); }
Example #16
Source File: KeycloakLogoutHandler.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { if (authentication == null) { log.warn("Cannot log out without authentication"); return; } else if (!KeycloakAuthenticationToken.class.isAssignableFrom(authentication.getClass())) { log.warn("Cannot log out a non-Keycloak authentication: {}", authentication); return; } handleSingleSignOut(request, response, (KeycloakAuthenticationToken) authentication); }
Example #17
Source File: KeycloakUserDetailsAuthenticationProvider.java From smartling-keycloak-extras with Apache License 2.0 | 5 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) super.authenticate(authentication); String username; UserDetails userDetails; if (token == null) { return null; } username = this.resolveUsername(token); userDetails = userDetailsService.loadUserByUsername(username); return new KeycloakUserDetailsAuthenticationToken(userDetails, token.getAccount(), token.getAuthorities()); }
Example #18
Source File: PortalController.java From keycloak-user-migration-provider with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/info/user", method = RequestMethod.GET) public String handlerUserInfoRequest(Model model) { KeycloakAuthenticationToken authentication = (KeycloakAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); IDToken token = authentication.getAccount().getKeycloakSecurityContext().getIdToken(); model.addAttribute("token", token); model.addAttribute("claims", token.getOtherClaims()); return "info"; }
Example #19
Source File: KeycloakAuthenticationProvider.java From keycloak with Apache License 2.0 | 4 votes |
@Override public boolean supports(Class<?> aClass) { return KeycloakAuthenticationToken.class.isAssignableFrom(aClass); }
Example #20
Source File: KeycloakUserDetailsAuthenticationProviderTest.java From smartling-keycloak-extras with Apache License 2.0 | 4 votes |
@Test public void testSupports() throws Exception { assertTrue(provider.supports(KeycloakAuthenticationToken.class)); assertTrue(provider.supports(KeycloakUserDetailsAuthenticationToken.class)); assertFalse(provider.supports(UsernamePasswordAuthenticationToken.class)); }
Example #21
Source File: DirectAccessGrantUserDetailsAuthenticationProviderTest.java From smartling-keycloak-extras with Apache License 2.0 | 4 votes |
@Ignore @Test public void testResolveUsername() throws Exception { KeycloakAuthenticationToken authentication = (KeycloakAuthenticationToken) provider.authenticate(token); assertEquals(AppConfig.KNOWN_EMAIL, provider.resolveUsername(authentication)); }
Example #22
Source File: KeycloakAuthenticationProviderTest.java From keycloak with Apache License 2.0 | 4 votes |
@Test public void testSupports() throws Exception { assertTrue(provider.supports(KeycloakAuthenticationToken.class)); assertFalse(provider.supports(PreAuthenticatedAuthenticationToken.class)); }
Example #23
Source File: DirectAccessGrantAuthenticationProviderTest.java From smartling-keycloak-extras with Apache License 2.0 | 4 votes |
@Test public void testSupports() throws Exception { assertTrue(directAccessGrantAuthenticationProvider.supports(DirectAccessGrantToken.class)); assertTrue(directAccessGrantAuthenticationProvider.supports(UsernamePasswordAuthenticationToken.class)); assertFalse(directAccessGrantAuthenticationProvider.supports(KeycloakAuthenticationToken.class)); }
Example #24
Source File: DirectAccessGrantUserDetailsAuthenticationProvider.java From smartling-keycloak-extras with Apache License 2.0 | 3 votes |
/** * Returns the username from the given {@link KeycloakAuthenticationToken}. By default, this method * resolves the username from the token's {@link KeycloakPrincipal}'s name. This value can be controlled * via <code>keycloak.json</code>'s * <a href="http://docs.jboss.org/keycloak/docs/1.2.0.CR1/userguide/html/ch08.html#adapter-config"><code>principal-attribute</code></a>. * For more fine-grained username resolution, override this method. * * @param token the {@link KeycloakAuthenticationToken} from which to extract the username * * @return the username to use when loading a user from the this provider's {@link UserDetailsService}. * * @see UserDetailsService#loadUserByUsername * @see OidcKeycloakAccount#getPrincipal */ protected String resolveUsername(KeycloakAuthenticationToken token) { Assert.notNull(token, "KeycloakAuthenticationToken required"); Assert.notNull(token.getAccount(), "KeycloakAuthenticationToken.getAccount() cannot be return null"); OidcKeycloakAccount account = token.getAccount(); Principal principal = account.getPrincipal(); return principal.getName(); }
Example #25
Source File: KeycloakUserDetailsAuthenticationProvider.java From smartling-keycloak-extras with Apache License 2.0 | 3 votes |
/** * Returns the username from the given {@link KeycloakAuthenticationToken}. By default, this method * resolves the username from the token's {@link KeycloakPrincipal}'s name. This value can be controlled * via <code>keycloak.json</code>'s * <a href="http://docs.jboss.org/keycloak/docs/1.2.0.CR1/userguide/html/ch08.html#adapter-config"><code>principal-attribute</code></a>. * For more fine-grained username resolution, override this method. * * @param token the {@link KeycloakAuthenticationToken} from which to extract the username * * @return the username to use when loading a user from the this provider's {@link UserDetailsService}. * * @see UserDetailsService#loadUserByUsername * @see OidcKeycloakAccount#getPrincipal */ protected String resolveUsername(KeycloakAuthenticationToken token) { Assert.notNull(token, "KeycloakAuthenticationToken required"); Assert.notNull(token.getAccount(), "KeycloakAuthenticationToken.getAccount() cannot be return null"); OidcKeycloakAccount account = token.getAccount(); Principal principal = account.getPrincipal(); return principal.getName(); }