In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how springboot uploads files to the remote server in the way of FTP. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
Through the author's previous two articles, I believe we already know what JWT is, how to use it, and how to use it in combination with Spring Security. Then this section uses the code to specifically implement the JWT login authentication and authentication process.
I. Environmental preparation
Set up the Spring Boot project and integrate Spring Security, the project can start normally.
Write a GET method service interface for HTTP through controller, such as "/ hello"
Realize the most basic dynamic data verification and authority allocation, that is, the implementation of UserDetailsService interface and UserDetails interface. These two interfaces are both interfaces that provide Spring Security with verification information such as users, roles, permissions, etc.
If you have studied Spring Security's formLogin login mode, please remove all the formLogin () configuration sections from the HttpSecurity configuration. Because JWT uses the JSON interface entirely, there is no from form submission.
Csrf (). Disable () must be added to the HttpSecurity configuration, that is, to temporarily turn off the defense against cross-site attacks on CSRF. This is not safe, and we will deal with it in the following chapters.
We have already talked about the above in previous articles. If you are still not familiar with it, you can refer to the previous article on this account.
# # II. Develop JWT tool class
Introducing JWT toolkit jjwt through maven coordinates
Io.jsonwebtoken jjwt 0.9.0
Add the following customization to application.yml for JWT configuration
Jwt: header: JWTHeaderName secret: aabbccdd expiration: 3600000
Where header is the name of the Header of the HTTP that carries the JWT token. Although I call it JWTHeaderName here, the worse the readability, the safer it is in actual production.
Secret is the key used to encrypt and decrypt the basic information of JWT. Although I am dead in the configuration file here, it is not usually written directly in the configuration file in actual production. Instead, it is passed through the startup parameters of the application and needs to be modified periodically.
Expiration is the valid time of the JWT token.
Write a utility class that automatically loads the Spring Boot configuration.
@ Data@ConfigurationProperties (prefix = "jwt") / / configure automatic loading. Prefix is the prefix @ Componentpublic class JwtTokenUtil implements Serializable {private String secret; private Long expiration; private String header; / * generate token token * * @ param userDetails user * @ return token * / public String generateToken (UserDetails userDetails) {Map claims = new HashMap (2); claims.put ("sub", userDetails.getUsername ()); claims.put ("created", new Date ()) Return generateToken (claims);} / * get username from token * * @ param token token * @ return username * / public String getUsernameFromToken (String token) {String username; try {Claims claims = getClaimsFromToken (token); username = claims.getSubject ();} catch (Exception e) {username = null;} return username } / * determine whether the token expires * * @ param token token * @ return expires * / public Boolean isTokenExpired (String token) {try {Claims claims = getClaimsFromToken (token); Date expiration = claims.getExpiration (); return expiration.before (new Date ());} catch (Exception e) {return false }} / * Refresh token * * @ param token original token * @ return New token * / public String refreshToken (String token) {String refreshedToken; try {Claims claims = getClaimsFromToken (token); claims.put ("created", new Date ()); refreshedToken = generateToken (claims);} catch (Exception e) {refreshedToken = null;} return refreshedToken } / * verify that the token * * @ param token token * @ param userDetails user * @ return is valid * / public Boolean validateToken (String token, UserDetails userDetails) {SysUser user = (SysUser) userDetails; String username = getUsernameFromToken (token); return (username.equals (user.getUsername ()) & &! isTokenExpired (token)) } / * generate tokens from claims. If you don't understand, see who calls it * * @ param claims data declaration * @ return token * / private String generateToken (Map claims) {Date expirationDate = new Date (System.currentTimeMillis () + expiration); return Jwts.builder () .setClaims (claims) .setExpiration (expirationDate) .signWith (SignatureAlgorithm.HS512, secret) .compact () } / * get the data declaration from the token. If you don't understand it, see who calls it * * @ param token token * @ return data declaration * / private Claims getClaimsFromToken (String token) {Claims claims; try {claims = Jwts.parser (). SetSigningKey (secret) .parseClaimsJws (token). GetBody ();} catch (Exception e) {claims = null;} return claims;}}
The above code uses the methods provided by io.jsonwebtoken.jjwt to develop JWT token generation and refresh tool classes.
Develop the login interface (the API to get Token)
The "/ authentication" interface is used for login verification, and the generated JWT is returned to the client "/ REFRESHTOKEN" interface to refresh the JWT. Update the validity period of the JWT token @ RESTCONTROLLERPUBLIC CLASS JWTAUTHCONTROLLER {@ RESOURCE PRIVATE JWTAUTHSERVICE JWTAUTHSERVICE; @ POSTMAPPING (VALUE = "/ AUTHENTICATION") PUBLIC AJAXRESPONSE LOGIN (@ REQUESTBODY MAP MAP) {STRING USERNAME = MAP.GET ("USERNAME"); STRING PASSWORD = MAP.GET ("PASSWORD") IF (STRINGUTILS.ISEMPTY (USERNAME) | | STRINGUTILS.ISEMPTY (PASSWORD)) {RETURN AJAXRESPONSE.ERROR (NEW CUSTOMEXCEPTION (CUSTOMEXCEPTIONTYPE.USER_INPUT_ERROR, "username password cannot be empty");} RETURN AJAXRESPONSE.SUCCESS (JWTAUTHSERVICE.LOGIN (USERNAME, PASSWORD));} @ POSTMAPPING (VALUE = "/ REFRESHTOKEN") PUBLIC AJAXRESPONSE REFRESH (@ REQUESTHEADER ("${JWT.HEADER}") STRING TOKEN) {RETURN AJAXRESPONSE.SUCCESS (JWTAUTHSERVICE.REFRESHTOKEN (TOKEN);}}
The core token business logic is written in JwtAuthService
The first step in the login method is to use the user name and password for login authentication. Throws a BadCredentialsException exception if validation fails. If the verification is successful, the program continues to go down and generates a JWT response to the front end
The refreshToken method can be refreshed only if the JWT token does not expire, and cannot be refreshed when it expires. You need to log in again.
@ Servicepublic class JwtAuthService {@ Resource private AuthenticationManager authenticationManager; @ Resource private UserDetailsService userDetailsService; @ Resource private JwtTokenUtil jwtTokenUtil; public String login (String username, String password) {/ / login authentication using username password UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken (username, password); Authentication authentication = authenticationManager.authenticate (upToken); SecurityContextHolder.getContext (). SetAuthentication (authentication); / / generate JWT UserDetails userDetails = userDetailsService.loadUserByUsername (username); return jwtTokenUtil.generateToken (userDetails) } public String refreshToken (String oldToken) {if (! jwtTokenUtil.isTokenExpired (oldToken)) {return jwtTokenUtil.refreshToken (oldToken);} return null;}}
Because AuthenticationManager is used, AuthenticationManager is declared as a Bean in the SpringSecurity configuration implementation class that inherits WebSecurityConfigurerAdapter. And open access to "/ authentication" and "/ refreshtoken", and how to open access, we have talked about in previous articles.
Bean (name = BeanIds.AUTHENTICATION_MANAGER) @ Overridepublic AuthenticationManager authenticationManagerBean () throws Exception {return super.authenticationManagerBean ();}
4. API access authentication filter
When the user logs in for the first time, we return the JWT token to the client, which should save the token. When making an API request, take the token and put it in the header of HTTP. The name of header must be the same as the configuration of jwt.header, so that the server can resolve it. Let's define an interceptor:
Intercept the API request, obtain the token from the request request, and parse the user name from the token
Then obtain the system user (from the database, or other its storage media) through UserDetailsService
According to the user information and the JWT token, verify the consistency between the system user and the user input, and determine whether the JWT expires. If it does not expire, it indicates that the user is indeed a user of the system.
However, just because you are a system user doesn't mean you can access all interfaces. So you need to construct UsernamePasswordAuthenticationToken to transmit user and permission information, and tell Spring Security this information through authentication. Spring Security will use this to determine your interface access permissions.
@ Slf4j@Componentpublic class JwtAuthenticationTokenFilter extends OncePerRequestFilter {@ Resource private MyUserDetailsService userDetailsService; @ Resource private JwtTokenUtil jwtTokenUtil; @ Override protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {/ / get jwt token String authHeader = request.getHeader (jwtTokenUtil.getHeader ()) in request from here; log.info ("authHeader: {}", authHeader) / / verify whether if (authHeader! = null & & StringUtils.isNotEmpty (authHeader)) exists in token {/ / get the user name String username = jwtTokenUtil.getUsernameFromToken (authHeader) according to token; if (username! = null & & SecurityContextHolder.getContext (). GetAuthentication () = null) {/ / obtain the user's information UserDetails userDetails = this.userDetailsService.loadUserByUsername (username) through the user name / / verify whether JWT is expired if (jwtTokenUtil.validateToken (authHeader, userDetails)) {/ / load user, role, permission information. Based on this information, Spring Security determines the access rights of the interface UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken (userDetails, null, userDetails.getAuthorities (); authentication.setDetails (new WebAuthenticationDetailsSource () .buildDetails (request)); SecurityContextHolder.getContext (). SetAuthentication (authentication);} chain.doFilter (request, response);}}
In the configure (HttpSecurity http) configuration method of the spring Security configuration class (that is, the WebSecurityConfigurerAdapter implementation class), add the following configuration:
.sessionManagement () .sessionCreationPolicy (SessionCreationPolicy.STATELESS) .and () .addFilterBefore (jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
Because we use JWT, which shows that our application is a front-end separation application, we can turn on STATELESS to disable the use of session. Of course, this is not absolute, front-end separation of applications can also use session through some ways, this is not the core of this article will not repeat. Load our custom jwtAuthenticationTokenFilter in front of the UsernamePasswordAuthenticationFilter.
5. Test it:
Test the login interface, that is, the interface to get token. Enter the correct user name and password to get token.
Let's access a simple interface "/ hello" that we define, but without passing the JWT token, as a result, access is prohibited. When we pass the token returned in the previous step to header, we can normally respond to the interface result of hello.
The above is the process that the editor introduced springboot to upload files to the remote server by FTP. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to our website! If you think this article is helpful to you, you are welcome to reprint it, please indicate the source, thank you!
After reading the above, do you have any further understanding of how springboot uploads files to the remote server in FTP? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.