List of usage examples for org.springframework.security.core.context SecurityContext getAuthentication
Authentication getAuthentication();
From source file:Controller.UsuarioBean.java
public void pegarUsuarioSpringer() { usuario = new Usuario(); SecurityContext context = SecurityContextHolder.getContext(); if (context instanceof SecurityContext) { Authentication authentication = context.getAuthentication(); if (authentication instanceof Authentication) { try { System.out/*from w w w . ja va 2 s .c o m*/ .println("Teste de usurio: " + ((User) authentication.getPrincipal()).getUsername()); usuario = UsuarioDAO.getInstance() .buscarDadosUsuario(((User) authentication.getPrincipal()).getUsername()); } catch (Exception ex) { Logger.getLogger(UsuarioBean.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:org.geonode.security.GeoNodeCookieProcessingFilter.java
/** * //from w w w .j av a2s . c o m * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final SecurityContext securityContext = SecurityContextHolder.getContext(); final Authentication existingAuth = securityContext.getAuthentication(); final String gnCookie = getGeoNodeCookieValue(httpRequest); final boolean alreadyAuthenticated = existingAuth != null && existingAuth.isAuthenticated(); final boolean anonymous = existingAuth == null || existingAuth instanceof AnonymousAuthenticationToken; // if logging in via geoserver web form, we want to short circuit the cookie // check below which might get triggered with an anon geonode cookie // the result looks like the login worked but because we replace the // auth below, it functionaly fails final boolean loggedInWithPassword = existingAuth instanceof UsernamePasswordAuthenticationToken && alreadyAuthenticated; final boolean hasPreviouslyValidatedGeoNodeCookie = (existingAuth instanceof GeoNodeSessionAuthToken) && existingAuth.getCredentials().equals(gnCookie); if (hasPreviouslyValidatedGeoNodeCookie) existingAuth.setAuthenticated(true); // if we still need to authenticate and we find the cookie, consult GeoNode for // an authentication final boolean authenticationRequired = (!alreadyAuthenticated || anonymous || !hasPreviouslyValidatedGeoNodeCookie); if (!loggedInWithPassword && authenticationRequired && gnCookie != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine( "Found GeoNode cookie - checking if we have the authorizations in cache or if we have to reload from GeoNode"); } try { Object principal = existingAuth == null ? null : existingAuth.getPrincipal(); Collection<? extends GrantedAuthority> authorities = existingAuth == null ? null : existingAuth.getAuthorities(); Authentication authRequest = new GeoNodeSessionAuthToken(principal, gnCookie, authorities); final Authentication authResult = getSecurityManager().authenticate(authRequest); LOGGER.log(Level.FINE, "authResult : {0}", authResult); securityContext.setAuthentication(authResult); } catch (AuthenticationException e) { // we just go ahead and fall back on basic authentication LOGGER.log(Level.WARNING, "Error connecting to the GeoNode server for authentication purposes", e); } } // move forward along the chain chain.doFilter(request, response); }
From source file:pl.chilldev.facelets.taglib.spring.security.AuthenticationTag.java
/** * {@inheritDoc}//from w w w.ja v a 2s.co m * * @since 0.0.1 */ @Override public void apply(FaceletContext context, UIComponent parent) { String property = this.property.getValue(context); Object value = null; SecurityContext securityContext = SecurityContextHolder.getContext(); // if there is no authentication object we can't process the property expression Authentication auth = securityContext.getAuthentication(); if (auth != null) { try { BeanWrapperImpl wrapper = new BeanWrapperImpl(auth); value = wrapper.getPropertyValue(property); } catch (BeansException error) { throw new FacesException(error); } } // just output the text if (this.var == null) { UIOutput component = new UIOutput(); component.setValue(value); parent.getChildren().add(component); } else { // assign result to the variable context.setAttribute(this.var.getValue(context), value); } }
From source file:org.jasig.schedassist.web.register.delegate.DelegateRegistrationHelper.java
/** * //from www .j a va2 s .c o m * @param registration * @throws IneligibleException * @throws InputFormatException * @throws ParseException */ public void executeDelegateRegistration(final Registration registration) throws IneligibleException, InputFormatException, ParseException { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); DelegateCalendarAccountUserDetailsImpl currentUser = (DelegateCalendarAccountUserDetailsImpl) authentication .getPrincipal(); IScheduleOwner delegateOwner = ownerDao.register(currentUser.getCalendarAccount()); delegateOwner = ownerDao.updatePreference(delegateOwner, Preferences.LOCATION, registration.getLocation()); delegateOwner = ownerDao.updatePreference(delegateOwner, Preferences.DURATIONS, registration.durationPreferenceValue()); delegateOwner = ownerDao.updatePreference(delegateOwner, Preferences.MEETING_PREFIX, registration.getTitlePrefix()); delegateOwner = ownerDao.updatePreference(delegateOwner, Preferences.NOTEBOARD, registration.getNoteboard()); delegateOwner = ownerDao.updatePreference(delegateOwner, Preferences.VISIBLE_WINDOW, registration.visibleWindowPreferenceKey()); delegateOwner = ownerDao.updatePreference(delegateOwner, Preferences.DEFAULT_VISITOR_LIMIT, Integer.toString(registration.getDefaultVisitorsPerAppointment())); delegateOwner = ownerDao.updatePreference(delegateOwner, Preferences.MEETING_LIMIT, Integer.toString(registration.getMeetingLimitValue())); delegateOwner = ownerDao.updatePreference(delegateOwner, Preferences.REFLECT_SCHEDULE, Boolean.toString(registration.isReflectSchedule())); delegateOwner = ownerDao.updatePreference(delegateOwner, Preferences.REMINDERS, registration.emailReminderPreferenceKey()); if (registration.isScheduleSet()) { SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); Set<AvailableBlock> blocks = AvailableBlockBuilder.createBlocks(registration.getStartTimePhrase(), registration.getEndTimePhrase(), registration.getDaysOfWeekPhrase(), dateFormat.parse(registration.getStartDatePhrase()), dateFormat.parse(registration.getEndDatePhrase()), registration.getDefaultVisitorsPerAppointment()); availableScheduleDao.addToSchedule(delegateOwner, blocks); } if (registration.isReflectSchedule()) { reflectionService.reflectAvailableSchedule(delegateOwner); } }
From source file:cn.org.once.cstack.users.UserControllerTestIT.java
@Test public void test00_userAuthenticatesSuccess() throws Exception { logger.info("test00_userAuthenticates"); final String username = "johndoe"; mockMvc.perform(post("/user/authentication").param("j_username", username).param("j_password", "abc2015")) .andExpect(mvcResult -> { HttpSession session1 = mvcResult.getRequest().getSession(); SecurityContext securityContext = (SecurityContext) session1.getAttribute(SEC_CONTEXT_ATTR); Assert.assertEquals(securityContext.getAuthentication().getName(), username); });/*from w w w . ja v a 2s .co m*/ }
From source file:com.javaforge.tapestry.acegi.service.impl.SecurityUtilsImpl.java
public void checkSecurity(Object object, Collection<ConfigAttribute> attr) { Assert.notNull(object, "Object was null"); if (attr != null) { if (getLog().isDebugEnabled()) { getLog().debug("Secure object: " + object.toString() + "; ConfigAttributes: " + attr.toString()); }/* ww w . ja v a2 s . c om*/ // We check for just the property we're interested in (we do // not call Context.validate() like the ContextInterceptor) if (SecurityContextHolder.getContext().getAuthentication() == null) { throw new AuthenticationCredentialsNotFoundException( messages.getMessage("AbstractSecurityInterceptor.authenticationNotFound", "An Authentication object was not found in the SecurityContext")); } // Attempt authentication if not already authenticated, or user always wants reauthentication Authentication authenticated; SecurityContext ctx = SecurityContextHolder.getContext(); if (ctx.getAuthentication() == null || !ctx.getAuthentication().isAuthenticated() || alwaysReauthenticate) { authenticated = this.authenticationManager .authenticate(SecurityContextHolder.getContext().getAuthentication()); // We don't authenticated.setAuthentication(true), because each provider should do that if (getLog().isDebugEnabled()) { getLog().debug("Successfully Authenticated: " + authenticated.toString()); } SecurityContextHolder.getContext().setAuthentication(authenticated); } else { authenticated = SecurityContextHolder.getContext().getAuthentication(); if (getLog().isDebugEnabled()) { getLog().debug("Previously Authenticated: " + authenticated.toString()); } } // Attempt authorization this.accessDecisionManager.decide(authenticated, object, attr); if (getLog().isDebugEnabled()) { getLog().debug("Authorization successful"); } // Attempt to run as a different user Authentication runAs = this.runAsManager.buildRunAs(authenticated, object, attr); if (runAs == null) { if (getLog().isDebugEnabled()) { getLog().debug("RunAsManager did not change Authentication object"); } } else { if (getLog().isDebugEnabled()) { getLog().debug("Switching to RunAs Authentication: " + runAs.toString()); } SecurityContextHolder.getContext().setAuthentication(runAs); } } else { if (getLog().isDebugEnabled()) { getLog().debug("Public object - authentication not attempted"); } } }
From source file:org.musicrecital.webapp.listener.UserCounterListener.java
/** * This method is designed to catch when user's login and record their name * * @param event the event to process//from www . j a v a 2 s.c o m * @see javax.servlet.http.HttpSessionAttributeListener#attributeAdded(javax.servlet.http.HttpSessionBindingEvent) */ public void attributeAdded(HttpSessionBindingEvent event) { if (event.getName().equals(EVENT_KEY) && !isAnonymous()) { SecurityContext securityContext = (SecurityContext) event.getValue(); if (securityContext != null && securityContext.getAuthentication().getPrincipal() instanceof User) { User user = (User) securityContext.getAuthentication().getPrincipal(); addUsername(user); } } }
From source file:org.brutusin.rpc.websocket.WebsocketEndpoint.java
protected boolean allowAccess(Session session, WebsocketContext websocketContext) { final RpcSpringContext rpcCtx = websocketContext.getSpringContext(); if (rpcCtx.getParent() != null) { try {/*from w ww . j a va 2 s . co m*/ if (rpcCtx.getParent().getBean("springSecurityFilterChain") != null) { // Security active final SecurityContext sc = (SecurityContext) websocketContext.getSecurityContext(); if (sc.getAuthentication() == null) { return false; } else { return sc.getAuthentication().isAuthenticated(); } } } catch (NoSuchBeanDefinitionException ex) { return true; } } return true; }
From source file:alpha.portal.webapp.listener.UserCounterListener.java
/** * This method is designed to catch when user's login and record their name. * //from ww w . j av a 2s . c o m * @param event * the event to process * @see javax.servlet.http.HttpSessionAttributeListener#attributeAdded(javax.servlet.http.HttpSessionBindingEvent) */ public void attributeAdded(final HttpSessionBindingEvent event) { if (event.getName().equals(UserCounterListener.EVENT_KEY) && !this.isAnonymous()) { final SecurityContext securityContext = (SecurityContext) event.getValue(); if (securityContext.getAuthentication().getPrincipal() instanceof User) { final User user = (User) securityContext.getAuthentication().getPrincipal(); this.addUsername(user); } } }
From source file:es.mdef.clientmanager.ui.GestionClientesUI.java
private String getNombreUsuario() { String nombre = ""; SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); if (authentication != null && authentication.isAuthenticated() && !authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))) { UserDetail userDetail = (UserDetail) authentication.getDetails(); nombre = userDetail.getAppUser().getUserName(); }//from w w w. j a va2 s .c o m return nombre; }