Integration of Spring Secure in SpringBoot

Spring Secure4 is not much different from Secure3 in use. Basically, you can use 4 how you use 3. And 4 is also recommended to use namespace for configuration, but since SpringBoot recommends not to use xml configuration, we are talking about not using xml here. The default introduction of sprngboot is 3, and 4 is similar.

 

There are two ways to introduce spring secure through maven in the project. If the starter of springboot is used like this:

                <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

 You can also use the secure introduction method directly:

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
		</dependency>

 The current springboot will lead to Secure3.2.8.

 

 

Next, start the configuration, just create a new class:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableWebMvcSecurity
public class WebAuthConfiguration extends WebSecurityConfigurerAdapter {}

 Here I named this class webauthconfiguration, which needs to inherit from org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.

 

Then add the Configuration annotation to this class to let springboot load the configuration when it starts. Then add the enablewebmvcsecurity annotation to start the secure configuration. As for the enableglobalmethodsecurity annotation, you can add it or not, and enable the method level configuration.

 

Now secure is added and works fine, but using the default configuration:

    protected void configure(HttpSecurity http) throws Exception {
        logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");

        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin().and()
            .httpBasic();
    }

 The default configuration says that all requests need to be authenticated securely, log in using the default form (which pops up a scary login box), and use http Basic authentication, which is via password and role.

 

We rewrite this method and add configuration according to our own needs:

http.authorizeRequests().antMatchers("/assets/", "/").permitAll()

.anyRequest().authenticated()
.and().formLogin().usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login").loginPage("/login")
.and().logout().permitAll().logoutUrl("/logout").logoutSuccessUrl("/login")
				.logoutSuccessHandler(logoutSuccessHandler)
				.invalidateHttpSession(true).addLogoutHandler(logoutHandler).deleteCookies(new String[] { "cookie名字" })
				.and().rememberMe();

 The first line means that access to / and urls matching the /assets/** pattern can be accessed directly, and the other ones require authentication. Use form to log in, why specify this? Because spring will look up the username and password domain parameters from the request. From which request? The default is /login, which can be customized by login(String s). The parameters for form submission can also be customized via usernameParameter() and passwordParamter(). If you do not use the default popup box and use your own page, the action of the form must be the same as that specified by loginProcessingUrl(), and of course it needs to be the post method.

Further down is to allow spring to control logout. The default access to /logout will perform logout, spring will invalidate the session, and clean up the cookies generated by rememberMe. logoutUrl() can customize the logout url. The jump url after successful logout is specified by logoutSuccessUrl(). The default is /login?logout. You can judge the logout parameter on this page to prompt the user to logout successfully.

To configure automatic login later, use the rememberMe() method. There are two methods for automatic login, one is configured by org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices class, and the other is configured by org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices, the difference is whether the database is used or not.

 

Login authentication requires a new autowired method configureGlobal(auth) in this class:

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.jdbcAuthentication().dataSource(dataSource)
		.usersByUsernameQuery("select username,password, enabled from users
		where username=?")
		.authoritiesByUsernameQuery("select username, role from user_roles
		where username=?");
	}

 

There are four methods. The first is to use memory configuration, which is to use constant strings directly, which I think are rarely used; the second is the jdbc method used in the above code, the third is the ldap method; the fourth is to use userDetailsService:

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
	auth.eraseCredentials(false).userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
	}

 Because automatic login is required, eraseCredentials is set to false.

 

So far, the login authentication, including automatic login and url access authentication, and logout have been configured. You can try adding a user to the database. I just saw that the passwordEncoder was used when logging in, so the password should also be encrypted when inserting a user.

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327042069&siteId=291194637