弹簧引导中使用Spring Security如何实现安全控制

  

弹簧引导中使用Spring Security如何实现安全控制?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

<强>准备工作

首先,构建一个简单的网工程,以用于后续添加安全控制,也可以用之前Chapter3-1-2做为基础工程。若对如何使用弹簧引导构建网络应用,可以先阅读《春天引导开发网络应用》一文。

Web层实现请求映射

@ controller   公开课HelloController {      @RequestMapping (“/?   公共字符串索引(){   返回“index";   }      @RequestMapping (“/hello")   公共字符串hello () {   返回“hello";   }      }
    <李>/:映射到索引。李李html <>/你好:映射到hello.html李

<强>实现映射的页面

src/main/资源/模板/索引。html

& lt; !DOCTYPE html>   http://www.w3.org/1999/xhtml" & lt; html xmlns=?xmlns: th=癶ttp://www.thymeleaf.org"xmlns:秒=癶ttp://www.thymeleaf.org/thymeleaf-extras-springsecurity3"比;   & lt; head>   & lt; title> Spring Security入门& lt;/title>   & lt;/head>   & lt; body>   & lt; h2>欢迎使用Spring Security ! & lt;/h2>   & lt; p>点击& lt; th: href=https://www.yisu.com/zixun/癅{/你好}”rel="外部nofollow”>这里打个招呼吧

        

src/main/资源/模板/你好。html

& lt; !DOCTYPE html>   http://www.w3.org/1999/xhtml" & lt; html xmlns=?xmlns: th=癶ttp://www.thymeleaf.org"   xmlns:秒=癶ttp://www.thymeleaf.org/thymeleaf-extras-springsecurity3"比;   & lt; head>   & lt; title> Hello World ! & lt;/title>   & lt;/head>   & lt; body>   & lt; h2> Hello world ! & lt;/h2>   & lt;/body>   & lt;/html>   

可以看到在索引。html中提供到/hello的链接,显然在这里没有任何安全控制,所以点击链接后就可以直接跳转到你好。html页面。

<强>整合Spring Security

在这一节,我们将对/你好页面进行权限控制,必须是授权用户才能访问。当没有权限的用户访问后,跳转到登录页面。

<强>添加依赖

在pom。xml中添加如下配置,引入对Spring Security的依赖。

& lt; dependencies>   …   & lt; dependency>   & lt; groupId> org.springframework.boot   & lt; artifactId> spring-boot-starter-security   & lt;/dependency>   …   & lt;/dependencies>   

<强> Spring Security配置

创建Spring Security的配置类WebSecurityConfig,具体如下:

@ configuration   @EnableWebSecurity   公开课WebSecurityConfig延伸WebSecurityConfigurerAdapter {      @Override   保护无效配置(HttpSecurity http){抛出异常   http   .authorizeRequests ()   .antMatchers (“/?“/home") .permitAll ()   .authenticated .anyRequest () ()   ,()   .formLogin ()   .loginPage (“/login")   .permitAll ()   ,()   .logout ()   .permitAll ();   }      @ autowired   公共空间configureGlobal (AuthenticationManagerBuilder auth)抛出异常{   身份验证   .inMemoryAuthentication ()   .withUser (“user") .password (“password") .roles (“user");   }      李}
    <>通过@EnableWebMvcSecurity注解开启Spring Security的功能李 <李>继承WebSecurityConfigurerAdapter,并重写它的方法来设置一些网络安全的细节 <李>配置(HttpSecurity http)方法
      <李>通过以()定义哪些URL需要被保护,哪些不需要被保护,例如以上代码指定了/和/home不需要任何认证就可以访问,其他的路径都必须通过身份验证。 <李>通过formLogin()定义当需要用户登录时候,转到的登录页面。
    <李> configureGlobal (AuthenticationManagerBuilder auth)方法,在内存中创建了一个用户,该用户的名称为用户,密码为密码,用户角色为用户。
      李,

<强>新增登录请求与页面

在完成了Spring Security配置之后,我们还缺少登录的相关内容。

HelloController中新增/登录请求映射至登录。html

@ controller   公开课HelloController {//省略之前的内容……      @RequestMapping (“/login")   公共字符串登录(){   返回“login";   }      }

新增登录页面:src/main/资源/模板/登录。html

弹簧引导中使用Spring Security如何实现安全控制