Search in sources :

Example 1 with NacosUser

use of com.alibaba.nacos.console.security.nacos.users.NacosUser in project nacos by alibaba.

the class UserController method login.

/**
 * Login to Nacos
 *
 * <p>This methods uses username and password to require a new token.
 *
 * @param username username of user
 * @param password password
 * @param response http response
 * @param request  http request
 * @return new token of the user
 * @throws AccessException if user info is incorrect
 */
@PostMapping("/login")
public Object login(@RequestParam String username, @RequestParam String password, HttpServletResponse response, HttpServletRequest request) throws AccessException {
    if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType()) || AuthSystemTypes.LDAP.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) {
        NacosUser user = (NacosUser) authManager.login(request);
        response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, NacosAuthConfig.TOKEN_PREFIX + user.getToken());
        ObjectNode result = JacksonUtils.createEmptyJsonNode();
        result.put(Constants.ACCESS_TOKEN, user.getToken());
        result.put(Constants.TOKEN_TTL, authConfigs.getTokenValidityInSeconds());
        result.put(Constants.GLOBAL_ADMIN, user.isGlobalAdmin());
        result.put(Constants.USERNAME, user.getUserName());
        return result;
    }
    // create Authentication class through username and password, the implement class is UsernamePasswordAuthenticationToken
    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
    try {
        // use the method authenticate of AuthenticationManager(default implement is ProviderManager) to valid Authentication
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        // bind SecurityContext to Authentication
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // generate Token
        String token = jwtTokenManager.createToken(authentication);
        // write Token to Http header
        response.addHeader(NacosAuthConfig.AUTHORIZATION_HEADER, "Bearer " + token);
        return RestResultUtils.success("Bearer " + token);
    } catch (BadCredentialsException authentication) {
        return RestResultUtils.failed(HttpStatus.UNAUTHORIZED.value(), null, "Login failed");
    }
}
Also used : NacosUser(com.alibaba.nacos.console.security.nacos.users.NacosUser) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 2 with NacosUser

use of com.alibaba.nacos.console.security.nacos.users.NacosUser in project nacos by alibaba.

the class NacosAuthManager method login.

@Override
public User login(Object request) throws AccessException {
    HttpServletRequest req = (HttpServletRequest) request;
    String token = resolveToken(req);
    if (StringUtils.isBlank(token)) {
        throw new AccessException("user not found!");
    }
    try {
        tokenManager.validateToken(token);
    } catch (ExpiredJwtException e) {
        throw new AccessException("token expired!");
    } catch (Exception e) {
        throw new AccessException("token invalid!");
    }
    Authentication authentication = tokenManager.getAuthentication(token);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    String username = authentication.getName();
    NacosUser user = new NacosUser();
    user.setUserName(username);
    user.setToken(token);
    List<RoleInfo> roleInfoList = roleService.getRoles(username);
    if (roleInfoList != null) {
        for (RoleInfo roleInfo : roleInfoList) {
            if (roleInfo.getRole().equals(NacosRoleServiceImpl.GLOBAL_ADMIN_ROLE)) {
                user.setGlobalAdmin(true);
                break;
            }
        }
    }
    req.getSession().setAttribute(RequestUtil.NACOS_USER_KEY, user);
    return user;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AccessException(com.alibaba.nacos.auth.exception.AccessException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) NacosUser(com.alibaba.nacos.console.security.nacos.users.NacosUser) RoleInfo(com.alibaba.nacos.config.server.auth.RoleInfo) Authentication(org.springframework.security.core.Authentication) AccessException(com.alibaba.nacos.auth.exception.AccessException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) AuthenticationException(org.springframework.security.core.AuthenticationException)

Example 3 with NacosUser

use of com.alibaba.nacos.console.security.nacos.users.NacosUser in project nacos by alibaba.

the class NacosAuthManager method loginRemote.

@Override
public User loginRemote(Object request) throws AccessException {
    Request req = (Request) request;
    String token = resolveToken(req);
    if (StringUtils.isBlank(token)) {
        throw new AccessException("user not found!");
    }
    try {
        tokenManager.validateToken(token);
    } catch (ExpiredJwtException e) {
        throw new AccessException("token expired!");
    } catch (Exception e) {
        throw new AccessException("token invalid!");
    }
    Authentication authentication = tokenManager.getAuthentication(token);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    String username = authentication.getName();
    NacosUser user = new NacosUser();
    user.setUserName(username);
    user.setToken(token);
    List<RoleInfo> roleInfoList = roleService.getRoles(username);
    if (roleInfoList != null) {
        for (RoleInfo roleInfo : roleInfoList) {
            if (roleInfo.getRole().equals(NacosRoleServiceImpl.GLOBAL_ADMIN_ROLE)) {
                user.setGlobalAdmin(true);
                break;
            }
        }
    }
    return user;
}
Also used : AccessException(com.alibaba.nacos.auth.exception.AccessException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) NacosUser(com.alibaba.nacos.console.security.nacos.users.NacosUser) RoleInfo(com.alibaba.nacos.config.server.auth.RoleInfo) Authentication(org.springframework.security.core.Authentication) Request(com.alibaba.nacos.api.remote.request.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) AccessException(com.alibaba.nacos.auth.exception.AccessException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) AuthenticationException(org.springframework.security.core.AuthenticationException)

Example 4 with NacosUser

use of com.alibaba.nacos.console.security.nacos.users.NacosUser in project nacos by alibaba.

the class UserControllerTest method setUp.

@Before
public void setUp() throws Exception {
    userController = new UserController();
    user = new NacosUser();
    user.setUserName("nacos");
    user.setGlobalAdmin(true);
    user.setToken("1234567890");
    injectObject("authConfigs", authConfigs);
    injectObject("authManager", authManager);
}
Also used : NacosUser(com.alibaba.nacos.console.security.nacos.users.NacosUser) Before(org.junit.Before)

Aggregations

NacosUser (com.alibaba.nacos.console.security.nacos.users.NacosUser)4 Authentication (org.springframework.security.core.Authentication)3 AccessException (com.alibaba.nacos.auth.exception.AccessException)2 RoleInfo (com.alibaba.nacos.config.server.auth.RoleInfo)2 ExpiredJwtException (io.jsonwebtoken.ExpiredJwtException)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 AuthenticationException (org.springframework.security.core.AuthenticationException)2 Request (com.alibaba.nacos.api.remote.request.Request)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 Before (org.junit.Before)1 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)1 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)1 PostMapping (org.springframework.web.bind.annotation.PostMapping)1