Spring security基本环境搭建

整个阴间版本,不推荐在项目里这样去使用,直接使用springboot就行了。这里只是为了更好的了解框架。
既有 xml 配置,也有servlet3.0 的方式加载,不过这2种方式都是基于spring注解来做的。

Spring security基本环境搭建

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zzhua</groupId>
    <artifactId>demo-spring-security</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!--整合spring-security-->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
-->
    </dependencies>

    <build>
        <finalName>demo-spring-security</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <!-- 配置端口 -->
                        <port>8080</port>
                        <!-- 配置urlencoding -->
                        <uriEncoding>UTF-8</uriEncoding>
                        <!-- 配置项目的访问路径 -->
                        <path>/</path>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>


</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>
    <!-- 使用spring 监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Spring核心配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.zzhua.config.AppConfig</param-value>
    </context-param>

    <!-- 配置SpringMVC -->
    <servlet>
        <servlet-name>springMvc</servlet-name>
        <servlet-class>com.zzhua.config.CustomizeDispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.zzhua.config.MyWebConfig</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 代理过滤器 -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

AppConfig

@Configuration
@Import({MySecurityConfig.class})
public class AppConfig {

}

CustomizeDispatcherServlet

public class CustomizeDispatcherServlet extends DispatcherServlet {
    public Class<?> getContextClass() {
        return AnnotationConfigWebApplicationContext.class;
    }
}

Servlet3.0 配置(可忽略)

MyWebApplicationInitializer

public class MyWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
    }

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

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

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

SpringSecurityApplicationInitializer

// 目的是为了配置: DelegatingFilterProxy去包含springSecurityFilterChain的名字
public class SpringSecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
    public SpringSecurityApplicationInitializer() {
    }
}
@Configuration
@EnableWebMvc
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackages = "com.zzhua.controller"
        ,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION
        ,classes = Service.class)})
public class MyWebConfig implements WebMvcConfigurer {

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

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(responseBodyConverter());
    }

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        return new StringHttpMessageConverter(Charset.forName("UTF-8"));
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

}

MySecurityConfig

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() // 关闭csrf
                .authorizeRequests()
                .antMatchers("/r/r1").hasAuthority("p1")
                .antMatchers("/r/r2").hasAuthority("p2")
                .antMatchers("/r/r3").hasRole("admin")
                .antMatchers("/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .formLogin()
                    // .successForwardUrl("/login-success") // 登录成功之后,转发到此url
                    .successHandler(
                            // 主要是想登录成功之后修改掉浏览器地址栏的url,所以改为重定向而非转发
                            (request, response, authentication) ->
                                    response.sendRedirect("/login-success"))
                    .loginProcessingUrl("/doLogin")
                    .loginPage("/login")
                    .permitAll()
                .and()
                .logout()
                    .logoutUrl("/doLogout")
                    .logoutSuccessUrl("/login")

        ;
    }

 // 配置用户信息

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        // 角色和权限的区别就是:角色前面多了个ROLE_
        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1","ROLE_admin").build());
        manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
        return manager;
        // return new CustomizeUserDetailsService();
    }

 // 密码匹配器

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }


}

IndexController

@Controller
public class IndexController {

    @RequestMapping("index")
    public String index() {
        return "index";
    }

    @RequestMapping("login-success")
    public String loginSuccess() {
        return "login_success";
    }
}

RController

@RestController
@RequestMapping("r")
public class RController {
    /**
     * 测试资源1
     *
     * @return
     */
    @GetMapping(value = "r1")
    public String r1() {
        return " 访问资源1";
    }

    /**
     * 测试资源2
     *
     * @return
     */
    @GetMapping(value = "r2")
    public String r2() {
        return " 访问资源2";
    }

    @GetMapping(value = "r3")
    public String r3() {
        return " 访问资源3";
    }

    @RequestMapping("r4")
    @PreAuthorize("hasAnyRole('admin')")
    public String r4() {
        return "访问资源4";
    }
}

jsp页面

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
 halo~
</body>
</html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form method="post" action="/doLogin">
        用户名:<input type="text" name="username">
        密码:  <input type="text" name="password">
        <input type="submit" value="提交">
    </form>
</body>
</html>

login_success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    登录成功
</body>
</html>

out.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    退出成功
</body>
</html>
上一篇:SSM---SpringMVC


下一篇:SSM整合pom文件