Search in sources :

Example 1 with User

use of com.alibaba.nacos.plugin.auth.impl.persistence.User in project nacos by alibaba.

the class LdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();
    if (isAdmin(username)) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (PasswordEncoderUtil.matches(password, userDetails.getPassword())) {
            return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
        } else {
            return null;
        }
    }
    try {
        if (!ldapLogin(username, password)) {
            return null;
        }
    } catch (Exception e) {
        Loggers.AUTH.error("[LDAP-LOGIN] failed", e);
        return null;
    }
    UserDetails userDetails;
    try {
        userDetails = userDetailsService.loadUserByUsername(LDAP_PREFIX + username);
    } catch (UsernameNotFoundException exception) {
        String nacosPassword = PasswordEncoderUtil.encode(DEFAULT_PASSWORD);
        userDetailsService.createUser(LDAP_PREFIX + username, nacosPassword);
        User user = new User();
        user.setUsername(LDAP_PREFIX + username);
        user.setPassword(nacosPassword);
        userDetails = new NacosUserDetails(user);
    }
    return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) NacosUserDetails(com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails) UserDetails(org.springframework.security.core.userdetails.UserDetails) User(com.alibaba.nacos.plugin.auth.impl.persistence.User) NacosUserDetails(com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AuthenticationException(org.springframework.security.core.AuthenticationException)

Example 2 with User

use of com.alibaba.nacos.plugin.auth.impl.persistence.User in project nacos by alibaba.

the class UserController method updatePassword.

/**
 * Update password.
 *
 * @param oldPassword old password
 * @param newPassword new password
 * @return Code 200 if update successfully, Code 401 if old password invalid, otherwise 500
 */
@PutMapping("/password")
@Deprecated
public RestResult<String> updatePassword(@RequestParam(value = "oldPassword") String oldPassword, @RequestParam(value = "newPassword") String newPassword) {
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String username = ((UserDetails) principal).getUsername();
    User user = userDetailsService.getUserFromDatabase(username);
    String password = user.getPassword();
    // TODO: throw out more fine grained exceptions
    try {
        if (PasswordEncoderUtil.matches(oldPassword, password)) {
            userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword));
            return RestResultUtils.success("Update password success");
        }
        return RestResultUtils.failed(HttpStatus.UNAUTHORIZED.value(), "Old password is invalid");
    } catch (Exception e) {
        return RestResultUtils.failed(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Update userpassword failed");
    }
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) NacosUser(com.alibaba.nacos.plugin.auth.impl.users.NacosUser) User(com.alibaba.nacos.plugin.auth.impl.persistence.User) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AccessException(com.alibaba.nacos.plugin.auth.exception.AccessException) IOException(java.io.IOException) PutMapping(org.springframework.web.bind.annotation.PutMapping)

Example 3 with User

use of com.alibaba.nacos.plugin.auth.impl.persistence.User in project nacos by alibaba.

the class UserController method updateUser.

/**
 * Update an user.
 *
 * @param username    username of user
 * @param newPassword new password of user
 * @param response    http response
 * @param request     http request
 * @return ok if update succeed
 * @throws IllegalArgumentException if user not exist or oldPassword is incorrect
 * @since 1.2.0
 */
@PutMapping
@Secured(resource = AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, action = ActionTypes.WRITE)
public Object updateUser(@RequestParam String username, @RequestParam String newPassword, HttpServletResponse response, HttpServletRequest request) throws IOException {
    // admin or same user
    if (!hasPermission(username, request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "authorization failed!");
        return null;
    }
    User user = userDetailsService.getUserFromDatabase(username);
    if (user == null) {
        throw new IllegalArgumentException("user " + username + " not exist!");
    }
    userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword));
    return RestResultUtils.success("update user ok!");
}
Also used : NacosUser(com.alibaba.nacos.plugin.auth.impl.users.NacosUser) User(com.alibaba.nacos.plugin.auth.impl.persistence.User) Secured(com.alibaba.nacos.auth.annotation.Secured) PutMapping(org.springframework.web.bind.annotation.PutMapping)

Example 4 with User

use of com.alibaba.nacos.plugin.auth.impl.persistence.User in project nacos by alibaba.

the class User_ITCase method createUpdateDeleteUser.

@Test
public void createUpdateDeleteUser() {
    login();
    // Create a user:
    ResponseEntity<String> response = request("/nacos/v1/auth/users", Params.newParams().appendParam("username", "username1").appendParam("password", "password1").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Query a user:
    response = request("/nacos/v1/auth/users", Params.newParams().appendParam("pageNo", "1").appendParam("pageSize", String.valueOf(Integer.MAX_VALUE)).appendParam("accessToken", accessToken).done(), String.class);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    Page<User> userPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<User>>() {
    });
    Assert.assertNotNull(userPage);
    Assert.assertNotNull(userPage.getPageItems());
    Assert.assertTrue(userPage.getPageItems().size() > 0);
    boolean found = false;
    for (User user : userPage.getPageItems()) {
        if ("username1".equals(user.getUsername()) && PasswordEncoderUtil.matches("password1", user.getPassword())) {
            found = true;
            break;
        }
    }
    Assert.assertTrue(found);
    // Update a user:
    response = request("/nacos/v1/auth/users", Params.newParams().appendParam("username", "username1").appendParam("newPassword", "password2").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.PUT);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Query a user:
    response = request("/nacos/v1/auth/users", Params.newParams().appendParam("pageNo", "1").appendParam("pageSize", String.valueOf(Integer.MAX_VALUE)).appendParam("accessToken", accessToken).done(), String.class);
    userPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<User>>() {
    });
    Assert.assertNotNull(userPage);
    Assert.assertNotNull(userPage.getPageItems());
    Assert.assertTrue(userPage.getPageItems().size() > 0);
    found = false;
    for (User user : userPage.getPageItems()) {
        if ("username1".equals(user.getUsername()) && PasswordEncoderUtil.matches("password2", user.getPassword())) {
            found = true;
            break;
        }
    }
    Assert.assertTrue(found);
    // Delete a user:
    response = request("/nacos/v1/auth/users", Params.newParams().appendParam("username", "username1").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Query a user:
    response = request("/nacos/v1/auth/users", Params.newParams().appendParam("pageNo", "1").appendParam("pageSize", String.valueOf(Integer.MAX_VALUE)).appendParam("accessToken", accessToken).done(), String.class);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    userPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<User>>() {
    });
    Assert.assertNotNull(userPage);
    Assert.assertNotNull(userPage.getPageItems());
    Assert.assertTrue(userPage.getPageItems().size() > 0);
    found = false;
    for (User user : userPage.getPageItems()) {
        if ("username1".equals(user.getUsername())) {
            found = true;
            break;
        }
    }
    Assert.assertFalse(found);
}
Also used : User(com.alibaba.nacos.plugin.auth.impl.persistence.User) Page(com.alibaba.nacos.config.server.model.Page) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HttpClient4Test(com.alibaba.nacos.test.base.HttpClient4Test) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 5 with User

use of com.alibaba.nacos.plugin.auth.impl.persistence.User in project nacos by alibaba.

the class NacosUserDetailsServiceImpl method reload.

@Scheduled(initialDelay = 5000, fixedDelay = 15000)
private void reload() {
    try {
        Page<User> users = getUsersFromDatabase(1, Integer.MAX_VALUE);
        if (users == null) {
            return;
        }
        Map<String, User> map = new ConcurrentHashMap<>(16);
        for (User user : users.getPageItems()) {
            map.put(user.getUsername(), user);
        }
        userMap = map;
    } catch (Exception e) {
        Loggers.AUTH.warn("[LOAD-USERS] load failed", e);
    }
}
Also used : User(com.alibaba.nacos.plugin.auth.impl.persistence.User) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Aggregations

User (com.alibaba.nacos.plugin.auth.impl.persistence.User)6 NacosUser (com.alibaba.nacos.plugin.auth.impl.users.NacosUser)3 Secured (com.alibaba.nacos.auth.annotation.Secured)2 UserDetails (org.springframework.security.core.userdetails.UserDetails)2 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)2 PutMapping (org.springframework.web.bind.annotation.PutMapping)2 Page (com.alibaba.nacos.config.server.model.Page)1 AccessException (com.alibaba.nacos.plugin.auth.exception.AccessException)1 NacosUserDetails (com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails)1 HttpClient4Test (com.alibaba.nacos.test.base.HttpClient4Test)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 IOException (java.io.IOException)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Test (org.junit.Test)1 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)1 Scheduled (org.springframework.scheduling.annotation.Scheduled)1 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)1 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)1 AuthenticationException (org.springframework.security.core.AuthenticationException)1 PostMapping (org.springframework.web.bind.annotation.PostMapping)1