关于spring-cloud:Spring-Cloud-Spring-Security实践二-自定义登录界面及鉴权

4次阅读

共计 1881 个字符,预计需要花费 5 分钟才能阅读完成。

上一篇文章 [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();}
}
正文完
 0