[Spring Cloud] - Spring Security实践(二)- 了解httpSecurity机制及自定义登录界面

上一篇文章Spring Security实践(一)- 基本概念及实践 中, 我们已经熟悉了spring security的基本使用. 下面会在此基础上加一个自定义的配置,即自定义登陆界面.

  1. 了解spring security配置项的新习惯(重要)
  2. 抛弃自带的登陆界面, 实现自定义登陆界面 (html方式)

添加自定义登陆界面

任何对资源的请求,都会被拦截,并返回设定好的login界面。
Spring security提供了设置自定义登陆页面的功能。

注:默认login界面是被spring security框架写在java类中,而不是html文件 - org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter

想要替换掉默认的login页面很简单,只需要两个步骤:

  1. resource下创建static文件夹,表示这是静态资源,直接访问就可以访问到。并在其中创建html页面。
  2. 在security的config类中,声明此自定义URL即可。

重点: 理解配置中loginpage及loginprocessingUrl及html页面中action,三者的关系

例子:
login页面:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
 xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
    Invalid username and password.
</div>
<div th:if="${param.logout}">
    You have been logged out.
</div>
<form action="/customlogin" method="post">
    <div><label> User Name : <input type="text" name="username"/> </label></div>
    <div><label> Password: <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>

Security配置文件:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasAuthority("ROLE_ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/app/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .formLogin()
                //自定义登录页url,默认为/login
 .loginPage("/login.html")
                //登录请求拦截的url,也就是form表单提交时指定的action
 .loginProcessingUrl("/customlogin").permitAll();
    }
}

此时访问项目controller或url,即可进入自定义登陆界面。

关于Security的配置方式

Spring security使用的配置方式(代码中configure部分)为【链式调用】,简单来说,所谓链式调用即每一个配置项都会返回一个预期上下文,并通过and连接在一起。
实现机制目前尚不明确,但对于配置方式,按xml格式的父子标签的形式去理解即可。

评论

暂无评论