/** * {@inheritDoc} */ @Override protected void extractUserData(ObjectNode jsonUser, ExternalUserVO userVO) throws AuthenticationServiceException { assertFieldsExist(jsonUser, JSON_PARAM_LOGIN, JSON_PARAM_EMAIL, JSON_PARAM_LAST_NAME, JSON_PARAM_FIRST_NAME); userVO.setExternalUserName(jsonUser.get(JSON_PARAM_LOGIN).asText()); userVO.setEmail(jsonUser.get(JSON_PARAM_EMAIL).asText()); userVO.setLastName(jsonUser.get(JSON_PARAM_LAST_NAME).asText()); userVO.setFirstName(jsonUser.get(JSON_PARAM_FIRST_NAME).asText()); if (jsonUser.has(JSON_PARAM_LANG)) { String lang = jsonUser.get(JSON_PARAM_LANG).asText(); Locale locale = new Locale(lang); userVO.setDefaultLanguage(locale); } }
@Override public String extract(String header) { if (header == null || "".equals(header)) { throw new AuthenticationServiceException( "Authorization header cannot be blank!" ); } if (header.length() < HEADER_PREFIX.length()) { throw new AuthenticationServiceException( "Invalid authorization header size." ); } return header.substring(HEADER_PREFIX.length(), header.length()); }
private JwtClaims getJwtClaims(String token) { HttpsJwks httpsJkws = new HttpsJwks(jwksBaseURL); HttpsJwksVerificationKeyResolver httpsJwksKeyResolver = new HttpsJwksVerificationKeyResolver(httpsJkws); JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(3600) .setExpectedIssuer(jwksIssuer) // whom the JWT needs to have been issued by .setExpectedAudience(jwksAudience).setVerificationKeyResolver(httpsJwksKeyResolver).build(); try { // Validate the JWT and process it to the Claims JwtClaims jwtClaims = jwtConsumer.processToClaims(token); return jwtClaims; } catch (InvalidJwtException e) { // Anyway here throws the exception , so no need to log the error. // log the error if required from where this function invokes // logger.error("Invalid JWT! " + e); throw new AuthenticationServiceException("Invalid Token"); } }
/** * Implementation of an abstract method defined in the base class. The * retrieveUser() method is called by authenticate() method of the base * class. The latter is called by the AuthenticationManager. */ @Override protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails details; try { details = this.getUserDetailsService().loadUserByUsername(username); authentication.setDetails(details); } catch (DataAccessException repositoryProblem) { throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } if (details == null) { throw new AuthenticationServiceException( "UserDetailsService returned null, which is an interface contract violation"); } return details; }
@NotNull public static Map<String, Object> verifiedToken(String token, String publicKey) { Jwt jwt = JwtHelper.decode(token); // Currently not sure how we should handle this because we have multiple // CF instances. We would need to have a central file for all UAA // instances // verifySignature(jwt, publicKey); Map<String, Object> tokenObj = tryExtractToken(jwt); if (tokenObj == null) { throw new AuthenticationServiceException("Error parsing JWT token/extracting claims"); } verifyExpiration(tokenObj); return tokenObj; }
public Authentication authenticate(final Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; } UaaRelyingPartyToken auth = (UaaRelyingPartyToken) authentication; Map<String, Object> tokenObj = UaaFilterUtils.verifiedToken(auth.getToken(), publicKey); UaaUserDetails userDetails = new UaaUserDetails(); userDetails.setUsername(tokenObj.get(Properties.USER_NAME).toString()); userDetails.setGrantedAuthorities(scopeToGrantedAuthority((List<String>) tokenObj.get(Properties.SCOPE))); if (!userDetails.isEnabled()) { throw new AuthenticationServiceException("User is disabled"); } return createSuccessfulAuthentication(userDetails); }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!HttpMethod.POST.name().equals(request.getMethod()) || !WebUtil.isAjax(request)) { if(logger.isDebugEnabled()) { logger.debug("Authentication method not supported. Request method: " + request.getMethod()); } throw new AuthMethodNotSupportedException("Authentication method not supported"); } LoginRequest loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class); if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) { throw new AuthenticationServiceException("Username or Password not provided"); } UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()); return this.getAuthenticationManager().authenticate(token); }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!HttpMethod.POST.name().equals(request.getMethod()) || !WebUtil.isAjax(request)) { if (logger.isDebugEnabled()) { logger.debug("Authentication method not supported. Request method: " + request.getMethod()); } throw new AuthMethodNotSupportedException("Authentication method not supported"); } LoginRequest loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class); if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) { throw new AuthenticationServiceException("Username or Password not provided"); } AdminUserAuthenticationToken token = new AdminUserAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()); return this.getAuthenticationManager().authenticate(token); }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!HttpMethod.POST.name().equals(request.getMethod())) { if (logger.isDebugEnabled()) { logger.debug("Authentication method not supported. Request method: " + request.getMethod()); } throw new AuthMethodNotSupportedException("Authentication method not supported"); } RefreshTokenRequest refreshTokenRequest; try { refreshTokenRequest = objectMapper.readValue(request.getReader(), RefreshTokenRequest.class); } catch (Exception e) { throw new AuthenticationServiceException("Invalid refresh token request payload"); } if (StringUtils.isBlank(refreshTokenRequest.getRefreshToken())) { throw new AuthenticationServiceException("Refresh token is not provided"); } RawAccessJwtToken token = new RawAccessJwtToken(refreshTokenRequest.getRefreshToken()); return this.getAuthenticationManager().authenticate(new RefreshAuthenticationToken(token)); }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { if (!request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } final String username = obtainUsername(request); final String password = obtainPassword(request); final String receivedOtp = obtainOneTimeToken(request); final OneTimePasswordAuthenticationToken authRequest = new OneTimePasswordAuthenticationToken(username, password, receivedOtp); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); return this.getAuthenticationManager().authenticate(authRequest); }
/** * Retrieve user. * * @param username * the username * @param authentication * the authentication * @return the user details * @throws AuthenticationException * the authentication exception */ @Override protected UserDetails retrieveUser(final String username, final UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails loadedUser; if (username == null || username.trim().length() < 1) { throw new AuthenticationServiceException(authenticationServiceExcep); } try { System.out.println(authenticationService); loadedUser = authenticationService.loadUserByUsername(username); } catch (final DataAccessException repositoryProblem) { throw new AuthenticationServiceException(authenticationServiceExcep); } if (loadedUser == null) { throw new AuthenticationServiceException(badCredentialExcep); } return loadedUser; }
/** * {@inheritDoc} */ @Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { String password = authentication.getCredentials().toString(); UserDetails existingUser; try { ResponseEntity<Collection<? extends GrantedAuthority>> authenticationResponse = authenticationDelegate.authenticate(username, password.toCharArray()); if (authenticationResponse.getStatusCode().value() == 401) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } existingUser = new User(username, password, authenticationResponse.getBody()); } catch (Exception ex) { logger.error(ex.getMessage(), ex); throw new AuthenticationServiceException(ex.getMessage(), ex); } return existingUser; }
@Override public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx) throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { checkEnteredCredentials(connEnv, authnCtx); MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true); UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); if (checkCredentials(principal, authnCtx, connEnv)) { recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, authnCtx.getEnteredCredential(), principal.getAuthorities()); return token; } else { recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch"); throw new BadCredentialsException("web.security.provider.invalid"); } }
@Override public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx) throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { checkEnteredCredentials(connEnv, authnCtx); MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false); UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); if (checkCredentials(principal, authnCtx, connEnv)) { return userType; } else { recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch"); throw new BadCredentialsException("web.security.provider.invalid"); } }
protected String getDecryptedValue(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString) { String decryptedPassword; if (protectedString.getEncryptedDataType() != null) { try { decryptedPassword = protector.decryptString(protectedString); } catch (EncryptionException e) { recordAuthenticationFailure(principal, connEnv, "error decrypting password: "+e.getMessage()); throw new AuthenticationServiceException("web.security.provider.unavailable", e); } } else { LOGGER.warn("Authenticating user based on clear value. Please check objects, " + "this should not happen. Protected string should be encrypted."); decryptedPassword = protectedString.getClearValue(); } return decryptedPassword; }
private String getPassword(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString) { String decryptedPassword; if (protectedString.getEncryptedDataType() != null) { try { decryptedPassword = protector.decryptString(protectedString); } catch (EncryptionException e) { recordAuthenticationFailure(principal, connEnv, "error decrypting password: "+e.getMessage()); throw new AuthenticationServiceException("web.security.provider.unavailable", e); } } else { LOGGER.warn("Authenticating user based on clear value. Please check objects, " + "this should not happen. Protected string should be encrypted."); decryptedPassword = protectedString.getClearValue(); } return decryptedPassword; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String enteredUsername = (String) authentication.getPrincipal(); LOGGER.trace("Authenticating username '{}'", enteredUsername); ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_USER_URI); Authentication token; if (authentication instanceof UsernamePasswordAuthenticationToken) { String enteredPassword = (String) authentication.getCredentials(); token = passwordAuthenticationEvaluator.authenticate(connEnv, new PasswordAuthenticationContext(enteredUsername, enteredPassword)); } else if (authentication instanceof PreAuthenticatedAuthenticationToken) { token = passwordAuthenticationEvaluator.authenticateUserPreAuthenticated(connEnv, enteredUsername); } else { LOGGER.error("Unsupported authentication {}", authentication); throw new AuthenticationServiceException("web.security.provider.unavailable"); } MidPointPrincipal principal = (MidPointPrincipal)token.getPrincipal(); LOGGER.debug("User '{}' authenticated ({}), authorities: {}", authentication.getPrincipal(), authentication.getClass().getSimpleName(), principal.getAuthorities()); return token; }
@SuppressWarnings("ConstantConditions") @Test public void shouldFailToAuthenticateUsingJWKIfMissingProvider() throws Exception { Jwk jwk = mock(Jwk.class); JwkProvider jwkProvider = null; KeyPair keyPair = RSAKeyPair(); when(jwk.getPublicKey()).thenReturn(keyPair.getPublic()); JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "issuer", "audience"); Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id"); String token = JWT.create() .withAudience("audience") .withIssuer("issuer") .withHeader(keyIdHeader) .sign(Algorithm.RSA256((RSAKey) keyPair.getPrivate())); Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token); exception.expect(AuthenticationServiceException.class); exception.expectMessage("Missing jwk provider"); provider.authenticate(authentication); }
@SuppressWarnings("unchecked") @Test public void shouldFailToAuthenticateUsingJWKIfKeyIdDoesNotMatch() throws Exception { JwkProvider jwkProvider = mock(JwkProvider.class); KeyPair keyPair = RSAKeyPair(); when(jwkProvider.get(eq("key-id"))).thenThrow(SigningKeyNotFoundException.class); JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "issuer", "audience"); Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id"); String token = JWT.create() .withAudience("some") .withIssuer("issuer") .withHeader(keyIdHeader) .sign(Algorithm.RSA256((RSAKey) keyPair.getPrivate())); Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token); exception.expect(AuthenticationServiceException.class); exception.expectMessage("Could not retrieve jwks from issuer"); exception.expectCause(Matchers.<Throwable>instanceOf(SigningKeyNotFoundException.class)); provider.authenticate(authentication); }
@SuppressWarnings("unchecked") @Test public void shouldFailToAuthenticateUsingJWKIfPublicKeyIsInvalid() throws Exception { Jwk jwk = mock(Jwk.class); JwkProvider jwkProvider = mock(JwkProvider.class); KeyPair keyPair = RSAKeyPair(); when(jwkProvider.get(eq("key-id"))).thenReturn(jwk); when(jwk.getPublicKey()).thenThrow(InvalidPublicKeyException.class); JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "issuer", "audience"); Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id"); String token = JWT.create() .withAudience("some") .withIssuer("issuer") .withHeader(keyIdHeader) .sign(Algorithm.RSA256((RSAKey) keyPair.getPrivate())); Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token); exception.expect(AuthenticationServiceException.class); exception.expectMessage("Could not retrieve public key from issuer"); exception.expectCause(Matchers.<Throwable>instanceOf(InvalidPublicKeyException.class)); provider.authenticate(authentication); }
@SuppressWarnings("unchecked") @Test public void shouldFailToAuthenticateUsingJWKIfKeyIdCannotBeObtained() throws Exception { JwkProvider jwkProvider = mock(JwkProvider.class); KeyPair keyPair = RSAKeyPair(); when(jwkProvider.get(eq("key-id"))).thenThrow(JwkException.class); JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "issuer", "audience"); Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id"); String token = JWT.create() .withAudience("some") .withIssuer("issuer") .withHeader(keyIdHeader) .sign(Algorithm.RSA256((RSAKey) keyPair.getPrivate())); Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token); exception.expect(AuthenticationServiceException.class); exception.expectMessage("Cannot authenticate with jwt"); exception.expectCause(Matchers.<Throwable>instanceOf(JwkException.class)); provider.authenticate(authentication); }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!HttpMethod.POST.name().equals(request.getMethod())) { if(log.isDebugEnabled()) { log.debug("Authentication method not supported. Request method: " + request.getMethod()); } throw new AuthMethodNotSupportedException("Authentication method not supported"); } RefreshTokenRequest refreshTokenRequest; try { refreshTokenRequest = objectMapper.readValue(request.getReader(), RefreshTokenRequest.class); } catch (Exception e) { throw new AuthenticationServiceException("Invalid refresh token request payload"); } if (StringUtils.isBlank(refreshTokenRequest.getRefreshToken())) { throw new AuthenticationServiceException("Refresh token is not provided"); } RawAccessJwtToken token = new RawAccessJwtToken(refreshTokenRequest.getRefreshToken()); return this.getAuthenticationManager().authenticate(new RefreshAuthenticationToken(token)); }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } String username = obtainUsername(request); String password = obtainPassword(request); if (StringUtils.isBlank(username)) { throw new BadCredentialsException("A blank username is not allowed."); } if (password == null) { password = StringUtils.EMPTY; } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( username, password); // Allow subclasses to set the "details" property setDetails(request, authRequest); return getAuthResult(authRequest); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UserDetails details = retrieveAndAuthenticateUserDetails(authentication); if (details == null) { return null; } Long userId = details.getUserId(); if (userId == null) { return null; } // do additional authentication checks doAdditionalAuthenticationChecks(userId); User user = ServiceLocator.findService(UserManagement.class).findUserByUserId(userId); if (user == null) { throw new AuthenticationServiceException( "User was not found for authenticated user with ID: " + details.getUserId()); } Authentication authResult = createSuccessAuthentication(details, authentication); return authResult; }
@Override public Authentication authenticate(Authentication auth) throws AuthenticationException { String username = auth.getName(); String password = (String) auth.getCredentials(); try { if (LoginProvider.checkCredantials(username, password)) { User user = ConfigLoader.getInstance().getUsers().queryForId(username.toLowerCase().trim()); if (user != null && user.isEnabled()) { List<GrantedAuthority> grantedAuths = new ArrayList<>(); for(Role r : user.getRoles()) { grantedAuths.add(new SimpleGrantedAuthority(r.getName())); } Authentication ret = new UsernamePasswordAuthenticationToken(username, password, grantedAuths); return ret; } } } catch (NoSuchAlgorithmException | SQLException | IOException e) { System.err.println("ERROR: Unable to check credentials: " + e.getMessage()); e.printStackTrace(); throw new AuthenticationServiceException("Unable to check user credantials.", e); } return null; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UserDetails userDetails; try { userDetails = userService.getUserByApiKey((String)authentication.getPrincipal()); if(userDetails != null) { return new RestAuthenticationToken(authentication.getPrincipal(),authentication.getCredentials(),userDetails); } else { throw new BadCredentialsException("Invalid API Key"); } } catch (Exception e) { throw new AuthenticationServiceException(e.getMessage(), e); } }
@Override public DirContextOperations authenticate(Authentication authentication) { //Spring expects an exception on failed authentication if (authenticators != null && centralConfig.getDescriptor().getSecurity().isLdapEnabled()) { RuntimeException authenticationException = null; for (BindAuthenticator authenticator : authenticators.values()) { DirContextOperations user = null; try { user = authenticator.authenticate(authentication); } catch (RuntimeException e) { authenticationException = e; } if (user != null) { return user; } } if (authenticationException != null) { throw authenticationException; } throw new AuthenticationServiceException(LDAP_SERVICE_MISCONFIGURED); } else { throw new AuthenticationServiceException(NO_LDAP_SERVICE_CONFIGURED); } }
@Override protected SSOUser doAuthenticate( UsernamePasswordAuthRequestInfoAuthenticationToken authRequest, String username, String password) { boolean ok = this.username.equals(username) && this.password.equals(password); if (!ok) { throw new BadCredentialsException("Bad password"); } SSOUser ssoUser; try { ssoUser = new SSOUser(username, buildActionsMap(username), buildPreferences()); } catch (Exception e) { throw new AuthenticationServiceException("Cannot collect action descriptions", e); } return ssoUser; }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!request.isSecure()) { throw new AuthenticationServiceException("Authentication scheme not supported: " + request.getScheme()); } Authentication authentication = super.attemptAuthentication(request, response); if (authentication instanceof VistaAuthenticationToken) { VistaAuthenticationToken vistaAuthenticationToken = (VistaAuthenticationToken) authentication; String requestedDuz = obtainUserDuz(request); if (!vistaAuthenticationToken.getDuz().equals(requestedDuz)) { throw new UserDUZMismatchException("The requested user's DUZ does not match the authenticated user's DUZ."); } } return authentication; }
@Test public void testAttemptNonSecureAuthentication() throws Exception { request.addParameter(CprsSsoVistaAuthenticationFilter.SERVER_KEY, "example.org"); request.addParameter(CprsSsoVistaAuthenticationFilter.PORT_KEY, "9060"); request.addParameter(CprsSsoVistaAuthenticationFilter.USER_DUZ_KEY, "1089"); request.addParameter(CprsSsoVistaAuthenticationFilter.APP_HANDLE_KEY, "~2xwbccw58-43436_1"); request.setRemoteAddr("10.0.1.34"); request.setRemoteHost("www.example.org"); request.setRequestURI(f.getFilterProcessesUrl()); request.setMethod("GET"); request.setScheme("http"); request.setSecure(false); f.doFilter(request, response, filterChain); verify(mockFailureHandler).onAuthenticationFailure(eq(request), eq(response), any(AuthenticationServiceException.class)); }
private String retrieveSecurityInfo(final CombinedTokenInformation combinedTokenInformation) { final String securityInfo; if (securityInfoRetriever == null) { securityInfo = null; } else { try { securityInfo = securityInfoRetriever.getSecurityInfo(combinedTokenInformation.getUser()); } catch (final RuntimeException e) { throw new AuthenticationServiceException("Could not retrieve security info", e); } if (null == securityInfo) { throw new AuthenticationServiceException("Could not retrieve security info"); } } return securityInfo; }
@Override public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (!StringUtils.isEmpty(request.getParameter("error"))) { throw new AuthenticationServiceException("The SSO page returned an error"); } final DateTime expiry; try { expiry = new DateTime(Long.parseLong(request.getParameter("expiry"))); } catch (final NumberFormatException ignored) { throw new BadCredentialsException("Invalid combined SSO token"); } final AuthenticationToken<E, TokenType.Simple> token = new AuthenticationToken<>( entityType, TokenType.Simple.INSTANCE, request.getParameter("type"), expiry, request.getParameter("id"), request.getParameter("secret"), null ); return getAuthenticationManager().authenticate(new HodTokenAuthentication<>(token)); }
@Override public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) { if (!request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } final UserPasswordDto userData; try { final ObjectMapper mapper = new ObjectMapper(); userData = mapper.readValue(request.getInputStream(), UserPasswordDto.class); } catch (final IOException e) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userData.getUsername(), userData.getPassword()); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); }
/** * Attempt to authenticate request - basically just pass over to another method to authenticate request headers */ @Override public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String token = null; if (null != request.getCookies()) { for (final Cookie cookie : request.getCookies()) { if (COOKIE_SECURITY_TOKEN.equals(cookie.getName())) { token = cookie.getValue(); } } } if (token == null) { logger.info("No token found request:" + request.getRequestURI()); throw new AuthenticationServiceException(MessageFormat.format("Error | {0}", "No Token")); } logger.info("token found:" + token + " request:" + request.getRequestURI()); final AbstractAuthenticationToken userAuthenticationToken = authUserByToken(token); if (userAuthenticationToken == null) { throw new AuthenticationServiceException(MessageFormat.format("Error | {0}", "Bad Token")); } return userAuthenticationToken; }
/** * Find tickets. * @param path The path. * @param key The key. * @return The ticket. */ private Ticket findTicket(String path, String key) { try { if (LOG.isDebugEnabled()) { LOG.debug("authenticating ticket " + key + " for resource at path " + path); } Item item = findItem(path); Ticket ticket = contentDao.getTicket(item, key); if (ticket == null) { return null; } if (ticket.hasTimedOut()) { if (LOG.isDebugEnabled()) { LOG.debug("removing timed out ticket " + ticket.getKey()); } contentDao.removeTicket(item, ticket); return null; } return ticket; } catch (DataAccessException e) { throw new AuthenticationServiceException(e.getMessage(), e); } }