Example usage for org.springframework.security.core Authentication getPrincipal

List of usage examples for org.springframework.security.core Authentication getPrincipal

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getPrincipal.

Prototype

Object getPrincipal();

Source Link

Document

The identity of the principal being authenticated.

Usage

From source file:eu.supersede.gr.rest.GameRest.java

@RequestMapping(value = "/{gameId}", method = RequestMethod.GET)
public HAHPGame getGame(Authentication authentication, @PathVariable Long gameId) {
    DatabaseUser currentUser = (DatabaseUser) authentication.getPrincipal();
    User user = users.findOne(currentUser.getUserId());
    HAHPGame g = games.findOne(gameId);//  w ww  .  j a v a 2 s .c  o m

    if (g == null) {
        throw new NotFoundException();
    }

    g.setCurrentPlayer(user);

    return g;
}

From source file:org.carewebframework.security.spring.AbstractSecurityService.java

/**
 * Returns whether the current context has authenticated
 * /*from  w w w.  j  a  va2  s.co m*/
 * @return boolean true if Authentication token is found and is not an Anonymous User
 */
@Override
public boolean isAuthenticated() {
    Authentication auth = getAuthentication();

    if (auth == null) {
        return false;
    }

    Object principal = auth.getPrincipal();
    String username = principal instanceof String ? (String) principal
            : ((org.springframework.security.core.userdetails.User) principal).getUsername();
    return (username != null && !username.equals(Constants.ANONYMOUS_USER));
}

From source file:org.deegree.securityproxy.wcs.responsefilter.clipping.WcsClippingResponseFilterManagerTest.java

private Authentication mockAuthenticationWithoutWcsUserPrincipal() {
    Authentication mockedAuthentication = mock(Authentication.class);
    when(mockedAuthentication.getPrincipal()).thenReturn(mock(UserDetails.class));
    return mockedAuthentication;
}

From source file:eu.supersede.dm.ga.rest.GAGameRest.java

@RequestMapping(value = "/games", method = RequestMethod.GET)
public List<HGAGameSummary> getGames(Authentication authentication, String roleName, Long processId) {
    Long userId = ((DatabaseUser) authentication.getPrincipal()).getUserId();
    return persistentDB.getGamesByRoleAndProcess(userId, roleName, processId);
}

From source file:eu.supersede.dm.ga.rest.GAGameRest.java

@RequestMapping(value = "/userranking", method = RequestMethod.GET)
public Map<Long, List<Long>> getUserRanking(Authentication authentication, @RequestParam Long gameId) {
    Long userId = ((DatabaseUser) authentication.getPrincipal()).getUserId();
    GAGameDetails gameDetails = persistentDB.getGameInfo(gameId);

    if (!gameDetails.getOpinionProviders().contains(userId)) {
        return new HashMap<>();
    } else {/* w  w  w.  j  a va  2 s  .c o m*/
        return persistentDB.getRanking(gameId, userId);
    }
}

From source file:com.company.project.web.controller.LoginTest.java

public void testCreateAuthentication() throws Exception {
    // http://spring.io/blog/2014/05/23/preview-spring-security-test-web-security
    // code to run as a specific user for every request to run a test with any of the approaches described in Method Based Security Testing
    //        mockMvc = MockMvcBuilders.webAppContextSetup(wac)
    //                .defaultRequest(get("/").with(userAdmin()))
    //                .addFilters(springSecurityFilterChain)
    //                .build();

    mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilter(springSecurityFilterChain, "/login*").build();

    // run as a user (which does not need to exist) 
    session = (MockHttpSession) mockMvc//from w ww.  j av  a2  s  .c  o m
            .perform(post("/login").with(user("admin").password("admin").roles("USER", "ADMIN")).with(csrf()))
            .andExpect(status().isOk())
            //.andExpect(redirectedUrl("/admin"))
            .andReturn().getRequest().getSession();

    assertNotNull(session);

    assertNotNull(session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY));
    assertNotNull(SecurityContextHolder.getContext().getAuthentication());

    Authentication auth = ((SecurityContextImpl) session
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
                    .getAuthentication();

    assertNotNull(auth);

    assertEquals("admin", ((UserDetails) auth.getPrincipal()).getUsername());
    assertEquals("ROLE_ADMIN", ((UserDetails) auth.getPrincipal()).getAuthorities().toArray()[0].toString());
    assertEquals("ROLE_USER", ((UserDetails) auth.getPrincipal()).getAuthorities().toArray()[1].toString());
}

From source file:es.osoco.grails.plugins.otp.authentication.OneTimePasswordAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    Assert.isInstanceOf(OneTimePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only OneTimePasswordAuthenticationToken is supported"));

    // Determine username
    String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();

    boolean cacheWasUsed = true;
    UserDetails user = getUserCache().getUserFromCache(username);

    if (user == null) {
        cacheWasUsed = false;// w  w  w  .  j  a  v a  2 s  . c  o  m

        try {
            user = retrieveUser(username, (OneTimePasswordAuthenticationToken) authentication);
        } catch (UsernameNotFoundException notFound) {

            if (hideUserNotFoundExceptions) {
                throw new BadCredentialsException(messages.getMessage(
                        "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
            throw notFound;
        }

        Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
    }

    try {
        getPreAuthenticationChecks().check(user);
        additionalAuthenticationChecks(user, (OneTimePasswordAuthenticationToken) authentication);
    } catch (AuthenticationException exception) {
        if (cacheWasUsed) {
            // There was a problem, so try again after checking
            // we're using latest data (i.e. not from the cache)
            cacheWasUsed = false;
            user = retrieveUser(username, (OneTimePasswordAuthenticationToken) authentication);
            getPreAuthenticationChecks().check(user);
            additionalAuthenticationChecks(user, (OneTimePasswordAuthenticationToken) authentication);
        } else {
            throw exception;
        }
    }

    getPostAuthenticationChecks().check(user);

    if (!cacheWasUsed) {
        getUserCache().putUserInCache(user);
    }

    Object principalToReturn = user;

    if (isForcePrincipalAsString()) {
        principalToReturn = user.getUsername();
    }

    return createSuccessAuthentication(principalToReturn, authentication, user);
}

From source file:de.knightsoftnet.validators.server.security.AuthSuccessHandler.java

@Override
public void onAuthenticationSuccess(final HttpServletRequest prequest, final HttpServletResponse presponse,
        final Authentication pauthentication) throws IOException, ServletException {
    this.csrfCookieHandler.setCookie(prequest, presponse);

    if (pauthentication.isAuthenticated()) {
        presponse.setStatus(HttpServletResponse.SC_OK);
        LOGGER.info("User is authenticated!");
        LOGGER.debug(pauthentication.toString());

        final PrintWriter writer = presponse.getWriter();
        this.mapper.writeValue(writer,
                this.userDetailsConverter.convert((UserDetails) pauthentication.getPrincipal()));
        writer.flush();/* w ww  .  j  ava  2 s  .c  om*/
    } else {
        presponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}