如何在java spring rest中跨跨源调用持久化HttpSession?

时间:2018-09-12 06:10:13

标签: spring reactjs session

我在false上运行我的spring rest api,在 <DropdownMenu right> <DropdownItem> <NavLink> <Link onClick={this.toggle} to={"/client"} style={{ textDecoration: "none", color: "gray" }} > Client Side </Link> </NavLink> </DropdownItem> <DropdownItem> <NavLink> <Link onClick={this.toggle} to={"/server"} style={{ textDecoration: "none", color: "gray" }} > Server Side </Link> </NavLink> </DropdownItem> <DropdownItem divider /> <DropdownItem> <NavLink href="https://github.com/alzz0" target="_blank"> GitHub </NavLink> </DropdownItem> </DropdownMenu> 上运行了一个使用此api的react应用,并且我试图保留信息以防用户刷新页面。

如果我的前端代码驻留在spring应用程序本身中,但不在其他端口上运行时,则可以正常工作。

所有在线帮助都指向spring安全(或者对我不起作用),没有spring安全就没有办法吗?

这是相关的代码。

后端
localhost:8080/api

localhost:3000

src/com/config/InitConfig.java

@Configuration
@EnableWebMvc
@ComponentScan("com")
public class InitConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

src/com/config/Initializer.java

public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return new Class[] {InitConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        // TODO Auto-generated method stub
        System.out.println("inside the initializer");
        return new String[] { "/" };
    }

}

前端

src/com/controller/UserController.java

@RestController
@CrossOrigin
public class UserController {

    @Autowired
    UserService userService ;

    @RequestMapping(value="/users",method=RequestMethod.GET)
    public ResponseEntity<ArrayList<User>> getAllUsers(HttpServletRequest req) {
        System.out.println("Inside users controller ") ;
        System.out.println(req.getSession().getId()) ;
        ArrayList<User> arr = new ArrayList<User>() ;
        for(int i = 0 ; i < 10 ; ++i) {
            arr.add(new User("sarvagya" , 1)) ;
        }
        return new ResponseEntity<ArrayList<User>>(arr , HttpStatus.OK) ;
    }

    @RequestMapping(value="/" , method=RequestMethod.GET)
    public ResponseEntity<User> getCurrent(HttpServletRequest req) {
        System.out.println("Inside home controller ") ;
        System.out.println(req.getSession().getId()) ;
        System.out.println("CurrentUser is " + req.getSession().getAttribute("currentUser")) ;
        User user = (User) req.getSession().getAttribute("currentUser") ;
        if(user == null) return new ResponseEntity<User>(user, HttpStatus.OK) ; 
        return new ResponseEntity<User>(user , HttpStatus.OK) ;
    }


    @RequestMapping(value="/users/current" , method=RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getCurrentUser(HttpServletRequest req) {
        System.out.println(req.getSession().getId()) ;
        System.out.println("CurrentUser is " + req.getSession().getAttribute("currentUser")) ;
        User user = (User) req.getSession().getAttribute("currentUser") ;
        if(user == null) return new ResponseEntity<User>(user, HttpStatus.NOT_FOUND) ; 
        return new ResponseEntity<User>(user , HttpStatus.OK) ;
    }

    @RequestMapping(value="users/login" , method=RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUserByEmail(@RequestBody User user , HttpServletRequest req) {
        System.out.println("Inside java controller " + user) ;
        User newUser = userService.findByEmail(user.getEmail()) ;
        System.out.println(newUser) ;
        if(newUser == null || !newUser.getPassword().equals(user.getPassword())) {
            newUser = null ;
            return new ResponseEntity<User>(newUser, HttpStatus.NOT_FOUND) ;
        }
        System.out.println("Successful login") ;
        // successful login
        req.getSession().setAttribute("currentUser", newUser) ;
        System.out.println(req.getSession().getId());
        return new ResponseEntity<User>(newUser, HttpStatus.OK) ;
    }
}

我只是尝试在成功登录后在HttpSession对象中设置UserService.js属性,并在刷新页面之间获取该信息。我能够登录,以便跨源工作正常,我想,唯一的问题是我发出的每个请求的会话ID都不相同,因此刷新页面时丢失了信息。我的设置是否错误?或者这不是处理跨源请求会话的方法吗?

1 个答案:

答案 0 :(得分:0)

最佳做法是使用基于令牌的身份验证系统,而不是使用Session对象,在该系统中,您可以暂时将JWT或类似的加密令牌保留在浏览器本地存储中,并在注销/超时时销毁它。