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.cloudifysource.security.CloudifyUser.java

public CloudifyUser(final String username, final String password, final String roles, final String authGroups) {

    Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
    Set<String> roleNames = splitAndTrim(roles, VALUES_SEPARATOR);
    for (String role : roleNames) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role));
    }/*from w ww .java 2 s .  com*/

    delegateUser = new User(username, password, grantedAuthorities);
    this.authGroups = splitAndTrim(authGroups, VALUES_SEPARATOR);
}

From source file:org.eclipse.hawkbit.ui.common.UserDetailsFormatter.java

@SuppressWarnings({ "squid:S1166" })
private static UserDetails loadUserByUsername(final String username) {
    final UserDetailsService userDetailsService = SpringContextHelper.getBean(UserDetailsService.class);
    try {//from w  ww.j a v  a2s. c  om
        return userDetailsService.loadUserByUsername(username);
    } catch (final UsernameNotFoundException e) {
        return new User(username, "", Collections.emptyList());
    }
}

From source file:org.finra.herd.service.helper.DefaultNotificationMessageBuilderTest.java

@SuppressWarnings("serial")
@Test/*from  ww w  .ja va 2 s  . c  o  m*/
public void testBuildBusinessObjectDataStatusChangeMessagesWithXmlPayloadWithUserInContext() throws Exception {
    Authentication originalAuthentication = SecurityContextHolder.getContext().getAuthentication();
    try {
        SecurityContextHolder.getContext().setAuthentication(new Authentication() {
            @Override
            public String getName() {
                return null;
            }

            @Override
            public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
            }

            @Override
            public boolean isAuthenticated() {
                return false;
            }

            @Override
            public Object getPrincipal() {
                List<GrantedAuthority> authorities = Collections.emptyList();
                return new User("testUsername", "", authorities);
            }

            @Override
            public Object getDetails() {
                return null;
            }

            @Override
            public Object getCredentials() {
                return null;
            }

            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                return null;
            }
        });

        // Test message building using 4 sub-partitions and a non-default user.
        testBuildBusinessObjectDataStatusChangeMessagesWithXmlPayloadHelper(SUBPARTITION_VALUES,
                "testUsername");
    } finally {
        // Restore the original authentication.
        SecurityContextHolder.getContext().setAuthentication(originalAuthentication);
    }
}

From source file:org.finra.herd.service.helper.notification.BusinessObjectDataStatusChangeMessageBuilderTest.java

@SuppressWarnings("serial")
@Test/*from  w  w  w . j  a v a  2 s.  c o m*/
public void testBuildBusinessObjectDataStatusChangeMessagesXmlPayloadUserInContext() throws Exception {
    Authentication originalAuthentication = SecurityContextHolder.getContext().getAuthentication();
    try {
        SecurityContextHolder.getContext().setAuthentication(new Authentication() {
            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                return null;
            }

            @Override
            public Object getCredentials() {
                return null;
            }

            @Override
            public Object getDetails() {
                return null;
            }

            @Override
            public String getName() {
                return null;
            }

            @Override
            public Object getPrincipal() {
                List<GrantedAuthority> authorities = Collections.emptyList();
                return new User("testUsername", "", authorities);
            }

            @Override
            public boolean isAuthenticated() {
                return false;
            }

            @Override
            public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
            }
        });

        // Test message building using 4 sub-partitions and a non-default user.
        testBuildBusinessObjectDataStatusChangeMessagesWithXmlPayloadHelper(SUBPARTITION_VALUES,
                "testUsername");
    } finally {
        // Restore the original authentication.
        SecurityContextHolder.getContext().setAuthentication(originalAuthentication);
    }
}

From source file:org.meruvian.yama.security.UserService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    net.bogor.itu.entity.admin.User u = userService.findByUsername(username);
    BackendUser user = u.getUser();//from   w  w w.  ja  v a2 s .  c  o m

    if (user != null) {
        UserDetails details = new User(user.getUsername(), user.getPassword(),
                Arrays.asList(new SimpleGrantedAuthority(user.getRole())));

        return details;
    }

    return null;
}

From source file:org.springframework.security.oauth.examples.sparklr.oauth.RemoteTokenServices.java

@SuppressWarnings("unchecked")
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));

    Map<String, Object> map = requestTokenInfo(checkTokenEndpointUrl, method, accessToken, headers);

    if (map.containsKey("error")) {
        logger.debug("check_token returned error: " + map.get("error"));
        throw new InvalidTokenException(accessToken);
    }//  ww  w  .  j ava2  s .c  o  m

    Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
    String remoteClientId = (String) map.get("client_id");

    Set<String> scope = new HashSet<String>();
    if (map.containsKey("scope")) {
        Collection<String> values = (Collection<String>) map.get("scope");
        scope.addAll(values);
    }
    DefaultAuthorizationRequest clientAuthentication = new DefaultAuthorizationRequest(remoteClientId, scope);

    if (map.containsKey("resource_ids") || map.containsKey("client_authorities")) {

        Set<String> resourceIds = new HashSet<String>();
        if (map.containsKey("resource_ids")) {
            Collection<String> values = (Collection<String>) map.get("resource_ids");
            resourceIds.addAll(values);
        }

        Set<GrantedAuthority> clientAuthorities = new HashSet<GrantedAuthority>();
        if (map.containsKey("client_authorities")) {
            Collection<String> values = (Collection<String>) map.get("client_authorities");
            clientAuthorities.addAll(getAuthorities(values));
        }

        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(remoteClientId);
        clientDetails.setResourceIds(resourceIds);
        clientDetails.setAuthorities(clientAuthorities);
        clientAuthentication.addClientDetails(clientDetails);
    }

    Set<GrantedAuthority> userAuthorities = new HashSet<GrantedAuthority>();
    if (map.containsKey("user_authorities")) {
        Collection<String> values = (Collection<String>) map.get("user_authorities");
        userAuthorities.addAll(getAuthorities(values));
    } else {
        // User authorities had better not be empty or we might mistake user for unauthenticated
        userAuthorities.addAll(getAuthorities(scope));
    }

    String username = (String) map.get("username");
    UserDetails user = new User(username, "", userAuthorities);
    Authentication userAuthentication = new UsernamePasswordAuthenticationToken(user, null, userAuthorities);

    clientAuthentication.setApproved(true);
    return new OAuth2Authentication(clientAuthentication, userAuthentication);
}

From source file:org.springframework.security.web.authentication.www.DigestAuthenticationFilterTests.java

@Before
public void setUp() {
    SecurityContextHolder.clearContext();

    // Create User Details Service
    UserDetailsService uds = new UserDetailsService() {

        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            return new User("rod,ok", "koala", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
        }/*from  ww w.  j  a v  a 2 s.  c  om*/
    };

    DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
    ep.setRealmName(REALM);
    ep.setKey(KEY);

    filter = new DigestAuthenticationFilter();
    filter.setUserDetailsService(uds);
    filter.setAuthenticationEntryPoint(ep);

    request = new MockHttpServletRequest("GET", REQUEST_URI);
    request.setServletPath(REQUEST_URI);
}

From source file:rusch.megan6server.TextFileAuthentication.java

/**Load credentials from file
 * //from   w  w  w. ja va 2  s .c  om
 * @throws IOException
 */
private synchronized void load() throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(credentialsFile));
    String aLine;
    while ((aLine = reader.readLine()) != null) {
        if (aLine.startsWith("#")) {
            continue;
        }
        if (aLine.length() == 0) {
            continue;
        }
        String[] splits = aLine.split("\\t");
        UserDetails user = new User(splits[0], splits[1],
                getAuthorities(Boolean.valueOf(splits[2]), Boolean.valueOf(splits[3])));
        name2tokens.put(splits[0], user);
    }
    reader.close();
}

From source file:rusch.megan6server.TextFileAuthentication.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserDetails ud = name2tokens.get(username);

    if (ud == null) {
        throw new UsernameNotFoundException("No user with name: " + username);
    }/*  ww  w .j a v a2s  .  co m*/
    return new User(ud.getUsername(), ud.getPassword(), ud.getAuthorities());

}

From source file:rusch.megan6server.TextFileAuthentication.java

@Override
public void updateUser(UserDetails user) {
    synchronized (name2tokens) {
        try {//  w  w  w. j  a v  a2 s . c o  m
            name2tokens.put(user.getUsername(),
                    new User(user.getUsername(), md5(user.getPassword()), user.getAuthorities()));
        } catch (NoSuchAlgorithmException e) {
            logger.warn("MD5 algorithm not found. Can not happen...");
        }
        persist();
    }

}