ch02:添加自定义用户登录界面

在ch01的基础上,增加自定义用户登录界面。Spring Security增加自定义用户界面非常容易,只需要简单配置即可完成。

修改SecurityConfiguration.configure(HttpSecurity http)方法:

  @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/assets/**").permitAll()
                .antMatchers("/**").hasRole("USER")
                .and().formLogin().loginPage("/login.jsp").permitAll().loginProcessingUrl("/login")
                .and().csrf().disable();
    }

其中,login.jsp为用户自定义登录界面,/login为处理登录认证请求的地址。

login.jsp的关键代码为form表单,基本配置如下:




自定义登录界面只需要包含以上form表单内容,即可实现Spring Security的保驾护航。

Spring Security两大功能认证和授权

认证是验证操作者是否是其所申请的用户
授权是验证已认证的用户是否具有某种权限

认证的基本流程如图所示

ch02:添加自定义用户登录界面_第1张图片
Paste_Image.png

图中各个组件都是可以替换的,特别是AuthenticationProvider有多个实现类,可支持内存、数据库、LDAP等多种认证方式,这是Spring Security可以支持多种认证方式的基础。
通过认证后,Spring Security创建Authentication(可包含了用户的详细信息),并存储到SecurityContextHolder中。

授权的基本流程如图所示

ch02:添加自定义用户登录界面_第2张图片
Paste_Image.png

授权过程是由FilterSecurityInterceptor处理的,其本身是AbstractAuthenticationProcessingFilter的子类,并将授权过程交给AccessDecisionManager处理。后者包含采用投票机制验证权限,默认是用AffirmativeBased,即一票通过。此外还有 ConsensusBased(多数票通过)和 UnanimousBased(全票通过)。

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http
              .and().authorizeRequests().accessDecisionManager(unaninmousBased())//修改为全票通过的授权方式
   }

    /**
     * Description:声明全票通过授权方式
     *
     * @param
     * @return
     *
     * @Author: 瓦力
     * @Date: 2017/7/20 10:13
     */
    @Bean
    public AccessDecisionManager unaninmousBased() {
        RoleVoter roleVoter = new RoleVoter();
        AuthenticatedVoter authenticatedVoter = new AuthenticatedVoter();
        List> voters = new ArrayList<>();
        voters.add(roleVoter);
        voters.add(authenticatedVoter);
        UnanimousBased unanimousBased = new UnanimousBased(voters);
        return unanimousBased;
    }

关于授权SpringEl表达式,在随后的章节讲解

注销/退出

通过提交POST请求到"/logout"实现,退出后页面自动跳转到登录界面

基本流程如图所示


ch02:添加自定义用户登录界面_第3张图片
Paste_Image.png

代码示例:https://github.com/wexgundam/spring.security/tree/master/ch02

你可能感兴趣的:(ch02:添加自定义用户登录界面)