Example usage for org.springframework.security.core.context SecurityContext getAuthentication

List of usage examples for org.springframework.security.core.context SecurityContext getAuthentication

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContext getAuthentication.

Prototype

Authentication getAuthentication();

Source Link

Document

Obtains the currently authenticated principal, or an authentication request token.

Usage

From source file:org.jasig.schedassist.web.register.RegistrationFlowHelper.java

/**
 * Invoke methods on the {@link OwnerDao} and {@link AvailableScheduleDao} to complete
 * the registration process.//from w  w w.  ja  v a2s  . co m
 * 
 * @param registration
 * @throws IneligibleException
 * @throws ParseException 
 * @throws InputFormatException 
 */
public void executeRegistration(final Registration registration)
        throws IneligibleException, InputFormatException, ParseException {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    CalendarAccountUserDetailsImpl currentUser = (CalendarAccountUserDetailsImpl) authentication.getPrincipal();
    IScheduleOwner owner = ownerDao.register(currentUser.getCalendarAccount());
    owner = ownerDao.updatePreference(owner, Preferences.DURATIONS, registration.durationPreferenceValue());
    owner = ownerDao.updatePreference(owner, Preferences.LOCATION, registration.getLocation());
    owner = ownerDao.updatePreference(owner, Preferences.MEETING_PREFIX, registration.getTitlePrefix());
    owner = ownerDao.updatePreference(owner, Preferences.NOTEBOARD, registration.getNoteboard());
    owner = ownerDao.updatePreference(owner, Preferences.VISIBLE_WINDOW,
            registration.visibleWindowPreferenceKey());
    owner = ownerDao.updatePreference(owner, Preferences.DEFAULT_VISITOR_LIMIT,
            Integer.toString(registration.getDefaultVisitorsPerAppointment()));
    owner = ownerDao.updatePreference(owner, Preferences.MEETING_LIMIT,
            Integer.toString(registration.getMeetingLimitValue()));
    owner = ownerDao.updatePreference(owner, Preferences.REFLECT_SCHEDULE,
            Boolean.toString(registration.isReflectSchedule()));
    owner = ownerDao.updatePreference(owner, Preferences.REMINDERS, registration.emailReminderPreferenceKey());

    if (affiliationSource.doesAccountHaveAffiliation(owner.getCalendarAccount(), AffiliationImpl.ADVISOR)) {
        // set ADVISOR_SHARE_WITH_STUDENTS by default for all academic advisors
        owner = ownerDao.updatePreference(owner, Preferences.ADVISOR_SHARE_WITH_STUDENTS, "true");
    }
    if (affiliationSource.doesAccountHaveAffiliation(owner.getCalendarAccount(), AffiliationImpl.INSTRUCTOR)) {
        // set INSTRUCTOR_SHARE_WITH_STUDENTS by default for all instructors
        owner = ownerDao.updatePreference(owner, Preferences.INSTRUCTOR_SHARE_WITH_STUDENTS, "true");
    }
    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(owner, blocks);
    }

    if (registration.isReflectSchedule()) {
        reflectionService.reflectAvailableSchedule(owner);
    }

    // since Spring Security won't let you update someone's Authorities, have to force re-auth
    SecurityContextHolder.clearContext();
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.UserFormController.java

@ModelAttribute
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
protected User showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // If not an administrator, make sure user is not trying to add or edit another user
    if (!request.isUserInRole(Constants.ADMIN_ROLE) && !isFormSubmission(request)) {
        if (isAdd(request) || request.getParameter("id") != null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            log.warn("User '" + request.getRemoteUser() + "' is trying to edit user with id '"
                    + request.getParameter("id") + "'");

            throw new AccessDeniedException("You do not have permission to modify other users.");
        }//w  w w .  j a va2s.c o m
    }

    if (!isFormSubmission(request)) {
        String userId = request.getParameter("id");

        // if user logged in with remember me, display a warning that they can't change passwords
        log.debug("checking for remember me login...");

        AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx.getAuthentication() != null) {
            Authentication auth = ctx.getAuthentication();

            if (resolver.isRememberMe(auth)) {
                request.getSession().setAttribute("cookieLogin", "true");

                // add warning message
                saveMessage(request, getText("userProfile.cookieLogin", request.getLocale()));
            }
        }

        User user;
        if (userId == null && !isAdd(request)) {
            user = getUserManager().getUserByUsername(request.getRemoteUser());
        } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) {
            user = getUserManager().getUser(userId);
        } else {
            user = new User();
            user.addRole(new Role(Constants.USER_ROLE));
        }

        user.setConfirmPassword(user.getPassword());

        return user;
    } else {
        // populate user object from database, so all fields don't need to be hidden fields in form
        return getUserManager().getUser(request.getParameter("id"));
    }
}

From source file:org.cloudfoundry.identity.uaa.login.ResetPasswordControllerIntegrationTests.java

@Test
public void testResettingAPassword() throws Exception {
    mockUaaServer.expect(requestTo("http://localhost:8080/uaa/password_change")).andExpect(method(POST))
            .andExpect(jsonPath("$.code").value("the_secret_code"))
            .andExpect(jsonPath("$.new_password").value("secret"))
            .andRespond(withSuccess(//from  w w w . ja  va2s . c om
                    "{" + "\"user_id\":\"newly-created-user-id\"," + "\"username\":\"user@example.com\"" + "}",
                    APPLICATION_JSON));

    MockHttpServletRequestBuilder post = post("/reset_password.do").param("code", "the_secret_code")
            .param("email", "user@example.com").param("password", "secret")
            .param("password_confirmation", "secret");

    MvcResult mvcResult = mockMvc.perform(post).andExpect(status().isFound()).andExpect(redirectedUrl("home"))
            .andReturn();

    SecurityContext securityContext = (SecurityContext) mvcResult.getRequest().getSession()
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    Authentication authentication = securityContext.getAuthentication();
    Assert.assertThat(authentication.getPrincipal(), instanceOf(UaaPrincipal.class));
    UaaPrincipal principal = (UaaPrincipal) authentication.getPrincipal();
    Assert.assertThat(principal.getId(), equalTo("newly-created-user-id"));
    Assert.assertThat(principal.getName(), equalTo("user@example.com"));
    Assert.assertThat(principal.getEmail(), equalTo("user@example.com"));
    Assert.assertThat(principal.getOrigin(), equalTo(Origin.UAA));
}

From source file:alpha.portal.webapp.listener.UserCounterListener.java

/**
 * When user's logout, remove their name from the hashMap.
 * /*from  ww  w.j  a  v a2  s  .  co m*/
 * @param event
 *            the session binding event
 * @see javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent)
 */
public void attributeRemoved(final HttpSessionBindingEvent event) {
    if (event.getName().equals(UserCounterListener.EVENT_KEY) && !this.isAnonymous()) {
        final SecurityContext securityContext = (SecurityContext) event.getValue();
        final Authentication auth = securityContext.getAuthentication();
        if ((auth != null) && (auth.getPrincipal() instanceof User)) {
            final User user = (User) auth.getPrincipal();
            this.removeUsername(user);
        }
    }
}

From source file:fr.univlorraine.mondossierweb.controllers.LockController.java

/**
 * Retourne le nom de l'utilisateur pour le lock pass en paramtre
 * @param obj//  w ww.ja v a 2s  . c om
 * @return userName
 */
public String getUserNameFromLock(Object obj) {
    UI lockUi = locks.get(obj);
    if (lockUi != null) {
        SecurityContext securityContext = (SecurityContext) lockUi.getSession().getSession()
                .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        return securityContext.getAuthentication().getName();
    }
    return null;
}

From source file:org.openinfinity.sso.identityprovisioning.bpmn.IdentityProvisioningBridgeSpringActivitiImpl.java

private void executeRoleProvisioning(IdentityService identityService, String userId) {
    org.springframework.security.core.context.SecurityContext securityContext = SecurityContextHolder
            .getContext();/* w  w w.ja va  2  s  . co  m*/
    Collection<? extends GrantedAuthority> grantedAuthorities = securityContext.getAuthentication()
            .getAuthorities();
    Set<String> existiningGroupsFromMasterData = new HashSet<String>();
    addGrantedAuthoritiesAsRolesAndCreateMembershipWithUserAndGroup(identityService, userId, grantedAuthorities,
            existiningGroupsFromMasterData);
    if (isDeleteNotExistingGroupsInMasterData())
        invalideMembershipAndRemoveNonExistingRoles(identityService, userId, existiningGroupsFromMasterData);
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.ConferenceUserServiceImpl.java

@Override
public Authentication getCurrentAuthentication() {
    final SecurityContext context = SecurityContextHolder.getContext();
    return context.getAuthentication();
}

From source file:org.glassmaker.spring.oauth.OAuth2Util.java

public boolean requiresAuthentication(HttpServletRequest request) {

    HttpSession session = request.getSession();
    if (session != null) {
        SecurityContext securityContext = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
        if (securityContext != null) {
            Authentication auth = securityContext.getAuthentication();
            if (auth != null && auth.isAuthenticated())
                return false;
        }/* www.ja  va  2 s  .co  m*/
    }

    String code = request.getParameter("code");
    // If we have a code, finish the OAuth 2.0 dance
    if (code == null) {
        return true;
    }
    return false;
}

From source file:org.jasig.springframework.security.portlet.context.PortletSessionSecurityContextRepositoryTests.java

@Test
public void existingContextIsSuccessFullyLoadedFromSessionAndSavedBack() throws Exception {
    PortletSessionSecurityContextRepository repo = new PortletSessionSecurityContextRepository();
    repo.setSpringSecurityContextKey("imTheContext");
    MockPortletRequest request = new MockPortletRequest();
    SecurityContextHolder.getContext().setAuthentication(testToken);
    request.getPortletSession().setAttribute("imTheContext", SecurityContextHolder.getContext(),
            PortletSession.APPLICATION_SCOPE);
    MockPortletResponse response = new MockPortletResponse();
    PortletRequestResponseHolder holder = new PortletRequestResponseHolder(request, response);
    SecurityContext context = repo.loadContext(holder);
    assertNotNull(context);//from   w w  w. jav a 2  s  .  c  o  m
    assertEquals(testToken, context.getAuthentication());
    // Won't actually be saved as it hasn't changed, but go through the use case anyway
    repo.saveContext(context, holder);
    assertEquals(context,
            request.getPortletSession().getAttribute("imTheContext", PortletSession.APPLICATION_SCOPE));
}

From source file:alpha.portal.webapp.listener.UserCounterListener.java

/**
 * Checks if is anonymous.//from ww  w  .  j  a  v  a  2  s . c  o  m
 * 
 * @return true, if is anonymous
 */
private boolean isAnonymous() {
    final AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
    final SecurityContext ctx = SecurityContextHolder.getContext();
    if (ctx != null) {
        final Authentication auth = ctx.getAuthentication();
        return resolver.isAnonymous(auth);
    }
    return true;
}