Search in sources :

Example 1 with AnonymousAuthenticationToken

use of org.springframework.security.authentication.AnonymousAuthenticationToken in project ORCID-Source by ORCID.

the class StatsApiServiceBaseImplTest method init.

@Before
public void init() {
    // create our mock data
    List<StatisticValuesEntity> statsTimelineValues = new ArrayList<StatisticValuesEntity>();
    List<StatisticValuesEntity> statsSummaryValues = new ArrayList<StatisticValuesEntity>();
    StatisticValuesEntity a = new StatisticValuesEntity();
    a.setId(1l);
    a.setStatisticName(StatisticsEnum.KEY_LIVE_IDS.value());
    a.setStatisticValue(100l);
    StatisticKeyEntity akey = new StatisticKeyEntity();
    akey.setGenerationDate(new Date(2000, 1, 1));
    akey.setId(200L);
    a.setKey(akey);
    StatisticValuesEntity b = new StatisticValuesEntity();
    b.setId(1l);
    b.setStatisticName(StatisticsEnum.KEY_LIVE_IDS.value());
    b.setStatisticValue(101l);
    StatisticKeyEntity bkey = new StatisticKeyEntity();
    bkey.setGenerationDate(new Date(1999, 1, 1));
    bkey.setId(201L);
    b.setKey(bkey);
    StatisticValuesEntity c = new StatisticValuesEntity();
    c.setId(1l);
    c.setStatisticName(StatisticsEnum.KEY_NUMBER_OF_WORKS.value());
    c.setStatisticValue(102l);
    c.setKey(akey);
    statsTimelineValues.add(a);
    statsTimelineValues.add(b);
    statsSummaryValues.add(a);
    statsSummaryValues.add(c);
    // mock the methods used
    when(statisticsDao.getLatestKey()).thenReturn(akey);
    when(statisticsDao.getStatistic(StatisticsEnum.KEY_LIVE_IDS.value())).thenReturn(statsTimelineValues);
    when(statisticsDao.getStatistic(200l)).thenReturn(statsSummaryValues);
    // mock the methods used
    StatisticKeyEntity key200 = new StatisticKeyEntity();
    key200.setId(200L);
    key200.setGenerationDate(new Date(2000, 1, 1));
    StatisticKeyEntity key201 = new StatisticKeyEntity();
    key201.setId(201L);
    key201.setGenerationDate(new Date(1999, 1, 1));
    when(statisticsDao.getKey(200L)).thenReturn(key200);
    when(statisticsDao.getKey(201L)).thenReturn(key201);
    TargetProxyHelper.injectIntoProxy(statsManagerReadOnly, "statisticsDaoReadOnly", statisticsDao);
    // setup security context
    ArrayList<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
    roles.add(new SimpleGrantedAuthority("ROLE_ANONYMOUS"));
    Authentication auth = new AnonymousAuthenticationToken("anonymous", "anonymous", roles);
    SecurityContextHolder.getContext().setAuthentication(auth);
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) StatisticValuesEntity(org.orcid.statistics.jpa.entities.StatisticValuesEntity) StatisticKeyEntity(org.orcid.statistics.jpa.entities.StatisticKeyEntity) Authentication(org.springframework.security.core.Authentication) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) Date(java.util.Date) Before(org.junit.Before)

Example 2 with AnonymousAuthenticationToken

use of org.springframework.security.authentication.AnonymousAuthenticationToken in project midpoint by Evolveum.

the class MidpointRestSecurityQuestionsAuthenticator method createAuthenticationContext.

@Override
protected SecurityQuestionsAuthenticationContext createAuthenticationContext(AuthorizationPolicy policy, ContainerRequestContext requestCtx) {
    JsonFactory f = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(f);
    JsonNode node = null;
    try {
        node = mapper.readTree(policy.getAuthorization());
    } catch (IOException e) {
        RestServiceUtil.createSecurityQuestionAbortMessage(requestCtx, "{" + USER_CHALLENGE + "}");
        return null;
    }
    JsonNode userNameNode = node.findPath("user");
    if (userNameNode instanceof MissingNode) {
        RestServiceUtil.createSecurityQuestionAbortMessage(requestCtx, "{" + USER_CHALLENGE + "}");
        return null;
    }
    String userName = userNameNode.asText();
    policy.setUserName(userName);
    JsonNode answerNode = node.findPath("answer");
    if (answerNode instanceof MissingNode) {
        SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("restapi", "REST", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
        SearchResultList<PrismObject<UserType>> users = null;
        try {
            users = searchUser(userName);
        } finally {
            SecurityContextHolder.getContext().setAuthentication(null);
        }
        if (users.size() != 1) {
            requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Security question authentication failed. Incorrect username and/or password").build());
            return null;
        }
        PrismObject<UserType> user = users.get(0);
        PrismContainer<SecurityQuestionAnswerType> questionAnswerContainer = user.findContainer(SchemaConstants.PATH_SECURITY_QUESTIONS_QUESTION_ANSWER);
        if (questionAnswerContainer == null || questionAnswerContainer.isEmpty()) {
            requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Security question authentication failed. Incorrect username and/or password").build());
            return null;
        }
        String questionChallenge = "";
        List<SecurityQuestionDefinitionType> questions = null;
        try {
            SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("restapi", "REST", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
            questions = getQuestions(user);
        } finally {
            SecurityContextHolder.getContext().setAuthentication(null);
        }
        Collection<SecurityQuestionAnswerType> questionAnswers = questionAnswerContainer.getRealValues();
        Iterator<SecurityQuestionAnswerType> questionAnswerIterator = questionAnswers.iterator();
        while (questionAnswerIterator.hasNext()) {
            SecurityQuestionAnswerType questionAnswer = questionAnswerIterator.next();
            SecurityQuestionDefinitionType question = questions.stream().filter(q -> q.getIdentifier().equals(questionAnswer.getQuestionIdentifier())).findFirst().get();
            String challenge = QUESTION.replace(Q_ID, question.getIdentifier());
            questionChallenge += challenge.replace(Q_TXT, question.getQuestionText());
            if (questionAnswerIterator.hasNext()) {
                questionChallenge += ",";
            }
        }
        String userChallenge = USER_CHALLENGE.replace("username", userName);
        String challenge = "{" + userChallenge + ", \"answer\" : [" + questionChallenge + "]}";
        RestServiceUtil.createSecurityQuestionAbortMessage(requestCtx, challenge);
        return null;
    }
    ArrayNode answers = (ArrayNode) answerNode;
    Iterator<JsonNode> answersList = answers.elements();
    Map<String, String> questionAnswers = new HashMap<>();
    while (answersList.hasNext()) {
        JsonNode answer = answersList.next();
        String questionId = answer.findPath("qid").asText();
        String questionAnswer = answer.findPath("qans").asText();
        questionAnswers.put(questionId, questionAnswer);
    }
    return new SecurityQuestionsAuthenticationContext(userName, questionAnswers);
}
Also used : SecurityQuestionDefinitionType(com.evolveum.midpoint.xml.ns._public.common.common_3.SecurityQuestionDefinitionType) HashMap(java.util.HashMap) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonNode(com.fasterxml.jackson.databind.JsonNode) MissingNode(com.fasterxml.jackson.databind.node.MissingNode) IOException(java.io.IOException) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) PrismObject(com.evolveum.midpoint.prism.PrismObject) SecurityQuestionsAuthenticationContext(com.evolveum.midpoint.model.api.context.SecurityQuestionsAuthenticationContext) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType) SecurityQuestionAnswerType(com.evolveum.midpoint.xml.ns._public.common.common_3.SecurityQuestionAnswerType) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 3 with AnonymousAuthenticationToken

use of org.springframework.security.authentication.AnonymousAuthenticationToken in project ORCID-Source by ORCID.

the class SecurityContextTestUtils method setUpSecurityContextForAnonymous.

public static void setUpSecurityContextForAnonymous() {
    SecurityContextImpl securityContext = new SecurityContextImpl();
    ArrayList<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("ROLE_ANONYMOUS"));
    AnonymousAuthenticationToken anonToken = new AnonymousAuthenticationToken("testKey", "testToken", authorities);
    securityContext.setAuthentication(anonToken);
    SecurityContextHolder.setContext(securityContext);
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken)

Example 4 with AnonymousAuthenticationToken

use of org.springframework.security.authentication.AnonymousAuthenticationToken in project spring-security-oauth by spring-projects.

the class AccessTokenProviderChainTests method testAnonymousUser.

@Test(expected = InsufficientAuthenticationException.class)
public void testAnonymousUser() throws Exception {
    AccessTokenProviderChain chain = new AccessTokenProviderChain(Arrays.asList(new StubAccessTokenProvider()));
    SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("foo", "bar", user.getAuthorities()));
    AccessTokenRequest request = new DefaultAccessTokenRequest();
    OAuth2AccessToken token = chain.obtainAccessToken(resource, request);
    assertNotNull(token);
}
Also used : DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) Test(org.junit.Test)

Example 5 with AnonymousAuthenticationToken

use of org.springframework.security.authentication.AnonymousAuthenticationToken in project webofneeds by researchstudio-sat.

the class RestUserController method isSignedIn.

/**
 * Method only accessible if the user's still signed in / the session's still valid -> Use it to check the session cookie.
 */
// * @param user user object
// * @param request
// * @param response
// * @return
// 
@ResponseBody
@RequestMapping(value = "/isSignedIn", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
@Transactional(propagation = Propagation.REQUIRED)
public // public ResponseEntity isSignedIn(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
ResponseEntity isSignedIn(HttpServletRequest request, HttpServletResponse response) {
    // Execution will only get here, if the session is still valid, so sending OK here is enough. Spring sends an error
    // code by itself if the session isn't valid any more
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = null;
    if (context != null) {
        authentication = context.getAuthentication();
    }
    if (authentication == null) {
        authentication = rememberMeServices.autoLogin(request, response);
    } else if (authentication instanceof AnonymousAuthenticationToken) {
        // if we're anonymous, try to see if we can reactivate a remember-me session
        Authentication anonAuth = authentication;
        authentication = rememberMeServices.autoLogin(request, response);
        if (authentication == null) {
            authentication = anonAuth;
        }
    }
    if (authentication == null) {
        return new ResponseEntity("\"User not signed in.\"", HttpStatus.UNAUTHORIZED);
    } else if ("anonymousUser".equals(authentication.getPrincipal())) {
        return new ResponseEntity("\"User not signed in.\"", HttpStatus.UNAUTHORIZED);
    } else {
        User user = ((KeystoreEnabledUserDetails) authentication.getPrincipal()).getUser();
        Map values = new HashMap<String, String>();
        values.put("username", user.getUsername());
        values.put("authorities", user.getAuthorities());
        values.put("role", user.getRole());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return new ResponseEntity<Map>(values, HttpStatus.OK);
    }
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) User(won.owner.model.User) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) CheapInsecureRandomString(won.protocol.util.CheapInsecureRandomString) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) Map(java.util.Map) HashMap(java.util.HashMap) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

AnonymousAuthenticationToken (org.springframework.security.authentication.AnonymousAuthenticationToken)95 Authentication (org.springframework.security.core.Authentication)43 Test (org.junit.jupiter.api.Test)22 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)17 ArrayList (java.util.ArrayList)15 GrantedAuthority (org.springframework.security.core.GrantedAuthority)14 SecurityContext (org.springframework.security.core.context.SecurityContext)14 MidpointAuthentication (com.evolveum.midpoint.authentication.api.config.MidpointAuthentication)8 Test (org.junit.Test)7 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)7 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)7 ModuleAuthentication (com.evolveum.midpoint.authentication.api.config.ModuleAuthentication)6 Before (org.junit.Before)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 PreAuthenticatedAuthenticationToken (org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 AccessDeniedException (org.springframework.security.access.AccessDeniedException)3