上一篇:【SpringBoot攻略十一、自定义ISqlInjector,添加updateAllColumnById通用方法】
pom.xml添加依赖
<!-- spring boot spring-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
主要配置类WebSecurityConfig
package com.javasgj.springboot.springsecurity;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
/**
* 参考【认证、授权攻略三:spring security】
*
* @EnableWebSecurity:开启spring security功能;
* debug: 是否开启debug模式,默认为false;
*/
@Configuration
@EnableWebSecurity(debug = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 类似<security:authentication-manager>
// 测试,用户保存在内存中
/*auth
.inMemoryAuthentication()
.withUser("admin").password("{noop}123").roles("USER"); // USER自动加ROLE_前缀*/
// 数据库加载用户
auth
//.eraseCredentials(false) // 是否清空凭证即密码
.userDetailsService(jdbcDaoImpl()) // 指定获取用户信息的userDetailsService
.passwordEncoder(bCryptPasswordEncoder()); // 设置加密方式
// 缓存用户信息,可以参考maven项目SSM的spring-security.xml中的配置
}
@Override
public void configure(WebSecurity web) throws Exception {
// 用于Web静态资源的权限控制,忽略静态资源
web.ignoring().antMatchers("/static/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// 类似<security:http>
http
.authorizeRequests()
.antMatchers("/error1.jsp", "/accessDeny.jsp").permitAll() // 匹配页面,不需要认证就可以访问