[Spring Cloud] - Spring Security实践(一)- 基本概念及实践

基本使用

Spring security须要的基本依赖:web

<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>

其余部分不须要任何的增长。spring

Security的理论是两个核心:认证(我是谁)和鉴权(我能作什么)。
在code中,这两个核心都须要经过继承WebSecurityConfigurerAdapter来实现。app

➡️废话很少说,上代码ide

首先,确保yml中添加了上面提到的两个依赖。添加后这就是最基本的spring security工程了。spring-boot

而后,咱们能够先添加一些controller。好比IndexControllerui

@RestController
public 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页面。
image.png
默认username为user, password栏输入刚刚那一句“乱码”。
点击signin,发现跳转成功,会访问到咱们最初访问的页面。url

自定义用户名密码

建立@configuration: spa

新建一个类,继承 WebSecurityConfigurerAdapter, 添加注解@EnableWebSecurity (不用再添加@Configuration注解,由于已被EnableWebSecurity包含)以下所示。code

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
}

覆写父类方法:

覆写configure(AuthenticationManagerBuilder auth)方法
⚠️ 父类中包含多个configure方法,注意选择正确方法。代码以下所示:

@Override
protected 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 {
    }

示例代码及注释以下:

@Override
protected 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");
}
相关文章
相关标签/搜索