java如何返回用户信息

使用java spring security,用户登录成功的话如何返回用户信息给前端呢,token似乎不能带信息吧,jwt的话网上说有可能被劫持,不够安全?

就正常返回json 信息就可以啊,你这个前端要用的信息,还是要给前端的。

  • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/7689696
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:Spring security+jwt+前后端分离的登录
  • 除此之外, 这篇博客: 从零开始java安全权限框架篇(八):spring security+jwt实现前后端分离中的 3.jwt的登录拦截器 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • package com.config.Seurity.filter;
     
    
    import com.commons.base.response.DataResult;
    import com.commons.base.response.MyRespose;
    import com.commons.constant.JwtConstant;
    
    import com.commons.constant.UserConstant;
    
    import com.commons.utils.http.RequestUtil;
    
    import com.config.Seurity.exception.UserBeforeException;
    
    
    import com.config.Seurity.model.LoginFormDto;
    import com.config.Seurity.service.LoginOrLoginOutResultService;
    import com.util.CurrentUser;
    
    import lombok.extern.slf4j.Slf4j;
    
    import org.aspectj.lang.annotation.Aspect;
    
    import org.springframework.security.authentication.AuthenticationManager;
    
    import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.AuthenticationException;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.ArrayList;
    
    
     
    
    /**
     * jwt用户登录处理
     * @author monxz
     *
     * @date 2019年10月25日
     */
    @Slf4j
    @Aspect
    
    public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {
    	
    	
    	private  LoginOrLoginOutResultService  loginResultService;
     
        private AuthenticationManager authenticationManager;
        
       
     
        public JWTLoginFilter(AuthenticationManager authenticationManager,LoginOrLoginOutResultService  loginResultService) {
            this.authenticationManager = authenticationManager;
            this.loginResultService =  loginResultService;
            super.setFilterProcessesUrl(LoginFormDto.login_url);
        }
    
    
    
     
        /**
         * 请求登录
         */
        @Override
        public Authentication attemptAuthentication(HttpServletRequest req,
                                                    HttpServletResponse res) throws AuthenticationException {
        	LoginFormDto loginFormDto = reqCopyLoginDto(req);
        	try {   
        		
            	checkLogin(loginFormDto);
                return authenticationManager.authenticate(
                        new UsernamePasswordAuthenticationToken(
                        		loginFormDto.getUserName(),
                        		loginFormDto.getPassword(),
                                new ArrayList<>())
                );
            } catch (Exception e) {
            	CurrentUser   cu=new   CurrentUser(loginFormDto.getUserName() ==  null || loginFormDto.getUserName().isEmpty()? "unknown":loginFormDto.getUserName(),
            			loginFormDto.getPassword() == null || loginFormDto.getPassword().isEmpty() ? "unknown":loginFormDto.getPassword(),
            			new ArrayList<>());
            	
            	//错误登录
            	loginResultService.errorLoginAddRecord(req, cu, e);
            	
            	MyRespose.initResponse(res, DataResult.buildFail(e.getMessage()));
            }
            return null;
        }
     
       /**
        * 登录成功
        */
        @Override
        protected void successfulAuthentication(HttpServletRequest req,
                                                HttpServletResponse res,
                                                FilterChain chain,
                                                Authentication auth) throws IOException, ServletException {
        	
        	CurrentUser currentUser = (CurrentUser) auth.getPrincipal();
        	log.info(currentUser.getUsername()+"登录成功!");
        	
    		//登录日志的封装
    		currentUser.setLoginSuccess(UserConstant.login_success_status);
    		loginResultService.loginRecord(currentUser, req);
    		
    		//返回正确的Token
    		LoginFormDto  loginFormDto = reqCopyLoginDto(req);							
        	res.addHeader(JwtConstant.jwt_authorization, loginResultService.loginSuccessCreateToken(loginFormDto, currentUser));
            MyRespose.initResponse(res, DataResult.buildSuccess());
        }
        
    
    
    
        
        
        
        /**
         * 检测用户名和密码的正确性
         * @param userName
         * @param password
         * @throws Exception 
         */
        private  void checkLogin(LoginFormDto  loginForm ) throws Exception {
        	
        	if(loginForm.getUserName() == null  || loginForm.getUserName().isEmpty()  ){
        		throw  new UserBeforeException("用户名不能为空!");
        	}
        	
        	if(loginForm.getPassword() == null || loginForm.getPassword().isEmpty() ){
        		throw new UserBeforeException("密码不能为空");
        	}
        }
        
       
        
        
    
        
      
        
        /**
         * 将HttpServletRequest参数转成实体类
         * @param HttpServletRequest
         * @return LoginFormDto
         * @throws Exception
         */
        private LoginFormDto  reqCopyLoginDto(HttpServletRequest req){ 	
        	return RequestUtil.getBean(LoginFormDto.class, req);
        }
     
    }
    

在登录事件的处理函数中,判断登录是否成功,如果成功,将从数据库中获取的用户信息和生成的token一起返回就行。