文章来源:https://spring.io/guides/gs/securing-web/
一、创建一个简单的maven工程spring-boot-security,pom.xml依赖如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
二、创建springmvc配置类MvcConfig.java,并添加视图控制器
package com.szcatic.configurations;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
三、创建安全配置类WebSecurityConfig.java
package com.szcatic.configurations;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@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();
}
@SuppressWarnings("deprecation")
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
四、在资源src/main/resources目录下新建文件夹templates,并分别创建文件home.html、hello.html、login.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>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
</body>
</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>
<!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>
五、创建引导类Application.java
package com.szcatic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Throwable {
SpringApplication.run(Application.class, args);
}
}
六、启动程序,运行引导类
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.4.RELEASE)
2019-04-21 20:48:12.323 INFO 19004 --- [ main] com.szcatic.Application : Starting Application on zsx with PID 19004 (F:\workspace4.11\spring-boot-security\target\classes started by admin in F:\workspace4.11\spring-boot-security)
2019-04-21 20:48:12.325 INFO 19004 --- [ main] com.szcatic.Application : No active profile set, falling back to default profiles: default
2019-04-21 20:48:13.361 INFO 19004 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-04-21 20:48:13.390 INFO 19004 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-04-21 20:48:13.391 INFO 19004 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-04-21 20:48:13.398 INFO 19004 --- [ main] o.a.catalina.core.AprLifecycleListener : An older version [1.2.16] of the APR based Apache Tomcat Native library is installed, while Tomcat recommends a minimum version of [1.2.21]
2019-04-21 20:48:13.398 INFO 19004 --- [ main] o.a.catalina.core.AprLifecycleListener : Loaded APR based Apache Tomcat Native library [1.2.16] using APR version [1.6.3].
2019-04-21 20:48:13.399 INFO 19004 --- [ main] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2019-04-21 20:48:13.399 INFO 19004 --- [ main] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2019-04-21 20:48:14.436 INFO 19004 --- [ main] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.0.2m 2 Nov 2017]
2019-04-21 20:48:14.659 INFO 19004 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-04-21 20:48:14.659 INFO 19004 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2292 ms
2019-04-21 20:48:14.824 WARN 19004 --- [ main] o.s.security.core.userdetails.User : User.withDefaultPasswordEncoder() is considered unsafe for production and is only intended for sample applications.
2019-04-21 20:48:15.052 INFO 19004 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@2d691f3d, org.springframework.security.web.context.SecurityContextPersistenceFilter@5f574cc2, org.springframework.security.web.header.HeaderWriterFilter@5fa05212, org.springframework.security.web.csrf.CsrfFilter@15b986cd, org.springframework.security.web.authentication.logout.LogoutFilter@ceb4bd2, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@62d0ac62, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@7a9c84a5, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2f6bbeb0, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@1bdbf9be, org.springframework.security.web.session.SessionManagementFilter@5c09d180, org.springframework.security.web.access.ExceptionTranslationFilter@50b1f030, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@325f7fa9]
2019-04-21 20:48:15.154 INFO 19004 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-21 20:48:15.391 INFO 19004 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-21 20:48:15.394 INFO 19004 --- [ main] com.szcatic.Application : Started Application in 3.422 seconds (JVM running for 4.398)
七、打开浏览器
7.1查看请求http://localhost:8080/
7.2 点击here链接(http://localhost:8080/login),进入登录页面
7.3输入用户名:user,密码:password,点击登录,进入登录成功问候界面