欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Secure在SpringBoot中的集成

程序员文章站 2022-07-14 09:49:54
...

Spring Secure4在使用上和Secure3差别不大,基本上怎么使用3就可以怎么使用4。而且4也是推荐使用命名空间进行配置,不过由于SpringBoot推荐不使用xml配置,所以我们这里说的都是不使用xml的。sprngboot默认引入的是3,4也类似。

 

要在项目中通过maven引入spring secure有两种方式,如果使用springboot的starter是这样的:

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

 也可以直接使用secure的引入方式:

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

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

 现在的springboot会把Secure3.2.8引过来。

 

 

接下来开始进行配置,只需要新建一个类即可:

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

 这里我把这个类命名为webauthconfiguration,它需要继承自org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter。

 

然后给这个类添加Configuration注解,来让springboot启动的时候加载该配置。然后加上enablewebmvcsecurity注解启动secure配置。至于enableglobalmethodsecurity注解加不加都可以,开启方法级别配置的。

 

到现在secure就添加好了而且可以正常工作,但是使用的是默认配置:

    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();
    }

 默认配置说所有的请求都需要进行安全认证,登陆使用默认的form表单(会弹出一个可怕的登陆框),并使用http Basic 认证,就是通过密码和角色。

 

我们重新这个方法,并根据自己的需要增加配置:

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();

 第一行是说访问/和匹配/assets/**模式的url都可以直接访问,下面说其他的需要认证。使用form表单登录,为什么要指定这个呢?因为spring会从请求中查找username和password域参数。从哪个请求中呢?默认是/login,可以通过login(String s)自定义。表单提交的参数也可以通过usernameParameter()和passwordParamter()自定义。如果不使用默认的弹出框而使用自己的页面,表单的action必须和loginProcessingUrl()指定的一样,当然也需要是post方式。

再往下是允许spring控制登出。默认访问/logout会执行登出,spring会使session无效,并清理rememberMe生成的cookie。logoutUrl()可以自定义登出的url,成功登出后的跳转url由logoutSuccessUrl()指定,默认是/login?logout,你可以这个页面判断有Logout参数就提示用户登出成功。

再往后配置自动登录,使用rememberMe()方法。自动登录有两种方法,一个是由org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices类配置,另一个由org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices配置,差别是用不用数据库。

 

登录认证需要在这个类中新建一个autowired方法configureGlobal(auth):

	@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=?");
	}

 

有四种方法,第一种使用内存配置,就是直接使用常量串,我感觉用的很少;第二种是上面这段代码用的jdbc方式,第三种是ldap方式;第四种是使用userDetailsService:

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

 因为需要自动登录,就把eraseCredentials设为false。

 

到现在为止,就把登录认证包括自动登录和url访问认证以及登出配好了。可以往数据库加入一个用户试一下,刚才看到登录的时候使用了passwordEncoder,因此插入用户的时候也要这样加密密码。