navigation
[react] Hooks
[Encapsulation 01- Design Pattern] Design principles and factory pattern (simple abstract approach) Adapter pattern Decorator pattern [Encapsulation 02- Design Pattern] Command pattern Enjoy pattern Composite pattern Agent pattern
[React from zero practice 01- background] code split [React from zero practice 02- background] permission control [React from zero practice 03- background] custom hooks [React from zero practice 04- background] docker-compose Deploy React + Egg +nginx+mysql [React From zero practice 05- background] Gitlab-CI using Docker automated deployment
[source code – Webpack01 – precompiler] AST abstract syntax tree [source code – Webpack02 – Precompiler] Tapable [source code – Webpack03] hand written webpack-compiler simple compilation process [source code] Redux React-redux01 [source] Axios [source] vuex [source -vue01] Data reactive and initialize render [source -vue02] Computed responsive – Initialize, access, Update Procedure [source -vue04] Watch Listening properties – Initialize and update [source -vue04] vue. set and vm.$set [source -vue05] vue.extend
[source -vue06] Vue. NextTick and VM.$nextTick [Deployment 01] Nginx [Deployment 02] Docker deployVUE project [Deployment 03] Gitlab-CI
[Data Structures and Algorithms 01] Binary search and sort
[Deep 01] Execution context [Deep 02] Prototype chain [Deep 03] Inheritance [Deep 04] Event loop [Deep 05] Curri Bias function [Deep 06] Function memory [Deep 07] Implicit conversions and operators [Deep 07] Browser caching mechanism (HTTP caching mechanism) [Deep 08] Front-end security [Deep 09] Deep copy [Deep 10] Debounce Throttle [Deep 10] Front-end routing [Deep 12] Front-end modularization [Deep 13] Observer mode Publish subscribe mode Bidirectional data binding [Deep 14] Canvas [Deep 15] webSocket Webpack HTTP and HTTPS CSS- Interview Handwriting Promise Data Structures and Algorithms – Binary Search and Sorting Js Design Patterns – Agents, policies, singletons
/ front-end learn java01 – SpringBoot combat environment configuration and the HelloWorld service [front-end learn java02 – SpringBoot combat] mybatis + mysql implementation song to add and delete [front-end learn java03 – SpringBoot combat] Lombok, log, Java04 -SpringBoot combat deployment [front-end science Java04 -SpringBoot combat] static resources + interceptor + front and back end file upload [front-end science Java05 -SpringBoot combat] common annotates + Redis implementation statistics function [front-end science Java06 -SpringBoot combat] inject + Swagger2 3.0 + unit test JUnit5 [Front-End science Java07 -SpringBoot real World] IOC scanner + transaction + Jackson [front-end science Java08 -SpringBoot real world summary 1-7 [java09-SpringBoot] Multi-module configuration + Mybatis-plus + single multi-module package deployment [Java10 -SpringBoot] Bean assignment conversion + parameter verification + global exception handling [Front-end java11-SpringSecurity] configuration + memory + database = three ways to achieve RBAC
(1) Pre-knowledge
(1) Some words
Security Security advice Exception Maintainer Structure Hierarchy subtypes Subtypes Authorize authorization // Authorities cursor pointer cursor destructure deconstruction granted awarded agree structure structure = > command + 7 / / distinguish destructure and structure Assignee, principal ConcurrentCopy the code
(2) Idea shortcuts
See the full inheritance f4 jump to the source f3 quick look at the methods a class has command + 7 => StructureCopy the code
(3) What is salt encryption
- Salt encryption is a method of encrypting (system login – password)
- It is encrypted by (
Each password is associated with an n-bit random number
), the n-bit random number is called (salt
)
(4) MyBatis and MyBatis -plus configuration conflict
- Problem cause analysis (stepping pit)
-
The configuration of MyBais is specified in the config and mapper files in appliation.yml
- Resources/mybatis mapper/XXX. In the XML
-
While myBatis -plus’s mapper file needs to be in
- Resources/mapper/XXX. In the XML
-
The above two positions are different, which can easily lead to the situation that mapper cannot be found. It must be noted that it took several hours to find the reason after stepping on this pit
-
(5) ArrayList
- Commonly used API
- The add new
- Set to modify
- Remove delete
- Number of members of the size
- IndexOf index
- Similar to Array in JS
- The difference between ArrayList and List
- List:
- There can be only one data type in a collection. Multiple data types are not allowed
- Is an interface and therefore cannot be constructed i.e. cannot be instantiated (interfaces and abstractions cannot be instantiated)
- ArrayList
- ArrayList is an implementation of the List interface
- List:
@SpringBootTest public class ArrayListTest { @Test public void arrList() { ArrayList<String> addressList = new ArrayList<>(); addressList.add("beijing"); addressList.add("shanghai"); addressList.set(1, "shanghai2"); addressList.remove(1); int beijing = addressList.indexOf("beijing"); int size = addressList.size(); }}Copy the code
(6) PasswordEncoder and BCryptPasswordEncoder
- PasswordEncoder
- Spring-security requirements must be present in the container
PasswordEncoder
Instance, so you must inject the PasswordEncoder bean object into the container when customizable login logic - PasswordEncoder – api
- Encode parses parameters according to specific rules
- Matches the passwords before and after the matches code
- Spring-security requirements must be present in the container
- BCryptPasswordEncoder
- BCryptPasswordEncoder is a recommended password resolver for spring
@bean // @bean put the object in the container public PasswordEncoder PasswordEncoder() {return new BCryptPasswordEncoder(); } passwordEncoder().encode("111") // encodeCopy the code
(2) of the spring – the boot – starter ws-security
(0) RBAC permission model
- Basic concepts of RBAC
- RBAC stands for Role-based Access Control
- One user has multiple roles, one role has multiple permissions
- Relationship between
- More than a pair of
- One user corresponds to one role, and one role covers multiple users => one-to-many
- (a one-to-many relationship), need to add (the relationship field) to (the table with more) – see third figure
- For example, students and teachers, it is easier for students to remember teachers
- Many to many
- A user corresponds to multiple roles, and a role covers multiple users
- (many-to-many relationship), you need to (create a separate table) to (maintain the relationship) —— See the fourth figure
- More than a pair of
(1) Installation and memory-level user authentication
(1.1) Install dependencies
<! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>Copy the code
Experience in the early (1.2)
- I’m just going to put some random controller in the controller to validate it
- Accessing the URL leads to a landing page provided by Spring-Security, and the password is provided on the command line
- Password A new password is generated every time you restart
- The default (
The user name user
) (The password is a random string on the command line
)
(1.3) Custom login logic
- In 1.2, the user name can only be admin and the password can only be a printed string
- How to implement custom login logic
- Such as
- I want to enter the user name admin, password admin, just pass
- Any other user name and password will not be approved
- Specific steps
- 1. New
service/TestSecurityService
- 2. Implement
impletes UserDetailsService
interface - 3. Rewrite the
loadUserByUsername
methods
- 1. New
- Such as
@Service @Slf4j public class TestSecurityService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { log.info("+++++++++{}", username); if (!" Admin "equals (username)) {/ / an error if the user name you entered is not the admin throw new UsernameNotFoundException (" can only use the admin login"); } String password = new BCryptPasswordEncoder().encode("admin"); return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,guest")); }}Copy the code
(1.4) Custom form landing page
- Without this, the landing page is provided by Spring-Security and we need to use a custom form
The config/SecurityConfig. Java -- -- -- -- -- -- -- @ Configuration @ EnableWebSecurity / / start spring ws-security security framework @ EnableGlobalMethodSecurity (prePostEnabled = true) / / to enable the role of the method level certification class SecurityConfig extends WebSecurityConfigurerAdapter {/ / WebSecurityConfigurerAdapter is used to control the content of the safety management @ Bean / / @ Bean will public in the object into the container PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } / / custom authentication configuration @ Override protected void the configure (AuthenticationManagerBuilder auth) throws the Exception {PasswordEncoder PE = passwordEncoder(); // Call the method defined below, Return auth PasswordEncoder type. InMemoryAuthentication (.) withUser (" woow_wu7 ") / / user name. The password (PE) encode (" 111 ")) / / password, Encryption. Roles (" admin ", "guest"); @override public void configure(WebSecurity web) throws Exception {// Let spring-security pass JS CSS images file, Not to intercept web. Ignoring (.) antMatchers ("/js / * * ", "/ CSS / * *", "/ images / * *"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() AnyRequest (). Authenticated () / / said all requests (certification) to visit. And (). FormLogin () / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 【 】 .loginPage("/login.html") // --------------- .loginProcessingURL ("/security-test") //---- [] Submit url.usernameParameter ("username") // ---------- [] Customize the name attribute of the INPUT in an HTML form. PasswordParameter ("password") // ---------- [] Customize the name attribute of the input in an HTML form .forwardurl ("/musics") // ----------- //.defaultSuccessURL ("/musics") // ----------- Will return to the previous page. PermitAll () / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 【 】 said: //.logouturl ("/logout") // logoutRequestMatcher(new) //.logouturl ("/logout") // logoutRequestMatcher(new) AntPathRequestMatcher("/logout", "post")) .and() .csrf().disable(); // Turn off CSRF}}Copy the code
(1.5) Customize the route jump after successful login – successHandler
@ Configuration @ EnableWebSecurity / / start spring ws-security security framework @ EnableGlobalMethodSecurity (prePostEnabled = true) / / The role of enabling the method level certified public class SecurityConfig extends WebSecurityConfigurerAdapter {... @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antmatchers ("/security-admin/**").hasanyRole ("admin") // This controller needs the admin role .antmatchers ("/security-guest/**").hasanyRole ("guest") // This controller requires guest character.anyRequest ().authenticated() // Indicates that all requests except the above two are (role-level authentication), that is, only the above two require login and the corresponding role. And ().formlogin ().loginPage("/login.html").loginProcessingURL ("/doLogin").usernameParameter("username") .passwordParameter("password") .successForwardUrl("/musics") .successHandler(new AuthenticationSuccessHandler() { // --- @override public void onAuthenticationSuccess(HttpServletRequest HttpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { httpServletResponse.sendRedirect("/musics"); / / -- - after landing successful jump/musics}}) permitAll () and (). CSRF (). The disable (); // Turn off CSRF}}Copy the code
(1.6) How to Change (User Name) and (Password)
- There are three ways to change the user name and password
- in
application.yml
In the configuration - Through Java code configuration in
In the memory
- From Java code
In the database
loading
- in
- keywords
WebSecurityConfigurerAdapter
@EnableWebSecurity
Spring: security: user: name: woow_wu7 Password: 123Copy the code
(2) in the memory set user name/password - 2.1 - create a new configuration class (SecurityConfig), inheritance (WebSecurityConfigurerAdapter) to 2.2 to SecurityConfig add two annotations, One is @configuration, One is (@enablewebSecurity) - @config indicates the configuration class - @enableWebSecurity indicates the spring security framework content - 2.3 Set the user name and password by using the auth parameter. Role @configuration @enableWebSecurity // Start spring-Security framework content public Class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { Auth. InMemoryAuthentication (.) withUser (" woo_wu7 ") / / user name password (" 111 "). / / password roles (" admin "); / / character auth. InMemoryAuthentication (.) withUser (" woow_wu8 ") / / user name. The password (" 222 ") / / password. Roles (); / / role}} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - after the above Settings, complains, because the password is not clear, need to encrypt the error message: There is no PasswordEncoder mapped for the ID "null" Encrypt the password -------------------------- in 2.4Copy the code
(3) Configure the user name in memory, in addition to the above methods, You can also Override the userDetailsService method - both of the following methods are available ------- // 1 // custom authentication configuration @override protected void configure(AuthenticationManagerBuilder auth) throws Exception { PasswordEncoder pe = passwordEncoder(); // Call the method defined below, Return auth PasswordEncoder type. InMemoryAuthentication (.) withUser (" admin ") / / user name. The password (PE) encode (" admin ")) / / password, .roles("admin") // role.and().withuser ("guest").password("guest").roles("guest"); } // 2 // In addition to the above method to set the username and password, // - By overriding the (userDetailsService) method to implement protected userDetailsService() { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withUsername("admin2").password("admin2").roles("admin").build()); return manager; }Copy the code
(1.7) Password encryption
PasswordEncoder
@configuration @enableWebSecurity public Class SecurityConfig extends WebSecurityConfigurerAdapter {/ / WebSecurityConfigurerAdapter is used to control the content of the safety management @ Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { PasswordEncoder pe = passwordEncoder(); // ---------------- calls the method defined below, Return auth PasswordEncoder type. InMemoryAuthentication (.) withUser (" woow_wu7 ") / / user name. The password (PE) encode (" 111 ")) / / password -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - encryption. Roles (); / / role auth. InMemoryAuthentication (.) withUser (" woow_wu8 ") / / user name. The password (PE) encode (" 222 ")) / / password roles (); Public PasswordEncoder PasswordEncoder () {// ----------------- Encryption method return new BCryptPasswordEncoder(); // -------------------- is an encryption mode}}Copy the code
(1.8) Add (role) information and implement (method level) role validation
- (
Same user
There can be (Different roles
) - The following list is based on (
The method level
) - keywords
@EnableGlobalMethodSecurity
prePostEnabled
@PreAuthorize
@PostAuthorize
- Procedure For enabling role authentication at the method level
- Write @ the Configuration register class, and extends WebSecurityConfigurerAdapter inheritance
- Through @ Overvide rewrite the configure method, AuthenticationManagerBuilder by auth parameters – auth. InMemoryAuthentication – specifies the user’s role
- Through @ EnableGlobalMethodSecurity (prePostEnabled = true) to enable verification method level role
- Add role information to the controller method, and specify a list of roles that can be accessed by the @preauthorize (value = “hasAnyRole(‘admin’, ‘guest’)”) command
Config/SecurityConfig - -- -- -- -- -- - / * * * * * * * @ EnableGlobalMethodSecurity role: to enable the method level role certification * parameters: (prePostEnabled=true) => Indicates that (@preauthorize) annotations and (@postauthorize) ** **/ @configuration @enableWebSecurity // can be used Start the spring ws-security security framework content @ EnableGlobalMethodSecurity (prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter {/ / WebSecurityConfigurerAdapter is used to control the content of the safety management / / @ Override / / public void configure(WebSecurity web) throws Exception { // web.ignoring().antMatchers("/test-security"); // filter out (/test-security) // super.configure(web); // } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { PasswordEncoder pe = passwordEncoder(); // Call the method defined below, Return auth PasswordEncoder type. InMemoryAuthentication (.) withUser (" woow_wu7 ") / / user name. The password (PE) encode (" 111 ")) / / password, Encryption. Roles (" admin ", "guest"); / / role auth. InMemoryAuthentication (.) withUser (" woow_wu8 ") / / user name. The password (PE) encode (" 222 ")) / / password roles (" guest "); Public PasswordEncoder PasswordEncoder() {return new BCryptPasswordEncoder(); }}Copy the code
The controller/TestSecurityController -- -- -- -- -- -- -- / / admin and guest can access @ GetMapping ("/test - security - all ") @ PreAuthorize (value = "hasAnyRole('admin', Public String all() {return "@preauthorize (value = \"hasAnyRole('admin'), 'guest')\")"; }; @getMapping ("/test-security-only") @preauthorize (value = "hasAnyRole('admin')") // Only admin can access public String only() { return "@PreAuthorize(value = \"hasAnyRole('admin')\")"; }Copy the code
- When user woow_wu8 is entered, access to /test-security-only is denied because the user’s role does not satisfy the role authentication in Contrller, and only the admin role can access the address
(1.9) Ignore interception – Disable authentication
- If a URL does not need to be intercepted, there are two ways to do this
- Set the URL to be used for anonymous access
- The URL is filtered through spring-Security, which filters out the methods in the controller
(1) the method 1 / / main program, the master configuration class @ SpringBootApplication (exclude = {SecurityAutoConfiguration. Class}) to eliminate the security configuration, Public class Application {}Copy the code
(2) Front end separation – Returns JSON data
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() AnyRequest (). Authenticated () / / said all requests (certification) to visit. And (). FormLogin () / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 【 】 .loginPage("/login.html") // --------------- .loginProcessingURL ("/security-test") //---- [] Submit the URL for username and password //.usernameParameter("username") // ---------- [] Custom HTML form input name attribute //. PasswordParameter ("password") // ---------- [] Custom HTML form input name attribute // .forwardurl ("/musics") // ----------- //.defaultSuccessURL ("/musics") // ----------- SuccessHandler ((req, resp, Resp. SetContentType ("application/json; charset=utf-8"); PrintWriter writer = resp.getWriter(); writer.write(new ObjectMapper().writeValueAsString(authentication.getPrincipal())); writer.flush(); writer.close(); }). FailureHandler ((the req, resp, exception) - > {/ / = = = = = = = = = = = = = = = = = = = = = login failed callback function resp. SetContentType (" application/json; charset=utf-8"); PrintWriter writer = resp.getWriter(); writer.write(new ObjectMapper().writeValueAsString(exception.getMessage())); writer.flush(); writer.close(); }). PermitAll () / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 【 】 said: //.logouturl ("/logout") // logoutRequestMatcher(new) //.logouturl ("/logout") // logoutRequestMatcher(new) AntPathRequestMatcher("/logout", "post")) .and() .csrf().disable(); // Turn off CSRF}Copy the code
(3) Authorization – authenticates different roles required by different controllers
- Pay attention to
- In addition to this method here
- Methods in 1.6 can also be used, that is, via @preauthorize
- In the (SecurityConfig(of)WebSecurityConfigurerAdapterRewrittenconfigure) method
Specify user information: user name, password, and role
Specify the role required to access the route
(1) Define (user login role information) and (role permission rules) in the SecurityConfig file ------! [image.png](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/145438caf77c4d3cb934c3cf01df2586~tplv-k3u1fbpfcp-watermark Image) @ Configuration @ EnableWebSecurity / / start spring ws-security security framework @ EnableGlobalMethodSecurity (prePostEnabled = true) / / to enable the role of the method level certification class SecurityConfig extends WebSecurityConfigurerAdapter {/ / WebSecurityConfigurerAdapter is used to control the content of the safety management @bean // @bean put the object in the container public PasswordEncoder PasswordEncoder() {return new BCryptPasswordEncoder(); } / / custom authentication configuration @ Override protected void the configure (AuthenticationManagerBuilder auth) throws the Exception {PasswordEncoder PE = passwordEncoder(); // Call the method defined below, Return auth PasswordEncoder type. InMemoryAuthentication (.) withUser (" admin ") / / -- -- -- -- -- -- -- -- -- -- -- -- -- - the user name. The password (PE) encode (" admin ")) / / - password encryption. The roles (" admin ") / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- role. And (). WithUser (" guest "). The password (" guest "). The roles (" guest "); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antmatchers ("/security-admin/**").hasanyRole ("admin") // This controller needs the admin role .antmatchers ("/security-guest/**").hasanyRole ("guest") // This controller requires guest character.anyRequest ().authenticated() // In addition to the above two, And ().formlogin ().loginProcessingURL ("/doLogin").permitall ().and().csrf().disable(); // Turn off CSRF}}Copy the code
(2) to test the controller -- -- -- -- -- -- -- @ GetMapping ("/hello ") / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- don't need permissions to access the public String the login () {return "hello". } @getMapping ("/security-admin") // ------- Public String getAdmin() {return "admin"; } @getMapping ("/security-guest") // ------- Public String getGuest() {return "guest"; } @getMapping ("/security-admin-other-method") @preauthorize (value = "hasAnyRole('admin')") // ------ String getAdminByOtherMethod() { return "@PreAuthorize(value = \"hasAnyRole('admin')\")"; } @getMapping ("/security-guest-other-method") @preauthorize (value = "hasAnyRole('guest')") // ------ String getGuestByOtherMethod() { return "@PreAuthorize(value = \"hasAnyRole('guest')\")"; }Copy the code
- (3.1) Logout, /logout
- (3.2) Enter the user name and password. At this time, the user has carried role information in memory
- We log in with the admin account
- the
The admin role
You can visit/security-admin
- the
Role of guest
You can visit/security-guest
- the
Any role
Can be accessed/hello
- (3.3) access/security – admin
- Normal access
- Access/security – guest (3.4)
- Can not access
- Role mismatch
- Visit/security – hello (3.5)
- You can visit
- Since both admin and guest can access, there are no restrictions
- In addition to specifying the roles required by the controller’s methods in Config, you can also specify the roles in the controller’s methods via @preauthorize
@PreAuthorize
- You can visit
(3) Realize RBAC through database
(3.1) and populated UserDetails UserDetailsService
- UserDetails
- Express who you are and what role permissions do you have
- UserDetailsService
- Expression how to load UserDetails data dynamically
(3.2) Implement the UserDetails interface
- new
moudle/MyUserDetails
类 implements
implementationUserDetails
interface- And through the
command+1 => implement methods
Implement all the methods in the interface- Getauthpermissions list
- GetPassword password
- GetUsername user name
- IsAccountNonExpired is not expired
- IsAccountNonLocked Indicates whether the account is not locked
- IsCredentialsNonExpired Whether it has not expired
- IsEnabled Whether the account is available
- The class implementing (UserDetails) now has (user name, password, permission list, whether the account is available) and so on
@Data @AllArgsConstructor @NoArgsConstructor @Builder @Component public class MyUserDetails implements UserDetails { String password; String username; boolean accountNonExpired = true; Boolean accountNonLocked = true; Boolean credentialsNonExpired = true; Boolean enabled; // Is the account available? extends GrantedAuthority> authorities; // Set of permissions for the user}Copy the code
(3.3) Implement the UserDetailsService interface
- new
service/MyUserDetailsSerivce
类 implements
implementationUserDetailsService
interface- And through the
command+1 => implement methods
Implement theloadUserByUsername
methods - The specific process
- 1. Query related information of the user in the database through the unique id passed in during login
- For example: user name, password, permissions, account availability and other information
- 2. Assemble the queried information into a UserDetails object, that is, MyUserDetails object
- 3. Provide the MyUserDetails object as a return value to Spring-Security
- 4. Spring-security performs login, authentication, authentication and other related operations according to the obtained user information
- 1. Query related information of the user in the database through the unique id passed in during login
@Component public class MyUserDetailsService implements UserDetailsService { @Autowired MyUserDetailsServiceMapper myUserDetailsServiceMapper; @ Override public populated UserDetails loadUserByUsername (String s) throws UsernameNotFoundException {/ / s for the unique identification of the incoming landed Is not necessarily the user name / / 1 user base data loading MyUserDetails MyUserDetails = myUserDetailsServiceMapper. FindByUserName (s); If (myUserDetails = = null) {throw new UsernameNotFoundException (" the user name does not exist "); } / / 2 load the user's role List < String > roleCodes = myUserDetailsServiceMapper. FindRoleByUserName (s); / / 3 according to the character List loaded with user has permissions List < String >. Authorities = myUserDetailsServiceMapper findAuthorityByRoleCodes (roleCodes); roleCodes = roleCodes.stream() .map(rc -> "ROLE_" + rc) .collect(Collectors.toList()); authorities.addAll(roleCodes); myUserDetails.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList( String.join(",", authorities) )); return myUserDetails; }}Copy the code
Realize SecurityCofnig (3.3)
- in
config
In the newSecurityCofnig
implements
implementationWebSecurityConfigurerAdapter
interface- rewrite
configure
methods - Replace the user information we previously wrote in memory with the user information queried in the database
auth.userDetailsService(myUserDetailsService).passwordEncoder(pe)
package com.example.demo.config; import com.example.demo.service.MyUserDetailsService; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import java.io.PrintWriter; public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired MyUserDetailsService myUserDetailsService; @bean // @bean put the object in the container public PasswordEncoder PasswordEncoder() {return new BCryptPasswordEncoder(); } / / custom authentication configuration @ Override protected void the configure (AuthenticationManagerBuilder auth) throws the Exception {PasswordEncoder PE = passwordEncoder(); // Call the method defined below and return PasswordEncoder type auth.UserDetailsService (myUserDetailsService).passwordenCoder (PE); / / / / auth BCrypt encryption. InMemoryAuthentication () / /. WithUser (" admin ") / / user name / /. The password (PE) encode (" admin ")) / / password. Encryption / /. Roles (" admin ") / /. / / role and () / /. WithUser (" guest ") / /. "(" guest") / /. Roles (" guest "); } // In addition to the above method to set the username and password, // protected userDetailsService userDetailsService() {// InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); // manager.createUser(User.withUsername("admin2").password("admin2").roles("admin").build()); // return manager; //} @override public void configure(WebSecurity web) throws Exception {// Let spring-security pass JS CSS images file, Not to intercept web. Ignoring (.) antMatchers ("/js / * * ", "/ CSS / * *", "/ images / * *"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antmatchers ("/security-admin/**").hasanyRole ("admin") // This controller needs the admin role .antmatchers ("/security-common/**").hasanyRole ("common") // This controller requires guest character.anyRequest ().authenticated() Indicates that all requests except the above two are (role-level authentication), that is, only the above two require login and the corresponding role. Other are only need to log in. And (). FormLogin () / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - 【 】. LoginPage ("/login HTML ") / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 【 】 landing page ( If the following loginProcessingUrl is not set => Login page and login interface).loginProcessingURL ("/doLogin") // .loginProcessingURL ("/security-test") //---- [] Submit the URL for username and password //.usernameParameter("username") // ---------- [] Custom HTML form input name attribute //. PasswordParameter ("password") // ---------- [] Custom HTML form input name attribute // .forwardurl ("/musics") // ----------- //.defaultSuccessURL ("/musics") // ----------- SuccessHandler ((req, resp, Resp. SetContentType ("application/json; charset=utf-8"); PrintWriter writer = resp.getWriter(); writer.write(new ObjectMapper().writeValueAsString(authentication.getPrincipal())); writer.flush(); writer.close(); }). FailureHandler ((the req, resp, exception) - > {/ / = = = = = = = = = = = = = = = = = = = = = login failed callback function resp. SetContentType (" application/json; charset=utf-8"); PrintWriter writer = resp.getWriter(); writer.write(new ObjectMapper().writeValueAsString(exception.getMessage())); writer.flush(); writer.close(); }). PermitAll () / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 【 】 said: //.logouturl ("/logout") // logoutRequestMatcher(new) //.logouturl ("/logout") // logoutRequestMatcher(new) AntPathRequestMatcher("/logout", "post")) .and() .csrf().disable(); // Turn off CSRF}}Copy the code
data
Spring ws-security juejin. Cn/post / 684490… UserDetailService zhuanlan.zhihu.com/p/188747719 RBAC juejin. Cn/post / 684490… RBAC www.jianshu.com/p/ce1757360…