Spring Security 入门上手篇二

/ SpringSecurity / 没有评论 / 1555浏览

Spring Security 入门上手

依赖引入

<?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>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.20.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.zealzhangz</groupId>
    <artifactId>spring-security-guide</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>spring-security-guide</name>
    <description>Demo project for Spring Security</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.2 创建一个不受安全限制的web应用

这是一个首页,不受安全限制

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>

<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
</body>
</html>

这个简单的页面上包含了一个链接,跳转到”/hello”。对应如下的页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>

接下来配置Spring MVC,使得我们能够访问到页面。

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }
}

2.3 配置 Spring Security

一个典型的安全配置如下所示:

@Configuration
@EnableWebSecurity <1>
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { <1>
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http <2>
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth <3>
            .inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER");
    }
}
  1. <1> @EnableWebSecurity 注解使得 SpringMVC 集成了 Spring Securityweb 安全支持。另外,WebSecurityConfig 配置类同时集成了 WebSecurityConfigurerAdapter ,重写了其中的特定方法,用于自定义 Spring Security 配置。整个 Spring Security 的工作量,其实都是集中在该配置类,不仅仅是这个 guides,实际项目中也是如此。
  2. <2> configure(HttpSecurity) 定义了哪些URL路径应该被拦截,如字面意思所描述:”/“, “/home”允许所有人访问,”/login”作为登录入口,也被允许访问,而剩下的”/hello”则需要登陆后才可以访问。
  3. <3> configureGlobal(AuthenticationManagerBuilder) 在内存中配置一个用户,admin/admin 分别是用户名和密码,这个用户拥有 USER 角色。
  4. 以上配置隐含部分登录登出的细节,配置了使用Form表单方式登录,登录的接口是 /login

创建登录页面如下

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Spring Security Example </title>
    </head>
    <body>
        <div th:if="${param.error}">
            Invalid username and password.
        </div>
        <div th:if="${param.logout}">
            You have been logged out.
        </div>
        <form th:action="@{/login}" method="post">
            <div><label> User Name : <input type="text" name="username"/> </label></div>
            <div><label> Password: <input type="password" name="password"/> </label></div>
            <div><input type="submit" value="Sign In"/></div>
        </form>
    </body>
</html>

这个 Thymeleaf 模板提供了一个用于提交用户名和密码的表单,其中 name=”username”,name=”password” 是默认的表单值,并发送到“/login”。 在默认配置中,Spring Security 提供了一个拦截该请求并验证用户的过滤器。 如果验证失败,该页面将重定向到“/login?error”,并显示相应的错误消息。 当用户选择注销,请求会被发送到“/login?logout”。

在 hello.html 添加一些内容,用于展示用户信息。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
    <input type="submit" value="Sign Out"/>
</form>
</body>
</html>

我们使用 Spring Security 之后,HttpServletRequest#getRemoteUser() 可以用来获取用户名。 登出请求将被发送到“/logout”。 成功注销后,会将用户重定向到“/login?logout”。

添加启动类

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

添加配置文件

spring:
  application:
    name: spring-security-guide
server:
  port: 8990

github 源码地址

github 源码地址

测试

访问地址 http://localhost:8990/

原文链接:http://blog.didispace.com/xjf-spring-security-2