Spring MVC 整合 Spring Security 纯java 配置

Spring MVC 整合 Spring Security 纯java 配置

Scroll Down

导入jar包

需要注意spring security和spring的版本对应

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.security.version>5.3.6.RELEASE</spring.security.version>
    <spring.version>5.2.11.RELEASE</spring.version>
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.26</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>${spring.security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>${spring.security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.1</version>
    </dependency>
</dependencies>

配置DelegatingFilterProxy过滤器

配置spring security过滤器

/*
 * 加载DelegatingFilterProxy过滤器
 * */
public class WebAppSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

}

spring security 配置类

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    // 把用户信息存储在内存中
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        // 正常用户
        manager.createUser(User.builder().username("admin").password("{noop}123456").roles("admin").build());
        // 用户帐号已被锁定
        manager.createUser(User.builder().username("user1").password("{noop}123456").roles("admin").accountLocked(true).build());
        // 用户帐号已过期
        manager.createUser(User.builder().username("user2").password("{noop}123456").roles("admin").accountExpired(true).build());
        // 用户凭证已过期
        manager.createUser(User.builder().username("user3").password("{noop}123456").roles("admin").credentialsExpired(true).build());
        // 用户已失效
        manager.createUser(User.builder().username("user4").password("{noop}123456").roles("admin").disabled(true).build());
        return manager;
    }
    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        // 显示用户不存在,默认提示用户名或密码错误
        provider.setHideUserNotFoundExceptions(false);
        provider.setUserDetailsService(userDetailsService());
        return provider;
    }
    @Bean //加载中文认证提示信息
    public ReloadableResourceBundleMessageSource messageSource(){
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        //加载org/springframework/security包下的中文提示信息 配置文件
        messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");
        return messageSource;
    }
}

spring mvc配置类

/*
 * spring mvc配置类
 * */
@EnableWebMvc
@ComponentScan(value = "zone.lxy", includeFilters = @ComponentScan.Filter(Controller.class))
public class WebConfig implements WebMvcConfigurer {

}

配置WebApplicationInitializer

/*
 *   加载各种配置类
 * */
public class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{WebSecurityConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

}

Controller配置

@RestController
@Controller
public class HelloController {
    @GetMapping("/")
    @Secured("ROLE_admin")
    public Object index() {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", "200");
        map.put("msg", "hello world!");
        return map;
    }
}

日志配置

log4j.rootLogger=info,console,rollingFile

log4j.logger.zone.lxy=debug
log4j.logger.org.springframework.security=debug

# 控制台输出
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c - %m%n

# 每天产生一个日志文件
log4j.appender.rollingFile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.rollingFile.DatePattern='.'yyyy-MM-dd
log4j.appender.rollingFile.File = D:/log/log4j.log
log4j.appender.rollingFile.Append = true
log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c - %m%n
log4j.appender.rollingFile.encoding=UTF-8
# 最多保存最近7天的日志
log4j.appender.rollingFile.MaxBackupIndex=7