美文网首页Spring Secuity
spring secuity快速入门

spring secuity快速入门

作者: 二月_春风 | 来源:发表于2018-01-29 11:20 被阅读222次

我们使用springmvc web项目基于xml配置文件和注解配置类二种方式来写一个快速入门。

基于配置文件的spring security的快速入门

  • 加入依赖

加入springmvc,spring secuityservlet的一些依赖,配置jetty的插件,配置端口是8001,contextPath是"/"

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.2.3.RELEASE</version>
        </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>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>secuity-quickstart-xml</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.3.v20170317</version>
                <configuration>
                    <httpConnector>
                        <port>8001</port>
                    </httpConnector>
                    <webApp>
                        <contextPath>/</contextPath>
                    </webApp>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • 配置系统初始化类
public class WebAppInitializer extends AbstractDispatcherServletInitializer{

    //配置配置文件,创建context上下文
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        XmlWebApplicationContext context = new XmlWebApplicationContext();
        context.setConfigLocation("classpath:applicationContext.xml");
        return context;
    }

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

    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}
  • 配置初始化spring secuity
public class WebAppSecuityInitializer extends AbstractSecurityWebApplicationInitializer{


    @Override
    protected String getDispatcherWebApplicationContextSuffix() {
        return AbstractDispatcherServletInitializer.DEFAULT_SERVLET_NAME;
    }
}
  • 配置文件
    配置容器扫描的包路径,配置spring security的用户名密码,url权限配置
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:s="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <mvc:annotation-driven/>
    
    <context:component-scan base-package="com.zhihao.miao.secuity"/>

    <!--处理静态资源,不配置静态资源被拦截了-->
    <mvc:default-servlet-handler />

    <!--用户名密码配置在配置文件-->
    <s:user-service>
        <s:user name="zhangsan" authorities="ROLE_GUEST" password="654321" />
        <s:user name="zhihao.miao" authorities="ROLE_USER" password="123456" />
        <s:user name="lisi" authorities="ROLE_USER,ROLE_ADMIN" password="12345678" />
    </s:user-service>

    <s:http>
        <s:intercept-url pattern="/hello" access="hasRole('ROLE_GUEST')" />
        <s:intercept-url pattern="/home" access="hasRole('ROLE_USER')" />
        <s:intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />
        <!--不需要权限认证-->
        <s:intercept-url pattern="/**/*.html" access="permitAll" />
        <s:intercept-url pattern="/**/*.css" access="permitAll" />
        <s:intercept-url pattern="/**/*.js" access="permitAll" />
        <s:intercept-url pattern="/**/*.jpg" access="permitAll" />
        <s:intercept-url pattern="/**/*.png" access="permitAll" />
        <!--只要是使用上面的权限就能访问-->
        <s:intercept-url pattern="/**" access="authenticated" />
        <!--使用spring secuity帮我们创建一个登录页面-->
        <s:form-login />
    </s:http>

</beans>
  • 进行相关的验证

http://localhost:8001/hello
http://localhost:8001/home
http://localhost:8001/admin

分别使用不同的用户名和密码进行验证

基于配置方式的spring security快速入门

  • 加入maven依赖

加入springmvc,spring secuityservlet的一些依赖,配置jetty的插件,配置端口是8001,contextPath是"/"

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.2.3.RELEASE</version>
        </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>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>


    <build>
        <finalName>secuity-quickstart-config</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.3.v20170317</version>
                <configuration>
                    <httpConnector>
                        <port>8001</port>
                    </httpConnector>
                    <webApp>
                        <contextPath>/</contextPath>
                    </webApp>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • 定义系统启动类
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    //系统启动的时候的根类
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    //设置成/*表示拦截静态的文件
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

}
  • web入口类
/**
 *
 * 入口类,启动spring mvc,启动spring secuity
 */
@EnableWebMvc
@EnableWebSecurity
@ComponentScan("com.zhihao.miao.secuity")
public class WebAppConfig extends WebMvcConfigurerAdapter {
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
  • spring security配置类
/**
 *
 * 初始化spring security
 */
public class WebAppSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

    protected String getDispatcherWebApplicationContextSuffix() {
        return AbstractDispatcherServletInitializer.DEFAULT_SERVLET_NAME;
    }
}
  • 具体的controller
@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello spring secuity";
    }

    @GetMapping("/home")
    public String home(){
        return "home spring security";
    }

    @GetMapping("/admin")
    public String admin(){
        return "admin spring secuity";
    }
}
  • 在webapp目录下定义一些静态资源

  • 权限用户名密码的具体配置

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("GUEST");
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");


        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();
        //http.authorizeRequests().anyRequest().access("authenticated");

        http.formLogin();
    }
}

使用mvn clean jetty:run启动程序进行验证,不同的用户名密码访问不同的资源。

参考资料

官方文档
Spring Security 从入门到进阶系列教程

相关文章

网友评论

    本文标题:spring secuity快速入门

    本文链接:https://www.haomeiwen.com/subject/mihxzxtx.html