How to integrate SpringSecurity in SpringBoot
SpringBoot how to integrate SpringSecurity, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
1. Guide package org.springframework.boot spring-boot-starter-security2. Test @ RestControllerpublic class HelloController {@ GetMapping ("/ hello") public String hello () {return "Hello";}}
Accessing http://localhost:8080/hello will automatically jump to the login page.
Default user name user
The default password is displayed in the console
Second, configure the user name and password required for security in the configuration file or code. First, configure spring.security.user.name=userspring.security.user.password=123spring.security.user.roles=admin in the configuration file. Second, configure the user name and password in the code.
Create a new SecurityConfig .java class
@ Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {/ / remove the spring5 must password encryption restriction @ Bean PasswordEncoder passwordEncoder () {return NoOpPasswordEncoder.getInstance () } / / the second: configure the user name and password @ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication () .withUser ("terry"). Password ("123"). Roles (" admin "). And (). WithUser (" tt "). Password (" user "). Roles (" user ");}} three configurations HttpSecurity1. Then the above configuration file writes @ Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {/ / remove the spring5 must password encryption restriction @ Bean PasswordEncoder passwordEncoder () {return NoOpPasswordEncoder.getInstance () } / / second: configure the user name and password @ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication () .withUser ("terry") .password ("123") .roles (" admin ") .and () .withUser (" tt ") .password (" 456 ") .roles (" user ") in the code. } / / HttpSecurity configuration @ Override protected void configure (HttpSecurity http) throws Exception {http.authorizeRequests () .antMatrices ("/ admin/**"). HasRole ("admin") .antMatrices ("/ user/**") .hasAnyRole ("admin", "user") / / .antMatch.Match.user/** ("hasAnyRole ('user'"). ) .anyRequest () .authenticated () .formLogin () .loginProcessingUrl ("/ doLogin") .permitAll () .and () .csrf () .disable () / / to use postman to prevent it from being considered a csrf attack}} 2. Test @ RequestMapping ("/ admin/hello") public String admin () {return "Hello admin";} @ RequestMapping ("/ user/hello") public String user () {return "hello user";} is it helpful for you to read the above? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.