org.springframework.security.authentication.AbstractAuthenticationToken Java Examples
The following examples show how to use
org.springframework.security.authentication.AbstractAuthenticationToken.
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: PhonePasswordTokenGranter.java From spring-cloud-shop with MIT License | 8 votes |
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters()); String username = parameters.get("phone"); String password = parameters.get("password"); // Protect from downstream leaks of password parameters.remove("password"); Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password); ((AbstractAuthenticationToken) userAuth).setDetails(parameters); try { userAuth = authenticationManager.authenticate(userAuth); } catch (AccountStatusException | BadCredentialsException ase) { //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage()); } // If the username/password are wrong the spec says we should send 400/invalid grant if (userAuth == null || !userAuth.isAuthenticated()) { throw new InvalidGrantException("Could not authenticate user: " + username); } return new OAuth2Authentication(getRequestFactory().createOAuth2Request(client, tokenRequest), userAuth); }
Example #2
Source File: MobileTokenAuthenticationFilter.java From Taroco with Apache License 2.0 | 6 votes |
@Override public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) { throw new AuthenticationServiceException( "Authentication method not supported: " + request.getMethod()); } AbstractAuthenticationToken authRequest; String principal; String credentials; // 手机验证码登陆 principal = obtainParameter(request, SPRING_SECURITY_RESTFUL_PHONE_KEY); credentials = obtainParameter(request, SPRING_SECURITY_RESTFUL_VERIFY_CODE_KEY); principal = principal.trim(); authRequest = new MobileTokenAuthenticationToken(principal, credentials); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); }
Example #3
Source File: AbstractSecureContentFilter.java From api-layer with Eclipse Public License 2.0 | 6 votes |
/** * Extracts the token from the request and use the authentication manager to perform authentication. * Then set the currently authenticated principal and call the next filter in the chain. * * @param request the http request * @param response the http response * @param filterChain the filter chain * @throws ServletException a general exception * @throws IOException a IO exception */ @Override protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { Optional<AbstractAuthenticationToken> authenticationToken = extractContent(request); if (authenticationToken.isPresent()) { try { Authentication authentication = authenticationManager.authenticate(authenticationToken.get()); SecurityContextHolder.getContext().setAuthentication(authentication); filterChain.doFilter(request, response); } catch (AuthenticationException authenticationException) { failureHandler.onAuthenticationFailure(request, response, authenticationException); } catch (RuntimeException e) { resourceAccessExceptionHandler.handleException(request, response, e); } } else { filterChain.doFilter(request, response); } }
Example #4
Source File: TokenAuthenticationConverterTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 6 votes |
@Test public void extractCustomAuthoritiesWithScopes() { TokenAuthenticationConverter tokenConverterCustom = new TokenAuthenticationConverter( new MyAuthoritiesExtractor(xsAppName, "cost-center", "country")); Jwt jwt = new JwtGenerator() .addScopes(scopeAdmin) .addAttribute("cost-center", new String[] { "0815" }) .addAttribute("country", new String[] { "DE", "IL" }) .getToken(); AbstractAuthenticationToken authenticationToken = tokenConverterCustom.convert(jwt); assertThat(authenticationToken.getAuthorities().size(), is(4)); assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("ATTR:COST-CENTER=0815"))); assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("ATTR:COUNTRY=DE"))); assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("ATTR:COUNTRY=IL"))); assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeAdmin))); }
Example #5
Source File: SmsTokenGranter.java From cola with MIT License | 6 votes |
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters()); String phoneNumber = parameters.get("phoneNumber"); String credential = parameters.get("credential"); String token = parameters.get("token"); Authentication userAuth = new SmsAuthenticationToken(phoneNumber, credential, token); ((AbstractAuthenticationToken) userAuth).setDetails(parameters); try { userAuth = authenticationManager.authenticate(userAuth); } catch (AccountStatusException | BadCredentialsException ase) { //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage()); } if (userAuth == null || !userAuth.isAuthenticated()) { throw new InvalidGrantException("Could not authenticate user: " + phoneNumber); } OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); return new OAuth2Authentication(storedOAuth2Request, userAuth); }
Example #6
Source File: AcTokenGranter.java From cola with MIT License | 6 votes |
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters()); String authorizationCode = parameters.get("authorizationCode"); String provider = parameters.get("provider"); Authentication userAuth = new AcAuthenticationToken(authorizationCode, provider); ((AbstractAuthenticationToken) userAuth).setDetails(parameters); try { userAuth = authenticationManager.authenticate(userAuth); } catch (AccountStatusException | BadCredentialsException ase) { //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage()); } if (userAuth == null || !userAuth.isAuthenticated()) { throw new InvalidGrantException("Could not authenticate user: " + authorizationCode); } OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); return new OAuth2Authentication(storedOAuth2Request, userAuth); }
Example #7
Source File: OpenIdTokenGranter.java From cola with MIT License | 6 votes |
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters()); String openId = parameters.get("openid"); String provider = parameters.get("provider"); Authentication userAuth = new OpenIdAuthenticationToken(openId,provider); ((AbstractAuthenticationToken) userAuth).setDetails(parameters); try { userAuth = authenticationManager.authenticate(userAuth); } catch (AccountStatusException | BadCredentialsException ase) { //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage()); } if (userAuth == null || !userAuth.isAuthenticated()) { throw new InvalidGrantException("Could not authenticate user: " + openId); } OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); return new OAuth2Authentication(storedOAuth2Request, userAuth); }
Example #8
Source File: TokenAuthenticationConverterTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 6 votes |
@Test public void authoritiesHaveLocalScopesWithoutAppIdPrefix() { String scopeWithNamespace = xsAppName + ".iot.Delete"; String scopeWithOtherAppId = "anyAppId!t200." + xsAppName + ".Delete"; Jwt jwt = new JwtGenerator() .addScopes(xsAppName + "." + scopeAdmin, scopeRead, scopeWithNamespace, scopeWithOtherAppId) .getToken(); AbstractAuthenticationToken authenticationToken = tokenConverterLocalScopesOnly.convert(jwt); assertThat(authenticationToken.getAuthorities().size(), is(3)); assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeAdmin))); assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("iot.Delete"))); assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("Read"))); }
Example #9
Source File: DefaultUserService.java From attic-rave with Apache License 2.0 | 6 votes |
private SecurityContext createContext(final User user) { SecurityContext securityContext = new SecurityContextImpl(); securityContext.setAuthentication(new AbstractAuthenticationToken(user.getAuthorities()) { private static final long serialVersionUID = 1L; @Override public Object getCredentials() { return "N/A"; } @Override public Object getPrincipal() { return user; } @Override public boolean isAuthenticated() { return true; } }); return securityContext; }
Example #10
Source File: DefaultUserServiceTest.java From attic-rave with Apache License 2.0 | 6 votes |
@Test public void getAuthenticatedUser_validUser() { final User authUser = new UserImpl(USER_ID); AbstractAuthenticationToken auth = createNiceMock(AbstractAuthenticationToken.class); expect(auth.getPrincipal()).andReturn(authUser).anyTimes(); replay(auth); SecurityContext context = new SecurityContextImpl(); context.setAuthentication(auth); SecurityContextHolder.setContext(context); User result = service.getAuthenticatedUser(); assertThat(result, is(sameInstance(authUser))); verify(auth); }
Example #11
Source File: RenderServiceIntegrationTest.java From attic-rave with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Before public void setup() throws SQLException { restOperations = EasyMock.createNiceMock(RestOperations.class); EasyMock.expect(restOperations.postForObject(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class), EasyMock.anyObject(Class.class))) .andReturn(VALID_METADATA); EasyMock.replay(restOperations); //Replace the real restOperations instance with a mock -- otherwise the call for gadget metadata would fail since //we don't have a shindig server available to hit. ReflectionTestUtils.setField(metadataRepository, "restOperations", restOperations); //Setup a mock authenticated user final User authUser = new UserImpl(VALID_USER_ID, VALID_USER_NAME); AbstractAuthenticationToken auth = EasyMock.createNiceMock(AbstractAuthenticationToken.class); EasyMock.expect(auth.getPrincipal()).andReturn(authUser).anyTimes(); EasyMock.replay(auth); SecurityContext context = new SecurityContextImpl(); context.setAuthentication(auth); SecurityContextHolder.setContext(context); }
Example #12
Source File: BasicContentFilterTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void extractContentFromRequestWithEmptyRealm() { request.addHeader(HttpHeaders.AUTHORIZATION, "Basic "); Optional<AbstractAuthenticationToken> token = basicContentFilter.extractContent(request); assertFalse(token.isPresent()); }
Example #13
Source File: BasicContentFilterTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void extractContentFromRequestWithIncompleteBasicAuth() { request.addHeader(HttpHeaders.AUTHORIZATION, "Basic dXNlcj11c2Vy"); Optional<AbstractAuthenticationToken> token = basicContentFilter.extractContent(request); assertTrue(token.isPresent()); assertNull(token.get().getPrincipal()); assertNull(token.get().getCredentials()); }
Example #14
Source File: BasicContentFilterTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void extractContentFromRequestWithValidBasicAuth() { request.addHeader(HttpHeaders.AUTHORIZATION, BASIC_AUTH); Optional<AbstractAuthenticationToken> token = basicContentFilter.extractContent(request); assertTrue(token.isPresent()); assertEquals("user", token.get().getPrincipal()); assertEquals("password", token.get().getCredentials().toString()); }
Example #15
Source File: BasicContentFilterTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void extractContentFromRequestWithNonsense() { request.addHeader(HttpHeaders.AUTHORIZATION, "Duck"); Optional<AbstractAuthenticationToken> token = basicContentFilter.extractContent(request); assertFalse(token.isPresent()); }
Example #16
Source File: BasicContentFilterTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void extractContentFromRequestWithNonsenseBasicAuth() { request.addHeader(HttpHeaders.AUTHORIZATION, "Basic dXNlG4m3oFthR0n3syZA=="); Optional<AbstractAuthenticationToken> token = basicContentFilter.extractContent(request); assertTrue(token.isPresent()); assertNull(token.get().getPrincipal()); assertNull(token.get().getCredentials()); }
Example #17
Source File: LoginFailureListener.java From airsonic with GNU General Public License v3.0 | 5 votes |
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof AbstractAuthenticationFailureEvent) { if (event.getSource() instanceof AbstractAuthenticationToken) { AbstractAuthenticationToken token = (AbstractAuthenticationToken) event.getSource(); Object details = token.getDetails(); if (details instanceof WebAuthenticationDetails) { LOG.info("Login failed from [" + ((WebAuthenticationDetails) details).getRemoteAddress() + "]"); } } } }
Example #18
Source File: AbstractAuthenticationFilter.java From WeBASE-Node-Manager with Apache License 2.0 | 5 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { final String header = request.getHeader(TOKEN_HEADER_NAME); if (header == null || !header.startsWith(getHeaderPrefix())) { chain.doFilter(request, response); return; } AbstractAuthenticationToken authRequest = buildAuthentication(header); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); final Authentication authResult; try { authResult = authenticationManager.authenticate(authRequest); } catch (AuthenticationException failed) { String errorMessage = failed.getMessage(); SecurityContextHolder.clearContext(); //response exception NodeMgrTools.responseString(response, errorMessage); return; } SecurityContextHolder.getContext().setAuthentication(authResult); chain.doFilter(request, response); }
Example #19
Source File: ConfigCommands.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
private static Authentication createAuthentication(final String principalName) { return new AbstractAuthenticationToken(null) { private static final long serialVersionUID = -2038812908189509872L; @Override public Object getCredentials() { return ""; } @Override public Object getPrincipal() { return principalName; } }; }
Example #20
Source File: DataFlowClientAutoConfiguration.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
private static Authentication createAuthentication(final String principalName) { return new AbstractAuthenticationToken(null) { private static final long serialVersionUID = -2038812908189509872L; @Override public Object getCredentials() { return ""; } @Override public Object getPrincipal() { return principalName; } }; }
Example #21
Source File: OidcUserManagementAutoConfiguration.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Override public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException { if (authentication instanceof AbstractAuthenticationToken) { final String defaultTenant = "DEFAULT"; final AbstractAuthenticationToken token = (AbstractAuthenticationToken) authentication; token.setDetails(new TenantAwareAuthenticationDetails(defaultTenant, false)); systemSecurityContext.runAsSystemAsTenant(systemManagement::getTenantMetadata, defaultTenant); } super.onAuthenticationSuccess(request, response, authentication); }
Example #22
Source File: DefaultUserServiceTest.java From attic-rave with Apache License 2.0 | 5 votes |
@Test(expected = SecurityException.class) public void getAuthenticatedUser_wrongPrincipalType() { AbstractAuthenticationToken auth = createNiceMock(AbstractAuthenticationToken.class); expect(auth.getPrincipal()).andReturn(USER_ID).anyTimes(); replay(auth); SecurityContext context = new SecurityContextImpl(); SecurityContextHolder.setContext(context); service.getAuthenticatedUser(); verify(auth); }
Example #23
Source File: JobExecutorTokenServiceImpl.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@Override public AbstractAuthenticationToken createToken(JobExecution jobExecution) { return jobExecution .getUser() .map(this::createRunAsUsertoken) .orElseGet(SystemSecurityToken::getInstance); }
Example #24
Source File: SecurityUtils.java From haven-platform with Apache License 2.0 | 5 votes |
/** * Set auth details if it possible * @param authentication * @param details * @return true if update details is success */ public static boolean setDetailsIfPossible(Authentication authentication, Object details) { if(authentication instanceof AbstractAuthenticationToken) { ((AbstractAuthenticationToken)authentication).setDetails(details); return true; } return false; }
Example #25
Source File: CookieContentFilterTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void shouldReturnEmptyIfCookieValueIsEmpty() { Cookie cookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), ""); request.setCookies(cookie); Optional<AbstractAuthenticationToken> content = cookieContentFilter.extractContent(request); assertFalse(content.isPresent()); }
Example #26
Source File: BasicContentFilter.java From api-layer with Eclipse Public License 2.0 | 5 votes |
/** * Extract credentials from the authorization header in the request and decode them * * @param request the http request * @return the decoded credentials */ public Optional<AbstractAuthenticationToken> extractContent(HttpServletRequest request) { return Optional.ofNullable( request.getHeader(HttpHeaders.AUTHORIZATION) ).filter( header -> header.startsWith(ApimlConstants.BASIC_AUTHENTICATION_PREFIX) ).map( header -> header.replaceFirst(ApimlConstants.BASIC_AUTHENTICATION_PREFIX, "").trim() ) .filter(base64Credentials -> !base64Credentials.isEmpty()) .map(this::mapBase64Credentials); }
Example #27
Source File: CookieContentFilter.java From api-layer with Eclipse Public License 2.0 | 5 votes |
/** * Extract the valid JWT token from the cookies * * @param request the http request * @return the {@link TokenAuthentication} object containing username and valid JWT token */ public Optional<AbstractAuthenticationToken> extractContent(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (cookies == null) { return Optional.empty(); } return Arrays.stream(cookies) .filter(cookie -> cookie.getName().equals(authConfigurationProperties.getCookieProperties().getCookieName())) .filter(cookie -> !cookie.getValue().isEmpty()) .findFirst() .map(cookie -> new TokenAuthentication(cookie.getValue())); }
Example #28
Source File: ZosmfAuthenticationProviderTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void testSupports() { ZosmfAuthenticationProvider mock = new ZosmfAuthenticationProvider(null, null); assertTrue(mock.supports(UsernamePasswordAuthenticationToken.class)); assertFalse(mock.supports(Object.class)); assertFalse(mock.supports(AbstractAuthenticationToken.class)); assertFalse(mock.supports(JaasAuthenticationToken.class)); assertFalse(mock.supports(null)); }
Example #29
Source File: LogsearchKRBAuthenticationFilter.java From ambari-logsearch with Apache License 2.0 | 5 votes |
@Override protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { logger.debug("LogsearchKRBAuthenticationFilter private filter"); String userName = getUsernameFromResponse(response); if (StringUtils.isNotEmpty(userName)) { Authentication existingAuth = SecurityContextHolder.getContext() .getAuthentication(); if (existingAuth == null || !existingAuth.isAuthenticated()) { // --------------------------- To Create Logsearch Session-------------------------------------- // if we get the userName from the token then log into Logsearch using the same user final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority(DEFAULT_USER_ROLE)); final UserDetails principal = new User(userName, "", grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken( principal, "", grantedAuths); WebAuthenticationDetails webDetails = new WebAuthenticationDetails( request); ((AbstractAuthenticationToken) finalAuthentication) .setDetails(webDetails); Authentication authentication = this .authenticate(finalAuthentication); authentication = getGrantedAuthority(authentication); SecurityContextHolder.getContext().setAuthentication(authentication); request.getSession(true).setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext()); request.setAttribute("spnegoEnabled", true); logger.info("Logged into Logsearch as = " + userName); filterChain.doFilter(request, response); } else { try { super.doFilter(filterChain, request, response); } catch (Exception e) { logger.error("Error LogsearchKRBAuthenticationFilter : " + e.getMessage()); } } } else { filterChain.doFilter(request, response); } }
Example #30
Source File: LogsearchTrustedProxyFilter.java From ambari-logsearch with Apache License 2.0 | 5 votes |
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String doAsUserName = request.getParameter("doAs"); final List<GrantedAuthority> authorities = RoleDao.createDefaultAuthorities(); final UserDetails principal = new User(doAsUserName, "", authorities); final AbstractAuthenticationToken finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", authorities); WebAuthenticationDetails webDetails = new WebAuthenticationDetails(request); finalAuthentication.setDetails(webDetails); SecurityContextHolder.getContext().setAuthentication(finalAuthentication); logger.info("Logged into Log Search User as doAsUser = {}", doAsUserName); return finalAuthentication; }