16.Spring Security应用详解-自定义认证-自定义登录页面

自定义认证

  • Spring Security提供了非常好的认证扩展方法,比如:快速上手中将用户信息存储到内存中,实际开发中用户信息通常在数据库,Spring Security可以实现从数据库读取用户信息,Spring Security还支持多种授权方法。

自定义登录页面

  • 在快速上手中,你可能会想知道登录页面从哪里来的?因为我们并没有提供任何的HTML或JSP文件。Spring Security的默认配置没有明确设定一个登录页面的URL,因此Spring Security会根据启用的功能自动生成一个登录页面URL,并使用默认URL处理登录的提交内容,登录后跳转的到默认URL等等。尽管自动生成的登录页面很方便快速启动和运行,但大多数应用程序都希望定义自己的登录页面。
认证页面
  • 将security-springmvc工程的login.jsp拷贝到security-springboot下,目录保持一致。

配置认证页面

  • 在WebConfig.java中配置认证页面地址:
/**
 * 默认Url根路径跳转到/login,此url为spring security提供
 * @param registry
 */
public void addViewControllers(ViewControllerRegistry registry){
    registry.addViewController("/").setViewName("redirect:/login-view");
    registry.addViewController("/login-view").setViewName("login");
}

安全配置

  • 在WebSecurityConfig中配置表章登录信息:
//安全拦截机制(最重要)
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/r/r1").hasAnyAuthority("p1")
            .antMatchers("/r/r2").hasAnyAuthority("p2")
            .antMatchers("/r/**").authenticated()//所有/r/**的请求必须认证通过
            .anyRequest().permitAll()//除了/r/**,其他的请求可以访问
            .and()
            .formLogin()//允许表单登录
            .loginPage("/login-view")//登录页面
            .loginProcessingUrl("/login")//登录地址
            .successForwardUrl("/login-success");//自定义登录成功的页面地址
}

你可能感兴趣的:(16.Spring Security应用详解-自定义认证-自定义登录页面)