简体   繁体   English

如何在 Spring MVC 应用程序中实现 Spring 安全性?

[英]How to Implement Spring security in Spring MVC application?

I'm new to Spring security.我是 Spring 安全的新手。 I have implemented spring security and have generated the JWT token.我已经实现了 spring 安全并生成了 JWT 令牌。 Now i need to get the user from the token and set it in the session so that the session for that user maintains until the token expires or logged out.现在我需要从令牌中获取用户并将其设置在会话中,以便该用户的会话保持到令牌过期或注销。 On the other hand i need to access the API's from the controller but the spring security is not allowing to access the API's without the JWT Token.另一方面,我需要从控制器访问 API,但 Spring Security 不允许在没有 JWT 令牌的情况下访问 API。 Is it possible to access the API's in my controller by setting the JWT Token globally or in the session for all the requests.是否可以通过全局设置 JWT 令牌或在所有请求的会话中访问我的控制器中的 API。

Here is what i tried till now ,这是我到目前为止所尝试的,

  UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginRequest.getUserName(), loginRequest.getPassword());
                Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                String jwt = tokenProvider.generateToken(authentication);               
                logger.info("jwt is:"+jwt);
                logger.info("authentication:"+authentication.getName());
                User user2 = new User();
                user2.setUserFirstName(user.getFirstName());
                user2.setUserLastName(user.getLastName());
                request.getSession().setAttribute("loggedInUser",user2);
                request.getSession().setMaxInactiveInterval(60);
                request.getSession().setAttribute("menu", MenuUtils.buildMenu(user2));
                return "home";

I'm doing this while signing in the user.我在登录用户时这样做。 I'm using Thymeleaf in the frontend.我在前端使用 Thymeleaf。

Thanks for the help in advance !!我在这里先向您的帮助表示感谢 !!

You need to add the jwt token to the request headers, when accessing the apis:访问 api 时,您需要将 jwt 令牌添加到请求标头中:

headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + jwt);

This allows the api's to read the headers, and check the user and his permissions这允许 api 读取标题,并检查用户及其权限

You don't need to store the user on the session.您不需要在会话中存储用户。 The token itself has an expiry date, and it should be send from the browser to the server on every request.令牌本身有一个到期日期,它应该在每次请求时从浏览器发送到服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM