Spring Secure在SpringBoot中的集成

Spring Security 4 配置指南
本文介绍如何在 Spring Boot 项目中配置 Spring Security 4,包括使用 Maven 引入依赖、创建配置类、自定义登录和注销流程、实现基于数据库的身份验证等关键步骤。

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,因此插入用户的时候也要这样加密密码。

 

 

<think>好的,用户想要将Spring Security与Spring Boot 1.5.9版本整合,需要配置示例和教程。首先,我需要回忆一下Spring Boot 1.5.x版本的特性,因为不同版本可能有不同的配置方式。根据引用[1]提到的,Spring Boot 1.5.9使用Maven或Gradle进行依赖管理,所以应该从添加依赖开始。 用户提到的引用[4]中提到了Spring Security的认证和授权,所以整合的关键在于正确引入Spring Security的依赖。查看引用[3],那里有一个依赖示例是spring-security-oauth2-jose,但不确定是否适用于基本整合。可能需要更基础的Spring Security starter。 在Spring Boot中,通常通过添加spring-boot-starter-security依赖来集成Security。但需要确认1.5.9版本是否支持这种方式。根据经验,Spring Boot 1.5.x确实支持starter,所以应该在pom.xml中添加该依赖。 接下来,配置类需要扩展WebSecurityConfigurerAdapter,并重写configure方法设置安全规则。记得启用Web安全,使用@EnableWebSecurity注解。同时,可能需要配置内存中的用户认证,比如使用inMemoryAuthentication()来添加测试用户。 另外,引用[2]提到了Actuator的依赖,如果用户需要健康检查等端点,可能需要配置这些端点的访问权限,避免被Security拦截。比如,对于/actuator/health允许所有访问,其他端点需要认证。 用户可能还关心如何自定义登录页面或禁用默认的安全配置。不过基本整合的话,可能只需要默认的HTTP Basic认证。但需要明确说明默认行为,比如自动生成的密码,或者如何配置静态用户。 最后,要确保提供的代码示例符合Spring Boot 1.5.9的语法,比如是否使用旧版的配置方式,以及是否需要排除自动配置。可能还需要提醒用户关于版本兼容性的问题,确保所有依赖的版本与1.5.9匹配,避免冲突。 总结步骤:添加依赖、创建配置类、设置安全规则、处理Actuator端点、示例代码验证。同时,生成相关问题,帮助用户深入理解,比如自动配置原理、OAuth2整合等。</think>以下是Spring Security与Spring Boot 1.5.9整合的配置示例及教程: ### 一、基础整合步骤 1. **添加Maven依赖** ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> ``` *Spring Boot 1.5.9会自动管理依赖版本[^1]* 2. **创建安全配置类** ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("admin").password("{noop}admin123").roles("ADMIN"); } } ``` *使用`{noop}`前缀表示明文密码[^4]* ### 二、关键配置说明 1. **HTTP安全配置** $$ \begin{cases} \text{permitAll() 用于开放公共路径} \\ \text{authenticated() 要求认证} \\ \text{hasRole() 角色控制} \end{cases} $$ 2. **整合Actuator端点** ```yaml # application.yml management: security: enabled: false # 1.5.x旧版需禁用安全端点[^2] endpoints: health: sensitive: false ``` ### 三、验证流程 1. 创建测试Controller ```java @RestController public class DemoController { @GetMapping("/public/hello") public String publicHello() { return "Public Access"; } @GetMapping("/secure/hello") public String secureHello() { return "Secure Area"; } } ``` 2. 启动日志会显示生成的随机密码(如启用默认认证): ``` Using default security password: 78fa095d-3f4c-48b1-9b3d-8620e9d6cfd3 ``` ### 四、最佳实践建议 1. 生产环境应使用加密密码存储: ```java @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } ``` 2. 建议配合`@EnableGlobalMethodSecurity`启用方法级安全控制[^4]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值