Search in sources :

Example 71 with SecurityContext

use of org.springframework.security.core.context.SecurityContext in project ORCID-Source by ORCID.

the class TokenTargetFilter method validateTargetRecord.

private void validateTargetRecord(String targetOrcid, ContainerRequest request) {
    // Verify if it is the owner of the token
    SecurityContext context = SecurityContextHolder.getContext();
    if (context != null && context.getAuthentication() != null) {
        Authentication authentication = context.getAuthentication();
        if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
            OAuth2Authentication oauth2Auth = (OAuth2Authentication) authentication;
            Authentication userAuthentication = oauth2Auth.getUserAuthentication();
            if (userAuthentication != null) {
                Object principal = userAuthentication.getPrincipal();
                if (principal instanceof ProfileEntity) {
                    ProfileEntity tokenOwner = (ProfileEntity) principal;
                    if (!targetOrcid.equals(tokenOwner.getId())) {
                        throwException(request);
                    }
                }
            }
        }
    }
}
Also used : OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity)

Example 72 with SecurityContext

use of org.springframework.security.core.context.SecurityContext in project ORCID-Source by ORCID.

the class BaseControllerUtilTest method getCurrentUserNoPrincipal.

@Test
public void getCurrentUserNoPrincipal() {
    SecurityContext context = mock(SecurityContext.class);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = mock(UsernamePasswordAuthenticationToken.class);
    when(context.getAuthentication()).thenReturn(usernamePasswordAuthenticationToken);
    assertNull(baseControllerUtil.getCurrentUser(context));
}
Also used : SecurityContext(org.springframework.security.core.context.SecurityContext) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 73 with SecurityContext

use of org.springframework.security.core.context.SecurityContext in project ORCID-Source by ORCID.

the class OAuthAuthorizeNotSignedInFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    if (OrcidUrlManager.getPathWithoutContextPath(request).equals("/oauth/authorize")) {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession();
        SecurityContext sci = null;
        if (session != null)
            sci = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
        if (baseControllerUtil.getCurrentUser(sci) == null) {
            String queryString = request.getQueryString();
            if (session != null)
                new HttpSessionRequestCache().saveRequest(request, response);
            if (!PojoUtil.isEmpty(queryString) && queryString.contains(OAUTH2_TWO_SCREENS_FEATURE_FLAG)) {
                response.sendRedirect(orcidUrlManager.getBaseUrl() + "/signin?oauth&" + queryString);
            } else {
                response.sendRedirect(orcidUrlManager.getBaseUrl() + "/oauth/signin?" + queryString);
            }
            return;
        }
    }
    chain.doFilter(req, res);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSession(javax.servlet.http.HttpSession) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) SecurityContext(org.springframework.security.core.context.SecurityContext) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 74 with SecurityContext

use of org.springframework.security.core.context.SecurityContext in project opennms by OpenNMS.

the class SurveillanceViewsUI method init.

/**
 * {@inheritDoc}
 */
@Override
protected void init(VaadinRequest request) {
    /**
     * Force the reload of the configuration
     */
    SurveillanceViewProvider.getInstance().load();
    /**
     * create a layout
     */
    VerticalLayout rootLayout = new VerticalLayout();
    rootLayout.setSpacing(true);
    /**
     * check query parameters for viewName, dashboard
     */
    String viewName = request.getParameter("viewName");
    boolean dashboard = request.getParameter("dashboard") != null && "true".equals(request.getParameter("dashboard"));
    /**
     * retrieve the username
     */
    String username = request.getRemoteUser();
    /**
     * now select the right view
     */
    View view;
    if (viewName == null) {
        view = m_surveillanceViewService.selectDefaultViewForUsername(username);
    } else {
        view = SurveillanceViewProvider.getInstance().getView(viewName);
    }
    /**
     * set the poll interval
     */
    setPollInterval(1000);
    /**
     * check for dashboard role
     */
    boolean isDashboardRole = true;
    SecurityContext context = SecurityContextHolder.getContext();
    if ((context != null) && !(context.toString().contains(org.opennms.web.api.Authentication.ROLE_DASHBOARD))) {
        isDashboardRole = false;
    }
    LOG.debug("User {} is in dashboard role? {}", username, isDashboardRole);
    /**
     * now construct the surveillance view/dashboard
     */
    rootLayout.addComponent(new SurveillanceView(view, m_surveillanceViewService, dashboard, !isDashboardRole));
    setContent(rootLayout);
    Page.getCurrent().getJavaScript().execute("function receiveMessage(event){\n" + "if(event.origin !== window.location.origin){ return; }\n" + "\n" + "event.source.postMessage( (document.getElementById('surveillance-window').offsetHeight + 17) + 'px', window.location.origin )\n" + "}\n" + "window.addEventListener(\"message\", receiveMessage, false);");
}
Also used : SecurityContext(org.springframework.security.core.context.SecurityContext) VerticalLayout(com.vaadin.ui.VerticalLayout) View(org.opennms.netmgt.config.surveillanceViews.View)

Example 75 with SecurityContext

use of org.springframework.security.core.context.SecurityContext in project head by mifos.

the class LoanBOTestUtils method createLoanAccount.

/**
     * Like
     * <b>createLoanAccountWithDisbursement(String, CustomerBO, AccountState, Date, LoanOfferingBO, int, Short)</b>
     * but differs in various ways.
     * <p/>
     * This test code needs to be refactored! By creating the loan with a
     * set of terms, then directly manipulating instance variables to completely
     * change the repayment schedule, it leaves the loan in an inconsistent
     * state, which leads one to suspect the validity of any of the 67 unit
     * tests that use it.
     *
     * It has been verified that setActionDate method calls in the loop below
     * will set the dates of the installments incorrectly for some if not all
     * cases. For certain classes of tests this doesn't matter, but for others
     * (involving verifying dates) it does. So BEWARE if you call down through
     * this method.
     *
     * @param globalNum
     */
public static LoanBO createLoanAccount(final String globalNum, final CustomerBO customer, final AccountState state, final Date startDate, final LoanOfferingBO loanOffering) {
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(startDate);
    MeetingBO meeting = TestObjectFactory.createLoanMeeting(customer.getCustomerMeeting().getMeeting());
    List<Date> meetingDates = TestObjectFactory.getMeetingDates(customer.getOfficeId(), meeting, 6);
    MifosCurrency currency = loanOffering.getCurrency();
    AmountFeeBO maintanenceFee = (AmountFeeBO) TestObjectFactory.createPeriodicAmountFee("Mainatnence Fee", FeeCategory.LOAN, "100", RecurrenceType.WEEKLY, Short.valueOf("1"));
    IntegrationTestObjectMother.saveFee(maintanenceFee);
    BigDecimal loanAmount = BigDecimal.valueOf(DEFAULT_LOAN_AMOUNT);
    BigDecimal minAllowedLoanAmount = loanAmount;
    BigDecimal maxAllowedLoanAmount = loanAmount;
    Double interestRate = loanOffering.getDefInterestRate();
    LocalDate disbursementDate = new LocalDate(meetingDates.get(0));
    int numberOfInstallments = 6;
    int minAllowedNumberOfInstallments = loanOffering.getEligibleInstallmentSameForAllLoan().getMaxNoOfInstall();
    int maxAllowedNumberOfInstallments = loanOffering.getEligibleInstallmentSameForAllLoan().getMaxNoOfInstall();
    int graceDuration = 0;
    Integer sourceOfFundId = null;
    Integer loanPurposeId = null;
    Integer collateralTypeId = null;
    String collateralNotes = null;
    String externalId = null;
    boolean repaymentScheduleIndependentOfCustomerMeeting = false;
    RecurringSchedule recurringSchedule = null;
    List<CreateAccountFeeDto> accountFees = new ArrayList<CreateAccountFeeDto>();
    accountFees.add(new CreateAccountFeeDto(maintanenceFee.getFeeId().intValue(), maintanenceFee.getFeeAmount().toString()));
    CreateLoanAccount createLoanAccount = new CreateLoanAccount(customer.getCustomerId(), loanOffering.getPrdOfferingId().intValue(), state.getValue().intValue(), loanAmount, minAllowedLoanAmount, maxAllowedLoanAmount, interestRate, disbursementDate, null, numberOfInstallments, minAllowedNumberOfInstallments, maxAllowedNumberOfInstallments, graceDuration, sourceOfFundId, loanPurposeId, collateralTypeId, collateralNotes, externalId, repaymentScheduleIndependentOfCustomerMeeting, recurringSchedule, accountFees, new ArrayList<CreateAccountPenaltyDto>());
    SecurityContext securityContext = new SecurityContextImpl();
    MifosUser principal = new MifosUserBuilder().nonLoanOfficer().withAdminRole().build();
    Authentication authentication = new TestingAuthenticationToken(principal, principal);
    securityContext.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContext);
    LoanBO loan = IntegrationTestObjectMother.createClientLoan(createLoanAccount);
    loan.updateDetails(TestUtils.makeUser());
    AccountFeesEntity accountPeriodicFee = new AccountFeesEntity(loan, maintanenceFee, (maintanenceFee).getFeeAmount().getAmountDoubleValue());
    AccountTestUtils.addAccountFees(accountPeriodicFee, loan);
    loan.setLoanMeeting(meeting);
    short i = 0;
    for (Date date : meetingDates) {
        LoanScheduleEntity actionDate = (LoanScheduleEntity) loan.getAccountActionDate(++i);
        actionDate.setPrincipal(new Money(currency, "100.0"));
        actionDate.setInterest(new Money(currency, "12.0"));
        // the following line overwrites the correct loan schedule dates
        // with dates that are not correct!
        actionDate.setActionDate(new java.sql.Date(date.getTime()));
        actionDate.setPaymentStatus(PaymentStatus.UNPAID);
        AccountTestUtils.addAccountActionDate(actionDate, loan);
        AccountFeesActionDetailEntity accountFeesaction = new LoanFeeScheduleEntity(actionDate, maintanenceFee, accountPeriodicFee, new Money(currency, "100.0"));
        setFeeAmountPaid(accountFeesaction, new Money(currency, "0.0"));
        actionDate.addAccountFeesAction(accountFeesaction);
    }
    loan.setCreatedBy(Short.valueOf("1"));
    loan.setCreatedDate(new Date(System.currentTimeMillis()));
    setLoanSummary(loan, currency);
    return loan;
}
Also used : SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) AccountFeesActionDetailEntity(org.mifos.accounts.business.AccountFeesActionDetailEntity) MeetingBO(org.mifos.application.meeting.business.MeetingBO) ArrayList(java.util.ArrayList) LocalDate(org.joda.time.LocalDate) Money(org.mifos.framework.util.helpers.Money) CreateLoanAccount(org.mifos.clientportfolio.newloan.applicationservice.CreateLoanAccount) CreateAccountPenaltyDto(org.mifos.dto.domain.CreateAccountPenaltyDto) CreateAccountFeeDto(org.mifos.dto.domain.CreateAccountFeeDto) AccountFeesEntity(org.mifos.accounts.business.AccountFeesEntity) MifosCurrency(org.mifos.application.master.business.MifosCurrency) GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) MifosUser(org.mifos.security.MifosUser) MifosUserBuilder(org.mifos.builders.MifosUserBuilder) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Date(java.util.Date) LocalDate(org.joda.time.LocalDate) AmountFeeBO(org.mifos.accounts.fees.business.AmountFeeBO) BigDecimal(java.math.BigDecimal) RecurringSchedule(org.mifos.clientportfolio.loan.service.RecurringSchedule) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext)

Aggregations

SecurityContext (org.springframework.security.core.context.SecurityContext)147 Test (org.junit.Test)65 Authentication (org.springframework.security.core.Authentication)63 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)46 SecurityContextImpl (org.springframework.security.core.context.SecurityContextImpl)46 MifosUser (org.mifos.security.MifosUser)38 MifosUserBuilder (org.mifos.builders.MifosUserBuilder)29 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)21 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)19 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)19 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)16 HttpServletResponse (javax.servlet.http.HttpServletResponse)15 Before (org.junit.Before)15 GrantedAuthority (org.springframework.security.core.GrantedAuthority)13 ArrayList (java.util.ArrayList)10 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 PrepareOnlyThisForTest (org.powermock.core.classloader.annotations.PrepareOnlyThisForTest)7 SessionDestroyedEvent (org.springframework.security.core.session.SessionDestroyedEvent)7 HttpSession (javax.servlet.http.HttpSession)6 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)6