Spring Security简单配置(二)

自定义密码策略

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

自定义用户信息并授权

配置文件

通过 autoconfigure自动配置类

application.yml

spring:
  security:
    user:
      name: rick
      password: $2a$10$Qs4BkX/ljq09QuYcE6GwBewe9aKIW9NlXvRFyqDurmZcyGcFzDXIq # 123456编码后的密码
      roles:
        - ADMIN

编程式

  • 注册 UserDetailsService
  • AuthenticationManagerBuilder

SecurityConfig.java

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled=true, prePostEnabled = true)// 控制权限注解 配合 @Secured({"ROLE_ADMIN","ROLE_USER2"})使用
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;


    /**
     * 方式一:自定义用户信息并授权
     * @return
     */
    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        //Admin Role
        UserDetails theUser = User.withUsername("rick")
                .password(passwordEncoder.encode("123456"))
                .roles("ADMIN").build();

        //User Role
        UserDetails theManager = User.withUsername("john")
                .password(passwordEncoder.encode("123456"))
                .roles("USER").build();


        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();

        userDetailsManager.createUser(theUser);
        userDetailsManager.createUser(theManager);
        return userDetailsManager;
    }


    /**
     * 方式二:自定义用户信息并授权
     * @return
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("rick")
                .password(passwordEncoder.encode("123456"))
                .roles("ADMIN")
                .and()
                .withUser("john")
                .password(passwordEncoder.encode("123456"))
                .roles("USER");

    }
}

不能再使用默认的user和生成的密码登录了。必须使用rick/123456登录

授权请求

IndexController.java

@RestController
public class IndexController {

    @GetMapping(value = {"index", "/"})
    public String index() {
        return "index";
    }

    @GetMapping("public")
    public String publicFun() {
        return "public";
    }

    @GetMapping("admin")
    public String admin() {
        return "admin";
    }

    @PreAuthorize("hasAnyRole('USER')")
    @GetMapping("user")
    public String user() {
        return "user";
    }
}

SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests((requests) -> requests.antMatchers("/public").permitAll()
            .antMatchers("/admin").hasAnyRole("ADMIN")
            .anyRequest().authenticated())
            .exceptionHandling().accessDeniedHandler((request, response, accessDeniedException) -> {
                // 403 Forbidden 没有授权,执行到此处
        HttpServletResponseUtils.write(response, "text/plain", "403 Forbidden");
    });
    http.formLogin();
    http.httpBasic();
}
  • /public 不需要登录就能访问
  • /index 认证后允许访问
  • /admin 认证后,角色ADMIN才允许访问

Github:https://github.com/jkxyx205/spring-security-learn/tree/simple-configure