Spring security也是spring家族中的一员,使用spring boot集成spring security非常的方便,下面就通过一个例子来讲解一下如何在spring boot中集成spring security

1.1  创建mavean工程springboot_security

Pom.xml

<parent>
    <
groupId>org.springframework.bootgroupId>
    <
artifactId>spring-boot-starter-parentartifactId>
    <
version>2.0.6.RELEASEversion>
parent>
<
properties>
    <
project.build.sourceEncoding>UTF‐8project.build.sourceEncoding>
    <
maven.compiler.source>1.8maven.compiler.source>
    <
maven.compiler.target>1.8maven.compiler.target>
properties>
<
dependencies>
   

   
<dependency>
        <
groupId>org.springframework.bootgroupId>
        <
artifactId>spring-boot-starter-webartifactId>
    dependency>

   

   
<dependency>
        <
groupId>org.springframework.bootgroupId>
        <
artifactId>spring-boot-starter-securityartifactId>
    dependency>


   

   
<dependency>
        <
groupId>javax.servletgroupId>
        <
artifactId>javax.servlet-apiartifactId>

    dependency>
   

   
<dependency>
        <
groupId>javax.servletgroupId>
        <
artifactId>jstlartifactId>
    dependency>

    <
dependency>
        <
groupId>org.springframework.bootgroupId>
        <
artifactId>spring-boot-starter-tomcatartifactId>

    dependency>
   

   
<dependency>
        <
groupId>org.apache.tomcat.embedgroupId>
        <
artifactId>tomcat-embed-jasperartifactId>

    dependency>
    <
dependency>
        <
groupId>org.projectlombokgroupId>
        <
artifactId>lombokartifactId>
        <
version>1.18.0version>
    dependency>
dependencies>
<
build>
    <
finalName>security-springbootfinalName>
    <
pluginManagement>
        <
plugins>
            <
plugin>
                <
groupId>org.apache.tomcat.mavengroupId>
                <
artifactId>tomcat7-maven-pluginartifactId>
                <
version>2.2version>
            plugin>
            <
plugin>
                <
groupId>org.apache.maven.pluginsgroupId>
                <
artifactId>maven-compiler-pluginartifactId>
                <
configuration>
                    <
source>1.8source>
                    <
target>1.8target>
                configuration>
            plugin>

            <
plugin>
                <
artifactId>maven-resources-pluginartifactId>
                <
configuration>
                    <
encoding>utf-8encoding>
                    <
useDefaultDelimiters>trueuseDefaultDelimiters>
                    <
resources>
                        <
resource>
                            <
directory>src/main/resourcesdirectory>
                            <
filtering>truefiltering>
                            <
includes>
                                <
include>**/*include>
                            includes>
                        resource>
                        <
resource>
                            <
directory>src/main/javadirectory>
                            <
includes>
                                <
include>**/*.xmlinclude>
                            includes>
                        resource>
                    resources>
                configuration>
            plugin>
        plugins>
    pluginManagement>
build>

 

 

1.2  resources下添加springboot配置文件,application.properties

server.port=8080

 

1.3  创建springboot启动类

@SpringBootApplication
public class securityApplication {
   
public static void main(String[] args){
        SpringApplication.run(securityApplication.
class,args);
    }
}

 

1.4  创建springmvc配置类

 

@Configuration

public class WebConfig implements WebMvcConfigurer {
   
@Override
   
public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController(
"/").setViewName("redirect:/login");
    }
}

1.5  application.properties中配置视图解析器的属性:

spring.mvc.view.prefix=/WEB‐INF/views/
spring.mvc.view.suffix=.jsp

 

1.6  创建spring security的配置文件

@Configuration
public class WebSecurityConfig  extends WebSecurityConfigurerAdapter {
   
//配置用户信息服务
   
@Bean
   
public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager =
new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername(
"zhangsan").password("123").authorities("p1").build());
        manager.createUser(User.withUsername(
"lisi").password("456").authorities("p2").build());
       
return manager;
    }
   
@Bean
   
public PasswordEncoder passwordEncoder() {
        
return NoOpPasswordEncoder.getInstance();
    }
   
//配置安全拦截机制
   
@Override
   
protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(
"/r/r1").hasAuthority("p1")
                .antMatchers(
"/r/r2").hasAuthority("p2")
                .antMatchers(
"/r/**").authenticated()//所有/r/**的请求必须认证通过
               
.anyRequest().permitAll()//除了/r/**,其它的请求可以访问
               
.and()
                .formLogin()
//允许表单登录
                
.successForwardUrl("/login-success");//自定义登录成功的页面地址
   
}
}

 

1.7  创建控制器:LoginController

@RestController
public class LoginController {
   
@RequestMapping(value = "/login-success",produces = {"text/plain;charset=UTF-8"})
   
public String loginSuccess(){
       
return " 登录成功";
    }

   
/**
     *
测试资源1
     * @return
    
*/
   
@GetMapping(value = "/r/r1",produces = {"text/plain;charset=UTF-8"})
   
public String r1(){
       
return " 访问资源1";
    }

   
/**
     *
测试资源2
     * @return
    
*/
   
@GetMapping(value = "/r/r2",produces = {"text/plain;charset=UTF-8"})
   
public String r2(){
       
return " 访问资源2";
    }
}

测试