Java知识储备Java学习笔记Spring Boot

Spring Boot整合Spring Security简记-基

2018-01-13  本文已影响683人  78240024406c

new無语 转载请注明原创出处,谢谢!

Spring Security学习目录

1.项目初始化

创建一个boot项目。创建方式就不说了。
最基本的例子:
在application.yml配置文件中配置初始化用户信息,账号密码角色

security:
  user:
    name: user
    password: password
    role: USER

配置了这些就初始化了security功能。与下面Servlet API集成。

启动一下,访问默认路径http://localhost:8080,会有如下显示。

由于只是默认启动了security,都没有配置登陆页面的URL,所以只是默认实现。
接下来实现自定义登陆页面。

2.自定义登陆页面

spring security有一个WebSecurityConfigurerAdapter基类。我们的设置继承覆盖方法即可。

@SpringBootApplication
public class SpringcloudsecurityApplication {
    @Controller
    class LoginController {
        @RequestMapping("/login")
        public String login() {
            return "login";
        }
    }

    @Component
    class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    //设置登陆页面
                    .loginPage("/login")
                    //允许所有人进行访问此路径
                    .permitAll();
                    //关闭csrf保护
//                    .and().csrf().disable();
        }
    }

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

login.ftl 自定义登陆页面,用户名/密码为:user/password

<html>
<head>
</head>
<body>
<form role="form" action="login" method="post">
    <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" class="form-control" id="username" name="username"/>
    </div>
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" class="form-control" id="password" name="password"/>
    </div>
    <input type="hidden" id="csrf_token" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
</body>
</html>

使用freemarker需要导入spring boot支持。这里贴出所有的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.zee</groupId>
    <artifactId>springcloudsecurity</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springcloudsecurity</name>
    <description>spring cloud security demo</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</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-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

3.设置权限请求路径规则

配置权限请求规则,一样是在之前的configure(HttpSecurity http)方法中实现。具体实现代码如下。

            http
                //按照声明顺序
                .authorizeRequests()
                //"/resources/**", "/signup", "/about" 路径为免验证访问
                .antMatchers("/resources/**", "/signup", "/about").permitAll()
                //"/admin/**" 路径为 ADMIN 角色可访问
                .antMatchers("/admin/**").hasRole("ADMIN")
                //"/db/**" 路径为 ADMIN 和 DBA 角色同时拥有时可访问
                .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
                //未匹配路径为登陆可访问
                .anyRequest().authenticated()
                //...

4.注销操作处理

继承WebSecurityConfigurerAdapter类时,注销操作有默认设置。就是POST请求/logout路径进行注销操作,清除session、清除SecurityContextHolder等。

上一篇 下一篇

猜你喜欢

热点阅读