博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Secure在SpringBoot中的集成
阅读量:6916 次
发布时间:2019-06-27

本文共 3557 字,大约阅读时间需要 11 分钟。

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

 

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

org.springframework.boot
spring-boot-starter-security

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

org.springframework.security
spring-security-web
org.springframework.security
spring-security-config

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

 

 

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

@EnableGlobalMethodSecurity(prePostEnabled = true)@Configuration@EnableWebMvcSecuritypublic 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,因此插入用户的时候也要这样加密密码。

 

 

转载地址:http://ohacl.baihongyu.com/

你可能感兴趣的文章
相关时间处理类
查看>>
Java线程同步:synchronized锁住的是代码还是对象
查看>>
Android-PickerView系列之介绍与使用篇(一)
查看>>
shell之文本处理-echo
查看>>
Android 网络提交数据(使用Asynchronous Http Client)
查看>>
QQ空间g_tk加密算法PHP版
查看>>
解决Maven项目中的错误:Cannot change version of project
查看>>
如何避免在<a href=="#"> 中使用#
查看>>
我的 K8S 架构搭建 之旅
查看>>
idea使用笔记
查看>>
CSS实现树形结构效果
查看>>
我的友情链接
查看>>
关于xocde7.1.1安装VVDocumenter Xcode快速添加注释插件遇到的问题
查看>>
我的友情链接
查看>>
SpringMVC同名参数绑定问题
查看>>
软件级负载均衡器(LVS/HAProxy/Nginx)的特点简介和对比
查看>>
关于Session和Cookie简单实例
查看>>
每天多一点
查看>>
SpringMVC统一异常处理
查看>>
到底什么是自动化运维
查看>>