springboot保护web应用的安全

文章来源: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,点击登录,进入登录成功问候界面

八、项目目录结构显示如下:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 答:Spring Boot是一个开源框架,它可以快速、方便地创建独立的Spring应用程序,可以从独立的Tomcat容器中运行,也可以作为一个WAR文件部署到外部的应用服务器中。它提供了一种简单的方法,可以搭建基于web应用程序,并且提供丰富的功能,可以满足现代Web应用程序的需求。好的,我可以使用中文回答有关基于Spring Boot的Web项目的问题。 Spring Boot是一个流行的Java框架,它使得开发Web应用程序变得更加简单和快速。以下是一些基于Spring Boot的Web项目的基本概念和组件: 1. 控制器(Controller): 控制器是Web应用程序中的一个组件,它处理来自Web浏览器的请求并发送响应。在Spring Boot中,我们可以使用`@RestController`注解来创建控制器类。 2. 视图(View): 视图是Web应用程序中的另一个组件,它负责显示数据和UI元素。在Spring Boot中,我们可以使用`Thymeleaf`或`Freemarker`等模板引擎来创建视图。 3. 路由(Router): 路由是一个将URL请求映射到相应的控制器方法的组件。在Spring Boot中,我们可以使用`@RequestMapping`或其他相关注解来配置路由。 4. 数据库访问: 大多数Web应用程序需要与数据库进行交互,以存储和检索数据。在Spring Boot中,我们可以使用JPA或MyBatis等ORM框架来简化数据库访问。 5. 安全性: Web应用程序需要保护用户数据和敏感信息。在Spring Boot中,我们可以使用Spring Security框架来实现身份验证和授权等安全性功能。 以上是基于Spring Boot的Web项目的一些基本概念和组件,当然还有很多其他的组件和功能可以使用。如果您有任何其他问题或需要更详细的解释,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值