上一篇文章 [Spring Cloud] - Spring Security实际(一)- 基本概念及实际 中, 咱们曾经实现了根本的security鉴权和认证. 上面会在此基础上加一些自定义的配置.

  1. 摈弃自带的登陆界面, 实现自定义登陆界面 (themeleaf形式)
  2. 对资源(controller)实现更细化的鉴权操作

增加自定义登陆界面

Spring security默认应用/login办法跳转到登录界面, 咱们替换login页面,只需将/login指向的界面换成本人的即可.

  • 增加themeleaf依赖
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
  • 新建login controller
@Controllerpublic class Login {    @GetMapping("/login")    private String loginController(){        return "login";    }}
  • 在我的项目构造的/resource/templates下新建login.html
<!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 th:action="@{/login}" 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>

Spring security框架会拦挡login的post申请

  • security的@configuration中,为以下配置
@EnableWebSecuritypublic class SecurityConfiguration extends WebSecurityConfigurerAdapter {    @Override    protected void configure(AuthenticationManagerBuilder auth) throws Exception {        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())                .withUser("root").password(new BCryptPasswordEncoder().encode("1234")).roles("ADMIN")                .and()                .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("USER");    }    @Override    protected void configure(HttpSecurity http) throws Exception {        http                .authorizeRequests()//                    .antMatchers("/", "/user").permitAll()                    .antMatchers("/user").hasRole("USER")                    .antMatchers("/admin").hasRole("ADMIN")                    .anyRequest().authenticated()                    .and()                .formLogin()                    .loginPage("/login")                    .permitAll()                    .and()                .logout()                    .permitAll();    }}