转载

[Spring Cloud] - Spring Security实践(二)- 自定义登录界面及鉴权

上一篇文章 [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
@Controller
public 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中,为以下配置
@EnableWebSecurity
public 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();
    }
}
原文  https://segmentfault.com/a/1190000023293187
正文到此结束
Loading...