@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { try { Authentication userAuth = null; User user = extensionGrantProvider.grant(convert(tokenRequest)); if (user != null) { userAuth = new UsernamePasswordAuthenticationToken(user, "", AuthorityUtils.NO_AUTHORITIES); if (extensionGrant.isCreateUser()) { Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters()); parameters.put(RepositoryProviderUtils.SOURCE, extensionGrant.getIdentityProvider()); ((AbstractAuthenticationToken) userAuth).setDetails(parameters); eventPublisher.publishAuthenticationSuccess(userAuth); } } OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); return new OAuth2Authentication(storedOAuth2Request, userAuth); } catch (InvalidGrantException e) { throw new org.springframework.security.oauth2.common.exceptions.InvalidGrantException(e.getMessage(), e); } }
/** * {@inheritDoc} */ @Override protected Authentication createSuccessAuthentication(UserDetails details, Authentication authentication) { if (details == null || authentication == null) { return null; } AbstractAuthenticationToken auth = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { auth = new UsernamePasswordAuthenticationToken(details, authentication.getCredentials(), details.getAuthorities()); } else if (authentication instanceof ConfluenceAuthenticationToken) { auth = new ConfluenceAuthenticationToken(details, (String) authentication.getCredentials(), details.getAuthorities()); } if (auth != null) { auth.setDetails(authentication.getDetails()); } return auth; }
/** * JAVADOC Method Level Comments * * @throws Exception JAVADOC. */ @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); interceptor = new CurrentUserChannelInterceptor(systemUserService, userAccessor); if (null == SecurityContextHolder.getContext()) { SecurityContextHolder.setContext(new SecurityContextImpl()); } SecurityContext context = SecurityContextHolder.getContext(); user = new User(); user.setName("user"); AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, null); authToken.setDetails("pipipi"); context.setAuthentication(authToken); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // get username and password String username = (authentication.getPrincipal() == null) ? "" : authentication.getName(); String password = (authentication.getCredentials() == null) ? "" : authentication.getCredentials().toString(); // check credentials if (userService.checkCredentials(username, password)) { // init return value AbstractAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>()); // set user object authenticationToken.setDetails(userService.getUserByUsername(username)); // return user details return authenticationToken; } // indicate invalid credentials throw new InternalAuthenticationServiceException("Unable to authenticate"); }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String apiKeyValue = decodeParameterValue(request, API_KEY_PARAMETER_NAME); logger.debug("attemptAuthentication " + apiKeyValue); AbstractAuthenticationToken authRequest = createAuthenticationToken( apiKeyValue, new RestCredentials()); // Allow subclasses to set the "details" property setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); }
@Override @Transactional public void refreshUserContextIfActive(String userName) { LOGGER.info("Refreshing context for user: {}", userName); MotechUser user = motechUsersDao.findByUserName(userName); Collection<HttpSession> sessions = sessionHandler.getAllSessions(); for (HttpSession session : sessions) { SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT"); if (context != null) { Authentication authentication = context.getAuthentication(); AbstractAuthenticationToken token; User userInSession = (User) authentication.getPrincipal(); if (userInSession.getUsername().equals(userName)) { token = getToken(authentication, user); context.setAuthentication(token); } } } LOGGER.info("Refreshed context for user: {}", userName); }
/** * 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; }
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; }
@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); }
@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); }
@RequestMapping(value = "/rest/auth", method = RequestMethod.POST, produces = {"application/json"}) @ResponseBody public AuthenticationResultDto postUser(@RequestParam("user") String user, HttpServletRequest request) { AuthenticationResultDto dto = new AuthenticationResultDto(); dto.setSessionId(request.getSession().getId()); try { // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated AbstractAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, ""); token.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authentication); dto.setSuccess(Boolean.TRUE); request.getSession().setAttribute("authenticated", Boolean.TRUE); } catch (Exception e) { SecurityContextHolder.getContext().setAuthentication(null); dto.setSuccess(Boolean.FALSE); request.getSession().setAttribute("authenticated", Boolean.FALSE); } return dto; }
protected Authentication convertToAuthentication(Subject subject) { AbstractAuthenticationToken authToken = null; Set<UsernamePasswordPrincipal> principalSet = subject.getPrincipals(UsernamePasswordPrincipal.class); if (principalSet.size() > 0) { UsernamePasswordPrincipal upp = principalSet.iterator().next(); authToken = new UsernamePasswordAuthenticationToken(upp.getName(), upp.getPassword()); } if (authToken != null) { Set<DomainPrincipal> auxset = subject.getPrincipals(DomainPrincipal.class); if (auxset.size() > 0) { String domain = auxset.iterator().next().getName(); authToken.setDetails(domain); } } return authToken; }
@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() + "]"); } } } }
/** * 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; }
/** * JAVADOC Method Level Comments * * @throws Throwable JAVADOC. */ @Test public void test() throws Throwable { //create authentication User user = new User(); user.setUsername("loggedin"); //set security AbstractAuthenticationToken authToken = setSecurity(user, true); //mock systemUserService returns username String systemUsername = "ADMIN"; when(systemUserService.getUsername()).thenReturn(systemUsername); SystemUserMethodInterceptor interceptor = new SystemUserMethodInterceptor(userAccessor, systemUserService); interceptor.invoke(methodInvocation); //mock authenticatioNService call verify(userAccessor).forceUserToContext(systemUsername); verify(methodInvocation).proceed(); //test it switches back assertEquals(CurrentUserAccessor.currentAuthentication(), authToken); }
@Override @Transactional public void refreshAllUsersContextIfActive() { Collection<HttpSession> sessions = sessionHandler.getAllSessions(); MotechUser user; LOGGER.info("Refreshing context for all active users, number of sessions: {}", sessions.size()); for (HttpSession session : sessions) { SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT"); if (context != null) { Authentication authentication = context.getAuthentication(); AbstractAuthenticationToken token; User userInSession = (User) authentication.getPrincipal(); user = motechUsersDao.findByUserName(userInSession.getUsername()); if (user == null) { LOGGER.warn("User {} has a session, but does not exist", userInSession.getUsername()); } else { LOGGER.debug("Refreshing context for user {}", user.getUserName()); token = getToken(authentication, user); context.setAuthentication(token); } } } LOGGER.info("Refreshed context for all active users"); }
/** * authenticate the user based on token * * @return */ private AbstractAuthenticationToken authUserByToken(final String token) { final UserToken userToken = userTokenDao.findByAuthenticationToken(token); if (null == userToken) { return null; } final AbstractAuthenticationToken authToken = new AuthenticationToken(userToken); return authToken; }
@Override public void onApplicationEvent(AbstractAuthenticationEvent event) { Authentication authentication = event.getAuthentication(); if (event instanceof AuthenticationSuccessEvent) { ResourceOwnerPasswordResourceDetails resource = getResourceOwnerPasswordResourceDetails(); resource.setScope(Arrays.asList("words")); resource.setUsername(authentication.getName()); resource.setPassword(authentication.getCredentials().toString()); try { OAuth2AccessToken accessToken = accessTokenProvider.obtainAccessToken(resource, new DefaultAccessTokenRequest()); log.debug("Access token request succeeded for user: '{}', new token is '{}'" , resource.getUsername() , accessToken.getValue()); if (authentication instanceof AbstractAuthenticationToken && authentication.getDetails() instanceof CustomAuthenticationDetails) { ((CustomAuthenticationDetails) ((AbstractAuthenticationToken) authentication).getDetails()) .setBearer(accessToken.getValue()); log.debug("Access token was added to authentication as details"); } else if (log.isDebugEnabled()) { log.debug("Access token could not be added to authentication as details"); } } catch (Exception e) { log.error("Access token request failed for user: '" + resource.getUsername() + "'", e); } } if (authentication instanceof CredentialsContainer) { // Authentication is complete. Remove credentials and other secret data from authentication ((CredentialsContainer)authentication).eraseCredentials(); } }
@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); }
@PreAuthorize("isAuthenticated()") @RequestMapping(value = "/logged", method = RequestMethod.GET) public UserAuthView isLogged(Principal principal) { UserAuthView userAuthView = new UserAuthView(); if (principal instanceof AbstractAuthenticationToken) { userAuthView = (UserAuthView) ((AbstractAuthenticationToken) principal).getPrincipal(); } if (SecurityUtils.isSwitchedUser()) { userAuthView.setSwitchedUser(true); } return userAuthView; }
/** * Default implementation returns the user authentication associated with the auth token, if the token is provided. Otherwise, the consumer authentication * is returned. * * @param request The request that was successfully authenticated. * @param authentication The consumer authentication (details about how the request was authenticated). * @param authToken The OAuth token associated with the authentication. This token MAY be null if no authenticated token was needed to successfully * authenticate the request (for example, in the case of 2-legged OAuth). * @return The authentication. */ public Authentication createAuthentication(HttpServletRequest request, ConsumerAuthentication authentication, OAuthAccessProviderToken authToken) { if (authToken != null) { Authentication userAuthentication = authToken.getUserAuthentication(); if (userAuthentication instanceof AbstractAuthenticationToken) { //initialize the details with the consumer that is actually making the request on behalf of the user. ((AbstractAuthenticationToken) userAuthentication).setDetails(new OAuthAuthenticationDetails(request, authentication.getConsumerDetails())); } return userAuthentication; } return authentication; }
@Override public UserDetails loadUserDetails(AbstractAuthenticationToken token) throws UsernameNotFoundException { GameonUser user = new GameonUser(token.getName(), "", token.getAuthorities() ); // OpenIDAuthenticationToken if(token instanceof OpenIDAuthenticationToken){ List<OpenIDAttribute> attributes = ((OpenIDAuthenticationToken)token).getAttributes(); user.setOpenIDAttributes(attributes); } return user; }
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = new LinkedHashMap<String, String>( tokenRequest.getRequestParameters()); String username = parameters.get("username"); String password = parameters.get("password"); String clientId = client.getClientId(); // Protect from downstream leaks of password parameters.remove("password"); Authentication userAuth; if ("foo_app".equalsIgnoreCase(clientId)) { userAuth = new FooUsernamePasswordAuthenticationToken(username, password); } else if ("bar_app".equalsIgnoreCase(clientId)) { userAuth = new BarUsernamePasswordAuthenticationToken(username, password); } else { throw new InvalidGrantException("Unknown client: " + clientId); } ((AbstractAuthenticationToken) userAuth).setDetails(parameters); try { userAuth = authenticationManager.authenticate(userAuth); } catch (AccountStatusException ase) { //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage()); } catch (BadCredentialsException e) { // If the username/password are wrong the spec says we should send 400/invalid grant throw new InvalidGrantException(e.getMessage()); } if (userAuth == null || !userAuth.isAuthenticated()) { throw new InvalidGrantException( "Could not authenticate user: " + username); } OAuth2Request storedOAuth2Request = getRequestFactory() .createOAuth2Request(client, tokenRequest); return new OAuth2Authentication(storedOAuth2Request, userAuth); }
private AbstractAuthenticationToken createAuthenticationToken( String apiKeyValue, RestCredentials restCredentials) { return new RestAuthenticationToken(apiKeyValue, restCredentials); }
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse); responseWrapper.setHeader("X-Frame-Options", "DENY"); if (!ssoEnabled) { filterChain.doFilter(servletRequest, servletResponse); return; } HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; if (LOG.isDebugEnabled()) { LOG.debug("Knox doFilter {}", httpRequest.getRequestURI()); } if (httpRequest.getSession() != null && httpRequest.getSession().getAttribute("locallogin") != null) { servletRequest.setAttribute("ssoEnabled", false); filterChain.doFilter(servletRequest, servletResponse); return; } if (jwtProperties == null || isAuthenticated()) { filterChain.doFilter(servletRequest, servletResponse); return; } if (LOG.isDebugEnabled()) { LOG.debug("Knox ssoEnabled {} {}", ssoEnabled, httpRequest.getRequestURI()); } //if jwt properties are loaded and is current not authenticated then it will go for sso authentication //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String serializedJWT = getJWTFromCookie(httpRequest); // if we get the hadoop-jwt token from the cookies then will process it further if (serializedJWT != null) { SignedJWT jwtToken = null; try { jwtToken = SignedJWT.parse(serializedJWT); boolean valid = validateToken(jwtToken); //if the public key provide is correct and also token is not expired the process token if (valid) { String userName = jwtToken.getJWTClaimsSet().getSubject(); LOG.info("SSO login user : {} ", userName); //if we get the userName from the token then log into atlas using the same user if (userName != null && !userName.trim().isEmpty()) { List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName); final UserDetails principal = new User(userName, "", grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths); WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest); ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails); authenticationProvider.setSsoEnabled(ssoEnabled); Authentication authentication = authenticationProvider.authenticate(finalAuthentication); SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(servletRequest, httpServletResponse); } else { // if the token is not valid then redirect to knox sso redirectToKnox(httpRequest, httpServletResponse, filterChain); } } catch (ParseException e) { LOG.warn("Unable to parse the JWT token", e); redirectToKnox(httpRequest, httpServletResponse, filterChain); } } else { redirectToKnox(httpRequest, httpServletResponse, filterChain); } }
/** * @param token */ private static void putTokenInContext( AbstractAuthenticationToken token ) { SecurityContextHolder.getContext().setAuthentication( token ); }
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { final boolean debug = logger.isDebugEnabled(); final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; try { Authentication authentication = tokenExtractor.extract(request); if (authentication == null) { if (debug) { logger.debug("No token in request, will continue chain."); } } else { request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal()); if (authentication instanceof AbstractAuthenticationToken) { AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication; needsDetails.setDetails(authenticationDetailsSource.buildDetails(request)); } Authentication authResult = authenticationManager.authenticate(authentication); if (debug) { logger.debug("Authentication success: " + authResult); } SecurityContextHolder.getContext().setAuthentication(authResult); } } catch (OAuth2Exception failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request failed: " + failed); } authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(failed.getMessage(), failed)); return; } chain.doFilter(request, response); }
/** * Provided so that subclasses may configure what is put into the * authentication request's details property. * * @param request * that an authentication request is being created for * @param authRequest * the authentication request object that should have its details * set */ protected void setDetails(HttpServletRequest request, AbstractAuthenticationToken authRequest) { authRequest.setDetails(authenticationDetailsSource .buildDetails(request)); }
/** * Provided so that subclasses may configure what is put into the authentication request's details * property. * * @param request that an authentication request is being created for * @param authRequest the authentication request object that should have its details set */ protected void setDetails(HttpServletRequest request, AbstractAuthenticationToken authRequest) { authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); }