Spring Secure在SpringBoot中的集成

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

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

 

 

目录
相关文章
|
18天前
|
消息中间件 Java Kafka
Springboot集成高低版本kafka
Springboot集成高低版本kafka
|
24天前
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
269 0
|
29天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
415 0
|
1月前
|
NoSQL Java Redis
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
272 1
|
18天前
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
|
1天前
|
Java Docker 容器
SpringBoot项目集成XXL-job
SpringBoot项目集成XXL-job
|
1天前
|
监控 Java 应用服务中间件
spring和springboot的区别
spring和springboot的区别
11 1
|
2天前
|
Java Nacos 开发者
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
|
3天前
|
Java 关系型数据库 数据库
【SpringBoot系列】微服务集成Flyway
【4月更文挑战第7天】SpringBoot微服务集成Flyway
【SpringBoot系列】微服务集成Flyway
|
18天前
|
Java 容器
SpringBoot使用配置注解开启自动配置功能&整合spring-boot-configuration-processor
SpringBoot使用配置注解开启自动配置功能&整合spring-boot-configuration-processor
14 0