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:io.restassured.module.mockmvc.SecuredControllerTest.java

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

    try {/*from   w  ww  .ja  va2  s . co  m*/
        RestAssuredMockMvc.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:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java

@Test
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinWithUserTest()
        throws JsonProcessingException, JSONException {
    GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
    User user = new User("user", "pass", Collections.singleton(authority));
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, "pass",
            Collections.singleton(authority));
    String expectedJson = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\","
            + "\"principal\": {\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"user\", \"password\": \"pass\", \"accountNonExpired\": true, \"enabled\": true, "
            + "\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"authorities\": [\"java.util.Collections$UnmodifiableSet\","
            + "[{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}, \"credentials\": \"pass\","
            + "\"details\": null, \"name\": \"user\", \"authenticated\": true,"
            + "\"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
    String actualJson = buildObjectMapper().writeValueAsString(token);
    JSONAssert.assertEquals(expectedJson, actualJson, true);
}

From source file:eu.trentorise.smartcampus.permissionprovider.oauth.ClientCredentialsFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    String clientId = request.getParameter("client_id");
    String clientSecret = request.getParameter("client_secret");

    // If the request is already authenticated we can assume that this filter is not needed
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        return authentication;
    }/*  w ww  .  j  a  v a2 s  .  c  o m*/

    if (clientId == null) {
        throw new BadCredentialsException("No client credentials presented");
    }

    if (clientSecret == null) {
        clientSecret = "";
    }

    clientId = clientId.trim();

    //      UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret);
    ClientDetailsEntity clientDetails = clientDetailsRepository.findByClientId(clientId);
    boolean isTrusted = false;
    if (clientDetails.getAuthorities() != null) {
        for (GrantedAuthority ga : clientDetails.getAuthorities())
            if (Config.AUTHORITY.ROLE_CLIENT_TRUSTED.toString().equals(ga.getAuthority())) {
                isTrusted = true;
                break;
            }
    }
    if (!isTrusted) {
        throw new InvalidGrantException("Unauthorized client access by client " + clientId);
    }

    String clientSecretServer = clientDetails.getClientSecret();
    ClientAppInfo info = ClientAppInfo.convert(clientDetails.getAdditionalInformation());
    String clientSecretMobile = clientDetails.getClientSecretMobile();
    if (clientSecretMobile.equals(clientSecret) && !info.isNativeAppsAccess()) {
        throw new InvalidGrantException("Native app access is not enabled");
    }

    if (!clientSecretServer.equals(clientSecret) && !clientSecretMobile.equals(clientSecret)) {
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

    User user = new User(clientId, clientSecret, clientDetails.getAuthorities());

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user,
            clientSecretServer, user.getAuthorities());
    //        result.setDetails(authRequest.getDetails());
    return result;
}

From source file:org.alfresco.cacheserver.TestEdgeServer.java

@Test
public void test1() throws Exception {
    long nodeInternalId = 1l;
    String nodeId = GUID.generate();
    String nodeVersion = "1";
    String nodePath = "/1/2/3";
    byte[] bytes = "test".getBytes("UTF-8");
    String expectedMimeType = "text/plain";
    Long expectedSize = new Long(bytes.length);
    InputStream nodeContent = new ByteArrayInputStream(bytes);
    ReadableByteChannel channel = null;
    try {/*w w w . ja v a2 s . com*/
        contentGetter.addTestContent(nodeInternalId, nodeId, nodeVersion, nodePath, "test", expectedMimeType);

        edgeServer.repoContentUpdated(Node.build().nodeId(nodeId).versionLabel(nodeVersion).nodePath(nodePath),
                expectedMimeType, expectedSize, true);

        UserDetails userDetails = new User("admin", null, null);
        UserContext.setUser(userDetails);

        ContentReader content = edgeServer.getByNodeId(nodeId, nodeVersion, true);
        channel = content.getChannel();
        ByteBuffer bb = ByteBuffer.allocate(2048);
        channel.read(bb);
        assertNotNull(channel);
        assertEquals(expectedMimeType, content.getMimeType());
        assertEquals(expectedSize, content.getSize());

        ByteBuffer expectedNodeContent = ByteBuffer.wrap("test".getBytes("UTF-8"));

        compare(expectedNodeContent, bb);
    } finally {
        if (nodeContent != null) {
            nodeContent.close();
        }
        if (channel != null) {
            channel.close();
        }
        UserContext.setUser(null);
    }
}

From source file:com.rockagen.gnext.service.spring.security.extension.ExTokenAuthentication.java

/**
 * Get {@link org.springframework.security.core.userdetails.UserDetails} from token
 *
 * @param token token//from w  w  w  .j  a  v a2s .  c  om
 * @return {@link org.springframework.security.core.userdetails.UserDetails} if token authenticated,otherwise return null
 */
public UserDetails getUserDetailsFromToken(String token) {
    if (authenticated(token)) {
        // Load user
        Optional<AuthUser> user = authUserServ.load(Token.getUidFromToken(token));
        if (user.filter(AuthUser::enabled).isPresent()) {
            List<GrantedAuthority> authorities = new LinkedList<>();
            Set<AuthGroup> groups = user.get().getGroups();
            if (groups != null && groups.size() > 0) {
                groups.forEach(x -> x.getRoles()
                        .forEach(y -> authorities.add(new SimpleGrantedAuthority(y.getName().trim()))));
            }
            return new User(user.get().getUid(), "***", authorities);
        }
    }
    return null;
}

From source file:net.gplatform.sudoor.server.security.model.auth.SSAuth.java

public String register(String username, String password, String[] roles) {
    logger.debug("Register user: {} , with passwordEncoderEnabled: {}", username, passwordEncoderEnabled);
    String savedPw = password;//from w w w  . j a  va2s.c  o  m
    if (passwordEncoderEnabled) {
        savedPw = passwordEncoder.encode(password);
    }
    UserDetails ud = new User(username, savedPw, createSimpleGrantedAuthorities(roles));
    getUserDetailsManager().createUser(ud);
    return "SUCCESS";
}

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

@Test
public void statically_defined_auth_has_precedence_over_statically_defined_request_spec() {
    RestAssuredMockMvc.authentication = principal(
            new User("authorized_user", "password", Collections.<GrantedAuthority>emptyList()));
    RestAssuredMockMvc.requestSpecification = new MockMvcRequestSpecBuilder()
            .setAuth(authentication(new TestingAuthenticationToken("name", "pw"))).build();

    try {//from w w  w . j a v  a 2 s  . c om
        given().standaloneSetup(new SecuredController()).param("name", "Johan").when()
                .get("/springSecurityGreeting").then().statusCode(200)
                .body("content", equalTo("Hello, Johan!"));
    } finally {
        RestAssuredMockMvc.reset();
    }
}

From source file:uk.ac.serena.jws.plugins.SignUpPlugIn.java

public void createUser(WebSocketConnector aConnector, Token aToken) {

    if (mLog.isDebugEnabled())
        mLog.debug("Attempting to create new user.");

    // Create the response token, this includes the unique token-id.
    String username = aToken.getString(SignUpPlugInConstants.USER_NAME);
    String password = aToken.getString(SignUpPlugInConstants.PASSWORD);

    if (username == null) {
        sendErrorToken(aConnector, aToken, SignUpPlugInConstants.ERROR_NO_USERNAME_NOT_PROVIDED,
                SignUpPlugInConstants.ERROR_MSG_USERNAME_NOT_PROVIDED);
    } else if (password == null) {
        sendErrorToken(aConnector, aToken, SignUpPlugInConstants.ERROR_NO_PASSWORD_NOT_PROVIDED,
                SignUpPlugInConstants.ERROR_MSG_PASSWORD_NOT_PROVIDED);
    } else if (userDetailsService.userExists(username)) {
        sendErrorToken(aConnector, aToken, SignUpPlugInConstants.ERROR_NO_USERNAME_EXISTS,
                SignUpPlugInConstants.ERROR_MSG_USERNAME_EXISTS);
    } else {/* w  ww  .  j a  v  a  2 s .  co m*/
        // User() requires a list of authorities, which is not
        // actually needed here because we're using groups, which must be
        // manually assigned (below).
        List<GrantedAuthority> authorities = Collections.emptyList();

        // Does salting too.
        String hashedPassword = passwordEncoder.encode(password);

        // Create the new user account.
        User newUser = new User(username, hashedPassword, authorities);
        userDetailsService.createUser(newUser);

        // Assign new user to default groups.
        for (String group : defaultGroups)
            userDetailsService.addUserToGroup(username, group);

        // Send success response token back to the client.
        Token lResponse = createResponse(aToken);
        sendToken(aConnector, aConnector, lResponse);
    }
}

From source file:io.restassured.module.mockmvc.SecuredControllerTest.java

@Test
public void statically_defined_auth_has_precedence_over_statically_defined_request_spec() {
    RestAssuredMockMvc.authentication = RestAssuredMockMvc
            .principal(new User("authorized_user", "password", Collections.<GrantedAuthority>emptyList()));
    RestAssuredMockMvc.requestSpecification = new MockMvcRequestSpecBuilder()
            .setAuth(RestAssuredMockMvc.authentication(new TestingAuthenticationToken("name", "pw"))).build();

    try {// w w  w .j a  va  2 s  .  co m
        RestAssuredMockMvc.given().standaloneSetup(new SecuredController()).param("name", "Johan").when()
                .get("/springSecurityGreeting").then().statusCode(200)
                .body("content", equalTo("Hello, Johan!"));
    } finally {
        RestAssuredMockMvc.reset();
    }
}

From source file:eionet.transfer.controller.UserController.java

/**
 * Save user record to database.//  w  w  w. j  a  v  a 2  s .  c o  m
 *
 * @param user
 * @param bindingResult
 * @param model - contains attributes for the view
 * @return view name
 */
@RequestMapping("/edit")
public String editUser(Authorisation user, BindingResult bindingResult, ModelMap model) {
    ArrayList<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<SimpleGrantedAuthority>();
    if (user.getAuthorisations() != null) {
        for (String authority : user.getAuthorisations()) {
            grantedAuthorities.add(new SimpleGrantedAuthority(authority));
        }
    }
    User userDetails = new User(user.getUserId(), "", grantedAuthorities);
    userManagementService.updateUser(userDetails);
    model.addAttribute("message",
            "User " + user.getUserId() + " updated with " + rolesAsString(user.getAuthorisations()));
    return "redirect:view";
}