根本应用

Spring security须要的根本依赖:

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-security</artifactId></dependency><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency>

其余局部不须要任何的减少。

Security的实践是两个外围:认证(我是谁)和鉴权(我能做什么)。
在code中,这两个外围都须要通过继承WebSecurityConfigurerAdapter来实现。

➡️废话不多说,上代码

首先,确保yml中增加了下面提到的两个依赖。增加后这就是最根本的spring security工程了。

而后,咱们能够先增加一些controller。比方IndexController

@RestControllerpublic class IndexController{    @RequestMapping(value = "/", method = RequestMethod.GET)    public String index(){        return "index";    }}

此时启动我的项目,会发现启动log中夹杂着一句乱码:

Using generated security password: 2465a939-a37d-4d3e-9ee1-05d2e51f18fb

这个“乱码”就是spring security提供的缺省明码。
此时拜访我的项目url,会主动跳转到我的项目url/login页面。

默认username为user, password栏输出刚刚那一句“乱码”。
点击signin,发现跳转胜利,会拜访到咱们最后拜访的页面。

自定义用户名明码 - 第一种内存模式

创立@configuration:

新建一个类,继承 WebSecurityConfigurerAdapter, 增加注解@EnableWebSecurity (不必再增加@Configuration注解,因为已被EnableWebSecurity蕴含)如下所示。

@EnableWebSecuritypublic class SecurityConfiguration extends WebSecurityConfigurerAdapter {}

覆写父类办法:

覆写configure(AuthenticationManagerBuilder auth)办法
⚠️ 父类中蕴含多个configure办法,留神抉择正确办法。代码如下所示:

@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())            .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("USER");}

此办法实现了三个性能:

  1. 定义了用户名和明码(user/123)
  2. 加密了明码 - ⚠️ springsecurity强制明码加密,此处必须这样写
  3. 定义此用户的role为USER - Spring security依据role来做鉴权操作,此处只是认证,临时漠视即可。

此时,重启我的项目,曾经看不到最开始那一串乱码了,应用user/123登陆,即可跳转至正确页面。

自定义用户名明码 - 第二种内存模式

鉴权

覆写办法
鉴权依附的是另一个办法: configure(HttpSecurity http),代码如下:

@Override    protected void configure(HttpSecurity http) throws Exception {    }

示例代码及正文如下:

@Overrideprotected void configure(HttpSecurity http) throws Exception {    http        .authorizeRequests()         // 匹配 "/","/index" 门路,不须要权限即可拜访        .antMatchers("/user/user1").permitAll()         // 匹配 "/admin" 及其以下所有门路,都须要 "USER" 权限        .antMatchers("/admin/**").hasRole("USER")        .and()        // 登录地址为 "/login",登录胜利默认跳转到页面 "/user"        .formLogin().loginPage("/login").defaultSuccessUrl("/user/user1")        .and()        // 退出登录的地址为 "/logout",退出胜利后跳转到页面 "/login"        .logout().logoutUrl("/logout").logoutSuccessUrl("/login");}