Spring Security 是 Spring 家族中的一个安全管理框架,实际上,在 Spring Boot 出现以前,Spring Security 就已经发展了多年了,可是使用的并很少,安全管理这个领域,一直是 Shiro 的天下。java
相对于 Shiro,在 SSM/SSH 中整合 Spring Security 都是比较麻烦的操做,因此,Spring Security 虽然功能比 Shiro 强大,可是使用反而没有 Shiro 多(Shiro 虽然功能没有 Spring Security 多,可是对于大部分项目而言,Shiro 也够用了)。web
自从有了 Spring Boot 以后,Spring Boot 对于 Spring Security 提供了 自动化配置方案,能够零配置使用 Spring Security。spring
所以,通常来讲,常见的安全管理技术栈的组合是这样的:数据库
注意,这只是一个推荐的组合而已,若是单纯从技术上来讲,不管怎么组合,都是能够运行的。json
咱们来看下具体使用。后端
在 Spring Boot 中使用 Spring Security 很是容易,引入依赖便可:浏览器
pom.xml 中的 Spring Security 依赖:安全
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
复制代码
只要加入依赖,项目的全部接口都会被自动保护起来。app
咱们建立一个 HelloController:框架
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
}
复制代码
访问 /hello
,须要登陆以后才能访问。
当用户从浏览器发送请求访问 /hello
接口时,服务端会返回 302
响应码,让客户端重定向到 /login
页面,用户在 /login
页面登陆,登录成功以后,就会自动跳转到 /hello
接口。
另外,也可使用 POSTMAN
来发送请求,使用 POSTMAN
发送请求时,能够将用户信息放在请求头中(这样能够避免重定向到登陆页面):
经过以上两种不一样的登陆方式,能够看出,Spring Security 支持两种不一样的认证方式:
默认状况下,登陆的用户名是 user
,密码则是项目启动时随机生成的字符串,能够从启动的控制台日志中看到默认密码:
这个随机生成的密码,每次启动时都会变。对登陆的用户名/密码进行配置,有三种不一样的方式:
前两种比较简单,第三种代码量略大,本文就先来看看前两种,第三种后面再单独写文章介绍,也能够参考个人微人事项目。
能够直接在 application.properties 文件中配置用户的基本信息:
spring.security.user.name=javaboy
spring.security.user.password=123
复制代码
配置完成后,重启项目,就可使用这里配置的用户名/密码登陆了。
也能够在 Java 代码中配置用户名密码,首先须要咱们建立一个 Spring Security 的配置类,集成自 WebSecurityConfigurerAdapter 类,以下:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//下面这两行配置表示在内存中配置了两个用户
auth.inMemoryAuthentication()
.withUser("javaboy").roles("admin").password("$2a$10$OR3VSksVAmCzc.7WeaRPR.t0wyCsIj24k0Bne8iKWV1o.V9wsP8Xe")
.and()
.withUser("lisi").roles("user").password("$2a$10$p1H8iWa8I4.CA.7Z8bwLjes91ZpY.rYREGHQEInNtAp4NzL6PLKxi");
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
复制代码
这里咱们在 configure 方法中配置了两个用户,用户的密码都是加密以后的字符串(明文是 123),从 Spring5 开始,强制要求密码要加密,若是非不想加密,可使用一个过时的 PasswordEncoder 的实例 NoOpPasswordEncoder,可是不建议这么作,毕竟不安全。
Spring Security 中提供了 BCryptPasswordEncoder 密码编码工具,能够很是方便的实现密码的加密加盐,相同明文加密出来的结果老是不一样,这样就不须要用户去额外保存盐
的字段了,这一点比 Shiro 要方便不少。
对于登陆接口,登陆成功后的响应,登陆失败后的响应,咱们均可以在 WebSecurityConfigurerAdapter 的实现类中进行配置。例以下面这样:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
VerifyCodeFilter verifyCodeFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
http
.authorizeRequests()//开启登陆配置
.antMatchers("/hello").hasRole("admin")//表示访问 /hello 这个接口,须要具有 admin 这个角色
.anyRequest().authenticated()//表示剩余的其余接口,登陆以后就能访问
.and()
.formLogin()
//定义登陆页面,未登陆时,访问一个须要登陆以后才能访问的接口,会自动跳转到该页面
.loginPage("/login_p")
//登陆处理接口
.loginProcessingUrl("/doLogin")
//定义登陆时,用户名的 key,默认为 username
.usernameParameter("uname")
//定义登陆时,用户密码的 key,默认为 password
.passwordParameter("passwd")
//登陆成功的处理器
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("success");
out.flush();
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("fail");
out.flush();
}
})
.permitAll()//和表单登陆相关的接口通通都直接经过
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("logout success");
out.flush();
}
})
.permitAll()
.and()
.httpBasic()
.and()
.csrf().disable();
}
}
复制代码
咱们能够在 successHandler 方法中,配置登陆成功的回调,若是是先后端分离开发的话,登陆成功后返回 JSON 便可,同理,failureHandler 方法中配置登陆失败的回调,logoutSuccessHandler 中则配置注销成功的回调。
若是某一个请求地址不须要拦截的话,有两种方式实现:
推荐使用第二种方案,配置以下:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/vercode");
}
}
复制代码
Spring Security 另一个强大之处就是它能够结合 OAuth2 ,玩出更多的花样出来,这些咱们在后面的文章中再和你们细细介绍。
本文就先说到这里,有问题欢迎留言讨论。
关注公众号【江南一点雨】,专一于 Spring Boot+微服务以及先后端分离等全栈技术,按期视频教程分享,关注后回复 Java ,领取松哥为你精心准备的 Java 干货!