最近闲来无事,熟悉公司的项目框架的时候,发现公司是用的spring boot整合spring security来控制用户登录以及用户角色,权限等。之前只用过apache shiro,对spring security的了解甚少,只知道它提供的功能比shiro更强大,所以写下此文章,记录一下自己对spring security的学习过程。
spring官网上面有这么一段demo,它给我们说明了spring security自定义适配器的部分功能:
package org.springframework.security.samples.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/index").permitAll()
.antMatchers("/user/**").hasRole("USER")
.and()
.formLogin()
.loginPage("/login").failureUrl("/login-error");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
1. 与/ css / **和/ index匹配的请求是完全可访问的
2.与/ user / **匹配的请求要求用户进行身份验证,并且必须与USER角色相关联
3.使用自定义登录页面和失败URL启用基于表单的身份验证
4.configure方法重写了父类的方法,里面定义了spring security应该忽略或者拦截验证的一些url路径。
5. configureGlobal方法是确定您要如何进行身份验证,上面的demo是在内存中创建了一个用户,该用户的名称为user,密码为password,用户角色为USER。