本博客是根据spring.io的官网教程总结而来,希望能帮助到小白!我也是小白…原文地址:Security-Web
这篇入门篇博客将展示如何创建一个网站应用,使用Spring Security来保护你的网站资源文件。你构建的网站将是一个Spring MVC项目,通过一个login页面来保护你的资源文件。
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.9.RELEASE")
}
}
apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'org.springframework.boot' jar { baseName = 'gs-securing-web' version = '0.1.0' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile("org.springframework.boot:spring-boot-starter-thymeleaf") testCompile("junit:junit") testCompile("org.springframework.boot:spring-boot-starter-test") testCompile("org.springframework.security:spring-security-test") }
如果是使用Maven来构建项目,就替换pom.xml
<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.0modelVersion>
<groupId>org.springframeworkgroupId>
<artifactId>gs-securing-webartifactId>
<version>0.1.0version>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>1.5.9.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-testartifactId>
<scope>testscope>
dependency>
dependencies>
<properties>
<java.version>1.8java.version>
properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
<repositories>
<repository>
<id>spring-releasesid>
<name>Spring Releasesname>
<url>https://repo.spring.io/libs-releaseurl>
repository>
repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releasesid>
<name>Spring Releasesname>
<url>https://repo.spring.io/libs-releaseurl>
pluginRepository>
pluginRepositories>
project>
src/main/resources/templates/home.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 Exampletitle>
head>
<body>
<h1>Welcome!h1>
<p>Click <a th:href="@{/hello}">herea> to see a greeting.p>
body>
html>
在上面的页面里可以看到了有个/hello路径,所以我们的另一个html呼之欲出
src/main/resources/templates/hello.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>
后面我们可能还需要调整hello页面,暂时先放着。由于项目是基于Spring MVC的,所以我们需要配置Spring MVC并且建立视图控制器来暴露这些页面。
src/main/java/com/cjzheng/config/MvcConfig.java
package com.cjzheng.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/** * Created by CJ Zheng on 2018/1/11. * Project: spring-security */
@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");
}
}
这里,我们覆写了addViewControllers()
方法,加入了4个视图控制器。两个是指定到home页的,一个是指向hello页面,还有一个是指定到login 的。你应该也注意到了,我们少了一个login页面。不着急,后面加上,现在还不需要。
其实到此为止,我们就可以运行项目了,到这里,我们还没有加入任何Spring Security的配置,这就是个普通的Spring MVC项目。那就先使用Spring boot来跑起来吧!
src/main/java/com/cjzheng/Application.java
package com.cjzheng;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/** * Created by CJ Zheng on 2018/1/11. * Project: spring-security */
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Throwable {
SpringApplication.run(Application.class, args);
}
}
dependencies {
...
compile("org.springframework.boot:spring-boot-starter-security")
...
}
对应的Maven的依赖
...
org.springframework.boot
spring-boot-starter-security
...
然后是加入安全配置
src/main/java/com/cjzheng/config/WebSecurityConfig.java
package com.cjzheng.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/** * Created by CJ Zheng on 2018/1/11. * Project: spring-security */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
这里WebSecurityConfig
类加入了@EnableWebSecurity
注解来使得Spring Security web的支持得以生效。另外,它继承了WebSecurityConfigurerAdapter
并且覆写了两个config方法。
第一个方法configure(HttpSecurity http)
定义了那些URL需要被授权,那些不需要。在这个例子里,’/’和’/home/’路径不需要授权,就可以进入。
第二个方法configureGlobal(AuthenticationManagerBuilder)
在内存里创建了一个用户,用户名和密码如代码所示。
由于,我们需要用户登录,因此我们需要加入login页面
src/main/resources/templates/login.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>
然后,我们还需要改动hello页面,让成功登录的用户,可以看到自己的用户名
src/main/resources/templates/hello.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>