spring boot 项目整合 spring security 需要pom.xml 引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
然后在项目中创建security的Config文件
package com.springboot.wangpan.config;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @author homolo
* @version 1.0
* @date 20-8-25 上午10:02
*/
@Configuration
@EnableWebSecurity
public class securityConfig extends WebSecurityConfigurerAdapter {
/**
WebSecurity: 全局请求忽略规则配置(比如说静态文件,比如说注册页面)、全局HttpFirewall配置、是否debug配置、全局
SecurityFilterChain配置、privilegeEvaluator、expressionHandler、securityInterceptor;
*/
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity.ignoring().antMatchers("/", "/css/**", "/img/**", "/js/**");
}
/**
HttpSecurity:具体的权限控制规则配置。一个这个配置相当于xml配置中的一个标签。各种具体的认证机制的相关配置,
OpenIDLoginConfigurer、AnonymousConfigurer、FormLoginConfigurer、HttpBasicConfigurer等。
*/
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/unregistered/**").permitAll()
.antMatchers("/userService/controller/**").permitAll()
.anyRequest().authenticated().and()
.formLogin().loginPage("/").permitAll()
.and().logout().permitAll();
httpSecurity.csrf().disable();
}
/**
AuthenticationManagerBuilde:用来配置全局的认证相关的信息,其实就是AuthenticationProvider和UserDetailsService,
前者是认证服务提供商,后者是用户详情查询服务;
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("123456")).roles("USER");
}
/**
注入 PasswordEncoder bean 进行密码加密
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}