In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the springboot integration of security and vue example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
Environment
Springboot1.5.9
Complete code, there is sql, first build the library, run sql to build the table, sql has been inserted into the test data.
Https://github.com/2010yhh/springBoot-demos/tree/master/springboot-security
Visit the home page: http://localhost:8080
1.security reference material
Spring Security reference documentation: https://docs.spring.io/spring-security/site/docs/4.1.0.RELEASE/reference/htmlsingle/#what-is-acegi-security
Spring-security source code: https://github.com/spring-projects/spring-security/
Main functions: authentication and authorization
Configurer Filter feature description
CorsConfigurer CorsFilter provides Filter with cross-domain access configuration support
SessionManagementConfigurer SessionManagementFilter session Management Filter
Support for RememberMeConfigurer RememberMeAuthenticationFilter to remember username and password
ExpressionUrlAuthorizationConfigurer
CsrfConfigurer CsrfFilter cross-site request forgery to protect Filter
LogoutConfigurer LogoutFilter logon request processing Filter
FormLoginConfigurer UsernamePasswordAuthenticationFilter form login request processing Filter
OAuth3LoginConfigurer OAuth3AuthorizationRequestRedirectFilter OAuth3 requests permission control to process Filter, and provides Oauth3 login for other websites, that is, other websites are authorized to log in through the account password of this website.
Log in to the authorization Filter based on HttpBasicConfigurer BasicAuthenticationFilter Security and save the results in SecurityContextHolder
The principle of certification process:
Reference: https://www.processon.com/view/link/5ac1e565e4b00dc8a026ab46
Key points of 2.springboot Integration security
Mainly class WebSecurityConfig extends WebSecurityConfigurerAdapter.
For SecurityConfig configuration information, refer to the WebSecurityConfig class in the code
2.1 get login user information UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext () .getAuthentication () .getPrincipal (); 2.2 Custom login and logout url
1) configuration in SecurityConfig configuration:
.and () .formLogin () / / specify url The corresponding controller processing can be redirected to a login page such as login_page.html .loginPage ("/ mylogin") / / Custom login url / / specify the path of a custom form form request .loginProcessingUrl ("/ myloginForm") .loginProcessingUrl ("userName") .loginProcessingUrl ("userName"). PasswordParameter ("passWord") / /. DefaultSuccessUrl ("/ success") .login ForwardUrl ("/ success") / / sets the Handler for logging in and out Priority response Handler .failureUrl ("/ fail") / / set logout Handler, priority response Handler .and () .logout () .logoutUrl ("/ mylogout") / / Custom exit url .logoutSuccessUrl ("/ logoutSuccessUrl") .logoutSuccessHandler (myLogoutSuccessHandle) / / set logoutSuccessHandler / / Give priority to response Handler .invalidateHttpSession (true) .permitAll ()
2) overwrite the url of the request in the frontend request
For example, vue request:
Export const login = data = > {return http.post (`/ myloginForm?userName=$ {data.userName} & passWord=$ {data.passWord} & rememberMe=$ {data.rememberMe} & imageCode=$ {data.imageCode}`)} export const logout = data = > {return http.post (`/ mylogout`)}
As a general html form request:
User name: password:
Next time automatically login 2.3.Custom Handler returns json
1) rewrite AuthenticationSuccessHandler, AuthenticationFailureHandler, LogoutSuccessHandler, AccessDeniedHandler and AuthenticationEntryPoint, which are login success, login failure, exit success, insufficient permissions, and not yet login. Customize the return json format in these override classes.
2) configuration in SecurityConfig configuration
/ / return json .accounHandler (myAuthenticationSuccessHandler) .failureHandler (myAuthenticationFailureHandler) .logoutSuccessHandler (myLogoutSuccessHandle) / / set logoutSuccessHandler (myLogoutSuccessHandle) / / set logoutSuccessHandler (myLogoutSuccessHandle) / / give priority to Handler http.exceptionHandling () .authenticationEntryPoint (myAuthenticationEntryPoint); / / not logged in http.exceptionHandling () .failureHandler (myAccessDeniedHandler); / / have no access to 2.4.remember me function
Close the browser, reopen the login url, and jump to the home page or other page without logging in.
1) configuration in SecurityConfig configuration
.and () .remember me () .rememberMeParameter ("rememberMe") .tokenRepository (persistentTokenRepository ()) .userDetailsService (myUserDetailsService) .tokenValiditySeconds (60 * 60 * 24)
2) configure bean to write token to database in SecurityConfig configuration
/ * * springSecurity automatically inserts token into persistent_logins * * @ return * / @ Bean public PersistentTokenRepository persistentTokenRepository () {JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl (); tokenRepository.setDataSource (dataSource); return tokenRepository;} 2.5CAPTCHA function according to the situation
1) Custom CAPTCHA filter to verify that the entered CAPTCHA is consistent with the CAPTCHA saved in session
2) configuration in SecurityConfig configuration
/ / use our custom CAPTCHA filter to configure / / UsernamePasswordAuthenticationFilter before http.addFilterBefore (validateCodeFilter, UsernamePasswordAuthenticationFilter.class) 2.6 limit the number of logins
1) Custom event listeners for successful and failed login
Public class AuthenticationSuccessEventListener implements ApplicationListener {} public class AuthenticationFailureListener implements ApplicationListener {}
2) you can use the database or redis or replace it to store the number of login failures to determine and lock the account
3) the actual project administrator role should have the function of unlocking the account.
2.7 password encryption
1) when creating a new user, the storage password is encrypted. BCryptPasswordEncoder is used in this article.
2) during login: the password entered is encrypted and the user's password obtained by query is verified internally by security
2.8Backend provides interface, returns frontend json, integrates vue to do frontend login and logout.
This is also the mode of front-end separation.
The front end can first obtain all roles and permissions of the currently logged in user (permissions can be refined to menus, buttons and interfaces): and then determine the display effect of the front end.
Note that the url of the front-end request is written:
Export const login = data = > {return http.post (`/ myloginForm?userName=$ {data.userName} & passWord=$ {data.passWord} & rememberMe=$ {data.rememberMe} & imageCode=$ {data.imageCode}`)} export const logout = data = > {return http.post (`/ mylogout`)} 3. test
Three users: admin manager user2 for testing, permissions in this code are useless, only the role level is used. When the test remembers my function, clear the cookie so as not to affect the test.
User role permissions adminadmin manager useradd delete query queryall updatemanagermanager userquery queryalluser2userquery
Set different roles for the three url of http://localhost:8080/user/list http://localhost:8080/user/list2 http://localhost:8080/user/list3 (which can be accessed without login)
.antMatrices ("/ user/list") .hasAuthority ("admin") .antMatrices ("/ user/list2") .hasRole ("manager")
Enter: http://localhost:8080 redirect to login page: http://localhost:8080/#/login
2) after entering the correct user name and password of admin manager user2, the page returned after successful login will show different effects. After three users have successfully logged in, they will directly visit url and block it according to their roles. After clicking exit, they will return to http://localhost:8080/#/login.
User2:
Direct access to url: http://localhost:8080/user/list
Manager:
Direct access to url: http://localhost:8080/user/list
Admin:
Direct access to url: http://localhost:8080/user/list
Direct access to logout url:
4) Test. Remember me.
Testing with admin users
Here, after closing the browser or restarting the process, directly access the resources that need roles, such as http://localhost:8080/#/home or http://localhost:8080/user/list
You can access it directly without logging in.
But visiting the home page of http://localhost:8080 or http://localhost:8080/#/login cannot jump to http://localhost:8080/#/home.
5) Test verification code
If the CAPTCHA expires or is typed incorrectly or the page is refreshed, the CAPTCHA will be regenerated.
6) Test limits the number of logins
In the case of entering the correct verification code, the error verification code will directly throw the exception of the verification code. If you enter the wrong user name or password for 3 times in a row, the account will be locked and an account lock exception will be thrown.
Thank you for reading this article carefully. I hope the article "sample Analysis of springboot Integration of security and vue" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.