[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。好比IndexControlleroop

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

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

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

这个“乱码”就是spring security提供的缺省密码。
此时访问项目url,会自动跳转到项目url/login页面。
image.png
默认username为user, password栏输入刚刚那一句“乱码”。
点击signin,发现跳转成功,会访问到咱们最初访问的页面。加密

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

建立@configuration: url

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

@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登录,便可跳转至正确页面。

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

**此处注意,security 5.0以后的版本,须要在密码前加上加密格式。
因此仅仅使用BCryptPasswordEncoder将密码encode还不够,还要在encode后的密码前方加上密码格式。**

官方说明:

The general format for a password is:
 
{id}encodedPassword
Such that id is an identifier used to look up which PasswordEncoder should be used and encodedPassword is the original encoded password for the selected PasswordEncoder. The id must be at the beginning of the password, start with { and end with }. If the id cannot be found, the id will be null. For example, the following might be a list of passwords encoded using different id. All of the original passwords are "password".
 
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG 
{noop}password 
{pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc 
{scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=  
{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0
@Configuration
public class AuthConfiguration {
 @Bean
 public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        String password = new BCryptPasswordEncoder().encode("123");

// 正确的结果
manager.createUser(User.withUsername("user").password("{bcrypt}" + password).roles("USER").build());
       
// 错误  
manager.createUser(User.withUsername("admin").password(password).roles("ADMIN").build());
// 错误     
manager.createUser(User.withUsername("all").password(password).roles("USER", "ADMIN").build());
        return manager;
    }
}

鉴权

覆写方法
鉴权依靠的是另外一个方法: configure(HttpSecurity http),注意:其中httpSecurity表明一整套过滤器链,每一个过滤器表示一个配置项。
代码以下:

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