Example usage for org.springframework.security.core.userdetails User User

List of usage examples for org.springframework.security.core.userdetails User User

Introduction

In this page you can find the example usage for org.springframework.security.core.userdetails User User.

Prototype

public User(String username, String password, Collection<? extends GrantedAuthority> authorities) 

Source Link

Document

Calls the more complex constructor with all boolean arguments set to true .

Usage

From source file:org.opentides.util.SecurityUtilTest.java

@Test
public void testCurrentUserHasPermission() {
    List<GrantedAuthority> auths = new ArrayList<>();
    auths.add(new SimpleGrantedAuthority("ROLE1"));
    auths.add(new SimpleGrantedAuthority("ROLE2"));

    UserDetails userDetails = new User("admin", "password", auths);
    SessionUser sessionUser = new SessionUser(userDetails);
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(sessionUser,
            null, auths);/* w  w w . j a v  a2 s .  c  om*/
    SecurityContextHolder.getContext().setAuthentication(authentication);

    assertTrue(SecurityUtil.currentUserHasPermission("ROLE1"));
    assertFalse(SecurityUtil.currentUserHasPermission("ROLE3"));
}

From source file:com.kylinolap.rest.service.UserService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    HTableInterface htable = null;/*w  ww  .  j  a  va2 s  .co m*/
    try {
        htable = HBaseConnection.get(hbaseUrl).getTable(userTableName);

        Get get = new Get(Bytes.toBytes(username));
        get.addFamily(Bytes.toBytes(USER_AUTHORITY_FAMILY));
        Result result = htable.get(get);

        Collection<? extends GrantedAuthority> authorities = null;
        if (null != result && !result.isEmpty()) {
            byte[] gaBytes = result.getValue(Bytes.toBytes(USER_AUTHORITY_FAMILY),
                    Bytes.toBytes(USER_AUTHORITY_COLUMN));
            authorities = Arrays.asList(ugaSerializer.deserialize(gaBytes));
        } else {
            throw new UsernameNotFoundException("User " + username + " not found.");
        }

        return new User(username, "N/A", authorities);
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(htable);
    }
}

From source file:com.vivastream.security.oauth2.provider.DynamoDBUserDetailsManager.java

protected UserDetails buildUserFromItem(String username, String password,
        Collection<? extends GrantedAuthority> authorities, Map<String, AttributeValue> item) {
    return new User(username, password, authorities);
}

From source file:it.geosolutions.opensdi2.mvc.SessionController.java

/**
 * Creates a new session for the User in SecurityContext.
 * //from  w w w. j  a  v a2  s.c o m
 * @return
 * @throws ParseException 
 */
@RequestMapping(value = "/", method = RequestMethod.PUT)
@PreAuthorize("!hasRole('ROLE_ANONYMOUS')")
public @ResponseBody String createSession(@RequestParam(defaultValue = "", required = false) String expires)
        throws ParseException {
    Object user = getSecurityContext().getAuthentication().getPrincipal();
    if (user != null) {
        Calendar expiration = getExpiration(expires);
        UserSession session = null;
        if (user instanceof UserDetails) {
            session = new UserSessionImpl(null, (UserDetails) user, expiration);
        } else {
            User userData = new User(user.toString(), "",
                    getSecurityContext().getAuthentication().getAuthorities());
            session = new UserSessionImpl(null, userData, expiration);
        }
        return userSessionService.registerNewSession(session);
    }

    return null;
}

From source file:com.netflix.genie.web.security.saml.SAMLUserDetailsServiceImpl.java

/**
 * {@inheritDoc}//from   w w w  .  ja  v  a 2s .c  o  m
 */
@Override
public Object loadUserBySAML(final SAMLCredential credential) throws UsernameNotFoundException {
    final long start = System.nanoTime();
    try {
        if (credential == null) {
            throw new UsernameNotFoundException("No credential entered. Unable to get username.");
        }

        final String userAttributeName = this.samlProperties.getAttributes().getUser().getName();
        final String userId = credential.getAttributeAsString(userAttributeName);
        if (StringUtils.isBlank(userId)) {
            throw new UsernameNotFoundException("No user id found using attribute: " + userAttributeName);
        }

        // User exists. Give them at least USER role
        final List<GrantedAuthority> authorities = Lists.newArrayList(USER);

        // See if we can get any other roles
        final String groupAttributeName = this.samlProperties.getAttributes().getGroups().getName();
        final String adminGroup = this.samlProperties.getAttributes().getGroups().getAdmin();
        final String[] groups = credential.getAttributeAsStringArray(groupAttributeName);
        if (groups == null) {
            log.warn("No groups found. User will only get ROLE_USER by default.");
        } else if (Arrays.asList(groups).contains(adminGroup)) {
            authorities.add(ADMIN);
        }

        // For debugging what's available in the credential from the IDP
        if (log.isDebugEnabled()) {
            log.debug("Attributes:");
            credential.getAttributes().forEach(attribute -> {
                log.debug("Attribute: {}", attribute.getName());
                log.debug("Values: {}",
                        StringUtils.join(credential.getAttributeAsStringArray(attribute.getName()), ','));
            });
        }

        log.info("{} is logged in with authorities {}", userId, authorities);
        return new User(userId, "DUMMY", authorities);
    } finally {
        final long finished = System.nanoTime();
        this.loadTimer.record(finished - start, TimeUnit.NANOSECONDS);
    }
}

From source file:it.smartcommunitylab.aac.controller.LegacyNativeAuthController.java

protected ModelAndView processNativeAuth(Device device, HttpServletRequest request,
        HttpServletResponse response, String authority) throws UnsupportedEncodingException {
    Map<String, Object> model = new HashMap<String, Object>();
    String clientId = request.getParameter(OAuth2Utils.CLIENT_ID);
    if (clientId == null || clientId.isEmpty()) {
        model.put("message", "Missing client_id");
        return new ModelAndView("oauth_error", model);
    }/*from  ww  w  .  j  a va2  s  .c o m*/
    // each time create new OAuth request
    ClientAppBasic client = clientDetailsAdapter.getByClientId(clientId);
    AACOAuthRequest oauthRequest = new AACOAuthRequest(request, device, client.getScope(),
            client.getDisplayName());

    List<NameValuePair> pairs = URLEncodedUtils
            .parse(URI.create(request.getRequestURI() + "?" + request.getQueryString()), "UTF-8");

    String target = prepareRedirect(request, "/oauth/authorize");
    it.smartcommunitylab.aac.model.User userEntity = providerServiceAdapter.updateNativeUser(authority,
            request.getParameter("token"), toMap(pairs));
    List<GrantedAuthority> list = roleManager.buildAuthorities(userEntity);

    UserDetails user = new User(userEntity.getId().toString(), "", list);
    AbstractAuthenticationToken a = new AACAuthenticationToken(user, null, authority, list);
    a.setDetails(oauthRequest);
    SecurityContextHolder.getContext().setAuthentication(a);

    if (rememberMeServices != null) {
        rememberMeServices.loginSuccess(request, response, a);
    }

    return new ModelAndView("redirect:" + target);
}

From source file:de.uni_koeln.spinfo.maalr.login.SocialSignInAdapter.java

private UserDetails getUserDetails(MaalrUserInfo user) {
    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    GrantedAuthority authority = new SimpleGrantedAuthority(user.getRole().getRoleId());
    authorities.add(authority);/*from w  w w  .j av  a2 s.  co  m*/
    return new User(user.getLogin(), "ignored", authorities);
}

From source file:io.gravitee.management.idp.repository.authentication.RepositoryAuthenticationProvider.java

private UserDetails mapUserEntityToUserDetails(UserEntity userEntity) {
    List<GrantedAuthority> authorities = AuthorityUtils.NO_AUTHORITIES;
    if (userEntity.getRoles() != null && userEntity.getRoles().size() > 0) {

        authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
                userEntity.getRoles().stream().collect(Collectors.joining(",")));
    }//from ww w  .j av a  2  s.  c  om
    return new User(userEntity.getUsername(), "unknown", authorities);
}

From source file:com.jayway.restassured.module.mockmvc.SecuredControllerTest.java

@Test
public void spring_context_holder_is_cleared_after_failed_test_when_auth_is_statically_defined() {
    RestAssuredMockMvc.authentication = principal(
            new User("authorized_user", "password", Collections.<GrantedAuthority>emptyList()));

    try {/*from   ww  w .  j  av  a2 s .c om*/
        given().standaloneSetup(new SecuredController()).param("name", "Johan").when()
                .get("/springSecurityGreeting").then().statusCode(200)
                .body("content", equalTo("Hello, Johan!"));
    } finally {
        RestAssuredMockMvc.reset();
    }
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}

From source file:com.katsu.springframework.security.authentication.dni.HttpDniAuthenticationDao.java

private UserDetails createUserDetails(String dni, Collection<? extends GrantedAuthority> roles) {
    UserDetails result = new User(dni, "", roles);
    return result;
}