最近在学SpringSecurity,来拦截没有登录的用户,以及验证用户是否具有权限访问某个页面,照着网上做了个简单的练习。
这里用的是Thymeleaf作为模板引擎,因为SpringBoot建议不要使用JSP,下面是SpringBoot的配置:
server:
port: 8080
servlet:
context-path: /secureTest
spring:
datasource:
name: mysql
url: jdbc:mysql://127.0.0.1:3306/spring_security
username: mysql
password: mysql
driver-class-name: com.mysql.jdbc.Driver
# mvc:
# view:
# prefix: classpath:/static/views
# suffix: .html
thymeleaf:
servlet:
content-type: text/html
prefix: classpath:/static/views/
suffix: .html
一开始我用的是mvc视图的配置来配置视图的前缀跟后缀,发现Controller返回的视图名找不到视图,一直报错,说什么在templates目录下找不到视图,我明明配置的/static/views路径,后来发现Thymeleaf有自己的前缀跟后缀配置。先创建配置一个可以访问的视图,确保正常访问没有问题。
接下来只需要配置一个Security的配置文件,启动SpringBootApplication就可以了,配置文件如下:
@EnableWebSecurity
@Configuration
public class SecurityConfigure extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").hasAnyRole("USER","ADMIN")
.antMatchers("/home").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.and()
.logout().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("user1").password("password1").roles("USER")
.and().passwordEncoder(new MyPasswordEncoder()).withUser("admin1").password("password1").roles("ADMIN");
}
}
**configure(HttpSecurity http)**方法用来配置那些URL需要进行验证
这里的antMatchers用Ant通配来匹配地址,后面的permitAll(),hasRole,hasAnyRole是用来区分这个地址是那些角色可以访问的,如果没有权限,默认都会被引导到登录界面,Security的默认登录页面是/login。
方法 | 对应 |
---|---|
permitAll | 所有人都可以访问,不需要登录 |
hasRole | 对应一个角色有访问权限 |
hasAnyRole | 对应多个角色有访问权限,多个角色就像一个多个参数方法,每个参数一个角色。 |
**configure(AuthenticationManagerBuilder auto)**方法是用来生成AuthenticationManager,AuthenticationManager是一个对用户名跟密码进行验证的类。这里直接在内存中建立两个用户user1跟admin1。
方法 | 用处 |
---|---|
inMemoryAuthentication | 对内存中的对象进行验证 |
jdbcAuthentication | 基于JDBC的对象进行验证 |
ldapAuthentication | 基于LADP进行验证 |
这里还需要传入加解密对象passwordEncoder,不然会报错There is no PasswordEncoder mapped for the id null,自己创建一个加解密对象,覆写加密算法跟比较方法,这里加密方法直接返回原始密码,比较方法拿加密密码(也就是encode()中的返回,这里我没有加密,直接返回)跟原始密码直接比较,如果一致就返回true。
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if(rawPassword.equals(encodedPassword)){
return true;
}
return false;
}
}
好了,这时可以运行SpringBootApplication了!
这时,如果没有登录用户,只有/home这个被允许所有人访问的地址,才可以直接访问,其他随便输入一个地址,都会被自动引导到登录页面。
输入内存中存在的用户user1,可以进行登录,登录后会默认转到URL“/”,如果一个用户没有“/”上的角色,即使密码正确,也会报错。
上面就是十分简单的Security配置,基本都是用的原框架来进行登录验证,以及直接在内存中创建用户验证。实际上是配置自己的登录界面,大多数都用的jdbc验证,内存验证只是用来测试,这个后面再看看怎么搞。