Springboot集成SpringSecurity 附代码

之前做过公司的SSO接入,也网上找了很多博客,结合自己的理解 梳理了一些,文章有点长,希望可以有耐心的看下去。

一、Spring security 是什么?

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。

它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

二、Spring security 怎么使用?

使用Spring Security很简单,只要在pom.xml文件中,引入spring security的依赖就可以了。          

<!-- spring security依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

什么都不做,直接运行程序,这时你访问任何一个URL,都会弹出一个“需要授权”的验证框,如图:

,spring security 会默认使用一个用户名为:user 的用户,密码就是 启动的时候生成的(通过控制台console中查看),如图

然后在用户名中输入:user   密码框中输入 上面的密码 ,之后就可以正常访问之前URL了。很显然这根本不是我们想要的,接下来我们需要一步一步的改造。

 改造1 使用页面表单登录

通过修改Security的配置来实现  参考:https://docs.spring.io/spring-security/site/docs/current/guides/html5//helloworld-boot.html#creating-your-spring-security-configuration

首先 添加一个类 SecurityConfig 继承 WebSecurityConfigurerAdapter ,

重写configure方法。

并加上@Configuration 和@EnableWebSecurity 2个注解。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
      
      @Override
      protected void configure(HttpSecurity http) throws Exception {
            // TODO Auto-generated method stub
            //super.configure(http);
            http
                  .formLogin().loginPage("/login").loginProcessingUrl("/login/form").failureUrl("/login-error").permitAll()  //表单登录,permitAll()表示这个不需要验证 登录页面,登录失败页面
                  .and()
                  .authorizeRequests().anyRequest().authenticated()                  
                  .and()
                  .csrf().disable();            
      }
}
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
      
      @Override
      protected void configure(HttpSecurity http) throws Exception {
            // TODO Auto-generated method stub
            //super.configure(http);
            http
                  .formLogin().loginPage("/login").loginProcessingUrl("/login/form").failureUrl("/login-error").permitAll()  //表单登录,permitAll()表示这个不需要验证 登录页面,登录失败页面
                  .and()
                  .authorizeRequests().anyRequest().authenticated()                  
                  .and()
                  .csrf().disable();            
      }
}

View Code

 loginPage("/login")表示登录时跳转的页面,因为登录页面我们不需要登录认证,所以我们需要添加 permitAll() 方法。

 

  添加一个控制器,对应/login 返回一个登录页面。

  @RequestMapping("/login")
  public String userLogin(){

        return "demo-sign";
  }

 html页面是使用 thymeleaf 模板引擎的,这里就不详细讲解了。

 

demo_sign.html 的 html部分代码如下:  

<form  class="form-signin" action="/login/form" method="post">
              <h2 class="form-signin-heading">用户登录</h2>
            <table>
                  <tr>
                        <td>用户名:</td>
                        <td><input type="text" name="username"  class="form-control"  placeholder="请输入用户名"/></td>
                  </tr>
                        <tr>
                        <td>密码:</td>
                        <td><input type="password" name="password"  class="form-control" placeholder="请输入密码" /></td>
                  </tr>
                  <tr>
                  
                        <td colspan="2">
                              <button type="submit"  class="btn btn-lg btn-primary btn-block" >登录</button>
                        </td>
                  </tr>
            </table>
      </form>
  class="form-signin" action="/login/form" method="post">
              <h2 class="form-signin-heading">用户登录</h2>
            <table>
                  <tr>
                        <td>用户名:</td>
                        <td><input type="text" name="username"  class="form-control"  placeholder="请输入用户名"/></td>
                  </tr>
                        <tr>
                        <td>密码:</td>
                        <td><input type="password" name="password"  class="form-control" placeholder="请输入密码" /></td>
                  </tr>
                  <tr>
                  
                        <td colspan="2">
                              <button type="submit"  class="btn btn-lg btn-primary btn-block" >登录</button>
                        </td>
                  </tr>
            </table>
      </form>

需要注意下:form提交的url要和配置文件中的 loginProcessingUrl("")中的一致。

failureUrl=表示登录出错的页面,我们可以简单写个提示:如 用户名或密码错误。 

  @RequestMappin
  • 70
    点赞
  • 242
    收藏
    觉得还不错? 一键收藏
  • 49
    评论
Spring Security 是一个基于 Spring 的安全框架,提供了一组完整的安全性功能,包括身份验证、授权、防止 CSRF 攻击等等。Spring Boot 基于 Spring,自然也集成Spring Security。下面是 Spring Boot 集成 Spring Security 的步骤: 1. 在 pom.xml 中添加 Spring Security 的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 编写一个继承自 WebSecurityConfigurerAdapter 的配置类,并使用 @EnableWebSecurity 注解开启 Spring Security: ```java @Configuration @EnableWebSecurity public class SecurityConfig 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"); } } ``` 上面的代码中,我们配置了 Spring Security 的基本功能:对所有请求进行身份验证,允许访问首页和登录页面,使用 inMemoryAuthentication 来指定用户和密码。 3. 在 application.properties 或 application.yml 中配置登录页面的 URL: ```properties spring.security.login.form=/login ``` 4. 编写一个登录页面,例如一个 Thymeleaf 模板: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <form th:action="@{/login}" method="post"> <div><label>Username: <input type="text" name="username"/></label></div> <div><label>Password: <input type="password" name="password"/></label></div> <div><input type="submit" value="Log in"/></div> </form> </body> </html> ``` 这样就完成了 Spring Boot 集成 Spring Security 的配置。当用户访问受保护的页面时,会被重定向到登录页面进行身份验证。如果用户输入的用户名和密码正确,就会跳转到原来请求的页面。如果不正确,就会显示错误信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值