栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

Spring Boot & Security教程(1)-Spring Boot中开启Spring Security

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot & Security教程(1)-Spring Boot中开启Spring Security

开启Spring Security

创建一个Spring Boot项目,然后引入spring-boot-starter-security:


    org.springframework.boot
    spring-boot-starter-security

接下来我们创建一个TestController,对外提供一个/hello服务:

@RestController
public class TestController {
    @GetMapping("hello")
    public String hello() {
 return "hello spring security";
    }
}

这时候我们直接启动项目,访问http://localhost:8080/hello,可看到页面弹出了个HTTP Basic认证框:

当Spring项目中引入了Spring Security依赖的时候,项目会默认开启如下配置:

security:
  basic:
    enabled: true

这个配置开启了一个HTTP basic类型的认证,所有服务的访问都必须先过这个认证,默认的用户名为user,密码由Sping Security自动生成,回到IDE的控制台,可以找到密码信息:

Using default security password: c69dc6ec-8edd-46c5-9a44-d0e1acca4aa2
基于表单认证

我们可以通过一些配置将HTTP Basic认证修改为基于表单的认证方式。
创建一个配置类BrowserSecurityConfig继承org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter这个抽象类并重写configure(HttpSecurity http)方法。WebSecurityConfigurerAdapter是由Spring Security提供的Web应用安全配置的适配器:

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
 http.formLogin() // 表单方式
  .and()
  .authorizeRequests() // 授权配置
  .anyRequest()  // 所有请求
  .authenticated(); // 都需要认证
    }
}

Spring Security提供了这种链式的方法调用。上面配置指定了认证方式为表单登录,并且所有请求都需要进行认证。这时候我们重启项目,再次访问http://localhost:8080/hello,可以看到认证方式已经是form表单的方式了:

用户名依旧是user,密码由Spring Security自动生成。当输入凭证错误时,页面上将显示错误信息:

如果需要换回HTTP Basic的认证方式,我们只需要简单修改configure方法中的配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    // http.formLogin() // 表单方式
    http.httpBasic() // HTTP Basic方式
     .and()
     .authorizeRequests() // 授权配置
     .anyRequest()  // 所有请求
     .authenticated(); // 都需要认证
}

本文作者: MrBird
本文链接: http://mrbird.cc/Spring-Boot&Spring-Security.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/234463.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号