List of usage examples for org.springframework.security.core Authentication isAuthenticated
boolean isAuthenticated();
AuthenticationManager
. From source file:org.geoserver.security.GeoServerSecurityManager.java
/** * Checks if the specified authentication contains the specified role. * // w w w . j a va2s . c om * If the current {@link HttpServletRequest} has security disabled, * this method always returns <code>true</code>. * * @return <code>true</code> if the authenticated contains the role, otherwise <code>false</false> */ public boolean checkAuthenticationForRole(Authentication auth, GeoServerRole role) { if (GeoServerSecurityFilterChainProxy.isSecurityEnabledForCurrentRequest() == false) return true; // No security means any role is granted if (auth == null || !auth.isAuthenticated()) { return false; } for (GrantedAuthority authority : auth.getAuthorities()) { if (role.getAuthority().equals(authority.getAuthority())) { return true; } } return false; }
From source file:org.geoserver.security.password.MasterPasswordChangeTest.java
@Test public void testMasterPasswordChange() throws Exception { // keytool -storepasswd -new geoserver1 -storepass geoserver -storetype jceks -keystore geoserver.jks String masterPWAsString = getMasterPassword(); MasterPasswordConfig config = getSecurityManager().getMasterPasswordConfig(); URLMasterPasswordProviderConfig mpConfig = (URLMasterPasswordProviderConfig) getSecurityManager() .loadMasterPassswordProviderConfig(config.getProviderName()); assertTrue(mpConfig.getURL().toString().endsWith(URLMasterPasswordProviderConfig.MASTER_PASSWD_FILENAME)); getSecurityManager().getKeyStoreProvider().reloadKeyStore(); try {//from w w w . ja v a 2s. co m getSecurityManager().saveMasterPasswordConfig(config, null, null, null); fail(); } catch (MasterPasswordChangeException ex) { } ///// First change using rw_url mpConfig = new URLMasterPasswordProviderConfig(); mpConfig.setName("rw"); mpConfig.setClassName(URLMasterPasswordProvider.class.getCanonicalName()); mpConfig.setReadOnly(false); File tmp = new File(getSecurityManager().getSecurityRoot(), "mpw1.properties"); mpConfig.setURL(DataUtilities.fileToURL(tmp)); getSecurityManager().saveMasterPasswordProviderConfig(mpConfig); config = getSecurityManager().getMasterPasswordConfig(); config.setProviderName(mpConfig.getName()); getSecurityManager().saveMasterPasswordConfig(config, masterPWAsString.toCharArray(), "geoserver1".toCharArray(), "geoserver1".toCharArray()); assertEquals("geoserver1", getMasterPassword()); getSecurityManager().getKeyStoreProvider().getConfigPasswordKey(); /////////////// change with ro url mpConfig = new URLMasterPasswordProviderConfig(); mpConfig.setName("ro"); mpConfig.setClassName(URLMasterPasswordProvider.class.getCanonicalName()); mpConfig.setReadOnly(true); tmp = new File(getSecurityManager().getSecurityRoot(), "mpw2.properties"); mpConfig.setURL(DataUtilities.fileToURL(tmp)); FileUtils.writeStringToFile(tmp, "geoserver2"); getSecurityManager().saveMasterPasswordProviderConfig(mpConfig); config = getSecurityManager().getMasterPasswordConfig(); config.setProviderName("ro"); getSecurityManager().saveMasterPasswordConfig(config, "geoserver1".toCharArray(), null, "geoserver2".toCharArray()); assertEquals("geoserver2", getMasterPassword()); getSecurityManager().getKeyStoreProvider().getConfigPasswordKey(); /////////////////////// change simulating spring injection MasterPasswordProviderConfig mpConfig2 = new MasterPasswordProviderConfig(); mpConfig2.setName("test"); mpConfig2.setClassName(TestMasterPasswordProvider.class.getCanonicalName()); getSecurityManager().saveMasterPasswordProviderConfig(mpConfig2); config = getSecurityManager().getMasterPasswordConfig(); config.setProviderName("test"); getSecurityManager().saveMasterPasswordConfig(config, "geoserver2".toCharArray(), "geoserver3".toCharArray(), "geoserver3".toCharArray()); // now, a geoserver restart should appear, simulate with getSecurityManager().getKeyStoreProvider().commitMasterPasswordChange(); ////////// assertEquals("geoserver3", getMasterPassword()); getSecurityManager().getKeyStoreProvider().getConfigPasswordKey(); /// Test root login after master password change Authentication auth = new UsernamePasswordAuthenticationToken("root", "geoserver3"); GeoServerRootAuthenticationProvider authProvider = new GeoServerRootAuthenticationProvider(); authProvider.setSecurityManager(getSecurityManager()); auth = authProvider.authenticate(auth); assertTrue(auth.isAuthenticated()); auth = new UsernamePasswordAuthenticationToken("root", "abcdefghijk"); assertNull(authProvider.authenticate(auth)); assertFalse(auth.isAuthenticated()); }
From source file:org.hyperic.hq.web.login.LoginController.java
@RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login(HttpServletRequest request, HttpServletResponse response, HttpSession session) { final boolean debug = log.isDebugEnabled(); ModelAndView result = new ModelAndView(); // ...first check for an authentication object, if one exists we are already logged in... Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated()) { try {/*w w w .j a v a2 s.c o m*/ if (debug) log.debug("User has already been authenticated. Redirecting to dashboard."); response.sendRedirect("/Dashboard.do"); return result; } catch (IOException e) { log.warn("Could not perform the redirect for an authenticated user, displaying login page instead"); } } // ...we're dealing with an unauthenticated user, we're going to show the login form... AuthzSubject guestUser = authzSubjectManager.getSubjectById(AuthzConstants.guestId); // ...before we return, check for an error message... boolean loginError = request.getParameter("authfailed") != null; if (loginError) { if (session != null) { AuthenticationException ex = (AuthenticationException) session .getAttribute(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY); if (ex != null) { result.addObject("errorMessage", RequestUtils.message(request, ex.getMessage())); } } } result.addObject("guestUsername", (guestUser != null) ? guestUser.getName() : "guest"); result.addObject("guestEnabled", (guestUser != null && guestUser.getActive())); // ...set a response header so we can identify the login page explicitly... response.setHeader("hq-requires-auth", "1"); return result; }
From source file:org.jamwiki.authentication.JAMWikiPostAuthenticationFilter.java
/** * *//*from w w w . j av a 2 s . c om*/ private void handleAnonymousUser(Authentication auth) { if (!this.getUseJAMWikiAnonymousRoles()) { // the configuration file indicates that JAMWiki anonymous roles should not be // used, so assume that an external system is providing this information. return; } // get arrays of existing Spring Security roles and JAMWiki anonymous user roles Collection<GrantedAuthority> springSecurityAnonymousAuthorities = auth.getAuthorities(); Collection<GrantedAuthority> jamwikiAnonymousAuthorities = JAMWikiAuthenticationConfiguration .getJamwikiAnonymousAuthorities(); if (springSecurityAnonymousAuthorities == null || jamwikiAnonymousAuthorities == null) { return; } List<GrantedAuthority> anonymousAuthorities = new ArrayList<GrantedAuthority>(); anonymousAuthorities.addAll(springSecurityAnonymousAuthorities); anonymousAuthorities.addAll(jamwikiAnonymousAuthorities); // replace the existing anonymous authentication object with the new authentication array AnonymousAuthenticationToken jamwikiAuth = new AnonymousAuthenticationToken(this.getKey(), auth.getPrincipal(), anonymousAuthorities); jamwikiAuth.setDetails(auth.getDetails()); jamwikiAuth.setAuthenticated(auth.isAuthenticated()); SecurityContextHolder.getContext().setAuthentication(jamwikiAuth); }
From source file:org.josso.spring.security.JOSSOAuthenticationFilter.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { if (!(servletRequest instanceof HttpServletRequest)) { throw new IllegalArgumentException("Non HTTP request unsupported by this filter"); }/*from w w w.ja v a2 s .c om*/ if (!(servletResponse instanceof HttpServletResponse)) { throw new IllegalArgumentException("Non HTTP response unsupported by this filter"); } HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; // We have to provide Authentication information based on JOSSO auth information ... // Obtain a JOSSO security context instance, if none is found is because user has not been authenticated. JOSSOSecurityContext sctx = WebAccessControlUtil.getSecurityContext((HttpServletRequest) request); logger.debug("Current JOSSO Security Context is " + sctx); // This is the authentication information used by ACEGI Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // If authentication information is present, we only need to validate that it is up to date. if (authentication != null) { if (logger.isDebugEnabled()) { logger.debug("Authentication information already present : '" + SecurityContextHolder.getContext().getAuthentication() + "'"); } // If there is no principal, we may need to logout this user ... TODO detect anonymous principals ? if (sctx == null && authentication.isAuthenticated()) { // If an authenticated Authentication is present, we must issue a logout ! if (logger.isDebugEnabled()) { logger.debug("Logging out user '" + authentication + "'"); } for (int i = 0; i < handlers.length; i++) { handlers[i].logout(request, response, authentication); } } chain.doFilter(request, response); return; } // We have a principal but no Spring Security authentication, propagate identity from JOSSO to Spring Security. if (sctx != null) { // If a saved request is present, we use the saved request to redirect the user to the original resource. SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response); if (savedRequest != null) logger.debug("Redirecting to original resource " + savedRequest.getRedirectUrl()); UserDetails userDetails = userDetailsService.loadUserByUsername(sctx.getSSOSession()); // String jossoSessionId = (String) request.getAttribute("org.josso.agent.ssoSessionid"); // New authenticated autentication instance. Authentication jossoAuth = new JOSSOAuthenticationToken(sctx.getSSOSession(), userDetails, userDetails.getAuthorities()); // Store to SecurityContextHolder SecurityContextHolder.getContext().setAuthentication(jossoAuth); if (logger.isDebugEnabled()) { logger.debug("SecurityContextHolder populated with JOSSO Authentication Token: '" + SecurityContextHolder.getContext().getAuthentication() + "'"); } // Fire event if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent( SecurityContextHolder.getContext().getAuthentication(), this.getClass())); } // We have a saved request, redirect to original URL ... if (savedRequest != null) response.sendRedirect(savedRequest.getRedirectUrl()); } else { if (logger.isDebugEnabled()) logger.debug("No principal found in request !"); } // Move on ... chain.doFilter(request, response); }
From source file:org.jwebsocket.plugins.system.SystemPlugIn.java
/** * Logon a user given the username and password by using the Spring Security module * * @param aConnector//from w w w . ja v a 2s . c o m * @param aToken The token with the username and password */ void logon(WebSocketConnector aConnector, Token aToken) { TokenServer lServer = getServer(); if (aConnector.getSession().isAuthenticated()) { lServer.sendToken(aConnector, lServer.createErrorToken(aToken, -1, "is authenticated")); return; } String lUsername = aToken.getString("username"); String lPassword = aToken.getString("password"); if (mLog.isDebugEnabled()) { mLog.debug("Starting authentication ..."); } Authentication lAuthRequest = new UsernamePasswordAuthenticationToken(lUsername, lPassword); Authentication lAuthResult; try { lAuthResult = getAuthProvMgr().authenticate(lAuthRequest); } catch (AuthenticationException ex) { String lMsg = ex.getClass().getSimpleName() + ": " + ex.getMessage(); Token lResponse = getServer().createErrorToken(aToken, -1, lMsg); lResponse.setString("username", lUsername); sendToken(aConnector, aConnector, lResponse); if (mLog.isDebugEnabled()) { mLog.debug(lMsg); } return; // stop the execution flow } if (mLog.isDebugEnabled()) { mLog.debug("Authentication successful. Updating the user session (id: " + (null != aConnector.getSession() ? aConnector.getSession().getSessionId() : "[null]") + ", storage: " + (null != aConnector.getSession() ? aConnector.getSession().getStorage() : "[null]") + ")..."); } // getting the session Map<String, Object> lSession = aConnector.getSession().getStorage(); // setting the is_authenticated flag lSession.put(IS_AUTHENTICATED, lAuthResult.isAuthenticated()); // setting the connector username aConnector.setUsername(lUsername); // setting the uuid String lUUID; Object lDetails = lAuthResult.getDetails(); if (null != lDetails && lDetails instanceof IUserUniqueIdentifierContainer) { lUUID = ((IUserUniqueIdentifierContainer) lDetails).getUUID(); } else { lUUID = lUsername; } lSession.put(UUID, lUUID); // setting the authorities String lAuthorities = ""; for (GrantedAuthority lGA : lAuthResult.getAuthorities()) { lAuthorities = lAuthorities.concat(lGA.getAuthority() + " "); } // storing the user authorities as a string to avoid serialization problems lSession.put(AUTHORITIES, lAuthorities); // creating the response Token lResponse = createResponse(aToken); lResponse.setString("uuid", lUUID); lResponse.setString("username", lUsername); lResponse.setList("authorities", Tools.parseStringArrayToList(lAuthorities.split(" "))); // sending the response to requester sendToken(aConnector, lResponse); // sending response to clients that share the requester session getServer().broadcastToSharedSession(aConnector.getId(), aConnector.getSession().getSessionId(), lResponse, false); if (mLog.isDebugEnabled()) { mLog.debug("Logon process finished successfully!"); } // if successfully logged in... if (lUsername != null) { // broadcast "login event" to other clients broadcastLoginEvent(aConnector); } }
From source file:org.orcid.frontend.web.controllers.BaseController.java
protected void logoutCurrentUser(HttpServletRequest request, HttpServletResponse response) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (internalSSOManager.enableCookie()) { Cookie[] cookies = request.getCookies(); // Delete cookie and token associated with that cookie if (cookies != null) { for (Cookie cookie : cookies) { if (InternalSSOManager.COOKIE_NAME.equals(cookie.getName())) { try { // If it is a valid cookie, extract the orcid value // and // remove the token and the cookie @SuppressWarnings("unchecked") HashMap<String, String> cookieValues = JsonUtils .readObjectFromJsonString(cookie.getValue(), HashMap.class); if (cookieValues.containsKey(InternalSSOManager.COOKIE_KEY_ORCID) && !PojoUtil.isEmpty(cookieValues.get(InternalSSOManager.COOKIE_KEY_ORCID))) { internalSSOManager.deleteToken( cookieValues.get(InternalSSOManager.COOKIE_KEY_ORCID), request, response); } else { // If it is not valid, just remove the cookie cookie.setValue(StringUtils.EMPTY); cookie.setMaxAge(0); response.addCookie(cookie); }/*from www.ja va 2 s. co m*/ } catch (RuntimeException re) { // If any exception happens, but, the cookie exists, // remove the cookie cookie.setValue(StringUtils.EMPTY); cookie.setMaxAge(0); response.addCookie(cookie); } break; } } } // Delete token if exists if (authentication != null && !PojoUtil.isEmpty(authentication.getName())) { internalSSOManager.deleteToken(authentication.getName()); } } if (authentication != null && authentication.isAuthenticated()) { new SecurityContextLogoutHandler().logout(request, response, authentication); } CsrfToken token = csrfTokenRepository.generateToken(request); csrfTokenRepository.saveToken(token, request, response); request.setAttribute("_csrf", token); }
From source file:org.patientview.radar.service.impl.UserManagerImpl.java
public boolean authenticateProfessionalUser(String username, String password) throws AuthenticationException { ProfessionalUser professionalUser = userDao.getProfessionalUserByUsername(username); if (professionalUser != null) { try {//from w w w . ja v a 2 s .c om Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); return authentication.isAuthenticated(); } catch (AuthenticationException e) { LOGGER.warn("Authentication failed for user {} and password {}", username, e.getMessage()); throw e; } } return false; }
From source file:org.saiku.web.service.SessionService.java
private void createSession(Authentication auth, String username, String password) { if (auth == null || !auth.isAuthenticated()) { return;//from w w w . ja v a2 s . co m } boolean isAnonymousUser = (auth instanceof AnonymousAuthenticationToken); Object p = auth.getPrincipal(); String authUser = getUsername(p); boolean isAnonymous = (isAnonymousUser || StringUtils.equals("anonymousUser", authUser)); boolean isAnonOk = (!isAnonymous || (isAnonymous && anonymous)); if (isAnonOk && auth.isAuthenticated() && p != null && !sessionHolder.containsKey(p)) { Map<String, Object> session = new HashMap<>(); if (isAnonymous) { log.debug("Creating Session for Anonymous User"); } if (StringUtils.isNotBlank(username)) { session.put("username", username); } else { session.put("username", authUser); } if (StringUtils.isNotBlank(password)) { session.put("password", password); } session.put("sessionid", UUID.randomUUID().toString()); session.put("authid", RequestContextHolder.currentRequestAttributes().getSessionId()); List<String> roles = new ArrayList<>(); for (GrantedAuthority ga : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) { roles.add(ga.getAuthority()); } session.put("roles", roles); sessionHolder.put(p, session); } }
From source file:org.sakaiproject.rubrics.security.JwtAuthenticationSuccessHandler.java
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { if (logger.isDebugEnabled()) { logger.debug(String.format("Authenticated: %s", authentication.isAuthenticated())); }// w w w .j a va 2 s .com }