SpringBoot 集成 SpringSecurity 详解(七)-- 自定义登录页面

SpringBoot 集成 SpringSecurity 详解(七)-- 自定义登录页面

需求缘起

系统默认的登录页面不友好,这一节我们来实现自定义登录页面。
本节是在第六小节的基础上继续开发。

本节 demo

技术要点

  1. 编写登录界面
  2. 配置页面和登录路径等

1.编辑登录界面

编写login.html界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<h2>自定义登录页面</h2>
<form action="/authentication/form" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td colspan="2">
                <button type="submit">登录</button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

2.配置Spring Security的登录页面路径

@Configuration
@EnableWebSecurity//开启Spring Security的功能
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启方法安全级别的控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        //SpringSecurity 提供的一种编码器,我们也可以自己实现PasswordEncoder
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.formLogin()
                .loginPage("/login.html")// 自定义登录页面路径
                .loginProcessingUrl("/authentication/form")// 自定义页面的登录路径,注意要与登录页面的action值一致,<form action="/authentication/form" method="post">
                .and()
                .authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/login.html").permitAll()// 设置所有人都可以访问登录页面
                .anyRequest().authenticated()  // 除了以上的请求外都需要身份验证
        ;
        http.csrf().disable();// 禁用跨站攻击
    }
}

3.测试

重启应用,访问http://localhost:8080/hello/helloUser
现在的界面已经变成了我们自定义的界面,如下所示
在这里插入图片描述
然后输入用户名密码即可访问。

提示:

  1. login.html 要放在resource/static 目录下;
  2. 配置的 loginProcessingUrl 参数中的值要与界面中action中的值一致。
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的SpringBoot集成SpringSecurity的例子,实现自定义登录和授权。 1. 添加依赖 在`pom.xml`文件中添加如下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置SpringSecurity 在`application.properties`文件中添加如下配置: ```properties # 禁用csrf security.enable-csrf=false # 配置自定义登录页面 spring.security.login-form=/login # 配置自定义登录接口 spring.security.login-processing-url=/login ``` 3. 创建自定义UserDetailsService实现类 创建一个实现`UserDetailsService`接口的类`CustomUserDetailsService`,用于从数据库中获取用户信息。在该类中,我们需要注入一个`UserRepository`,用于从数据库中获取用户信息。 ```java @Service public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found with username: " + username); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>()); } } ``` 4. 创建自定义User实体类和Repository接口 创建一个`User`实体类,用于表示用户信息,并创建一个`UserRepository`接口,用于从数据库中获取用户信息。 ```java @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; // getter and setter methods } @Repository public interface UserRepository extends JpaRepository<User, Long> { User findByUsername(String username); } ``` 5. 创建自定义授权规则 创建一个实现`GrantedAuthority`接口的类`CustomGrantedAuthority`,用于表示用户的授权角色。在该类中,我们需要定义一个`role`属性,表示用户的角色。 ```java public class CustomGrantedAuthority implements GrantedAuthority { private String role; public CustomGrantedAuthority(String role) { this.role = role; } @Override public String getAuthority() { return role; } } ``` 6. 创建自定义AuthenticationProvider实现类 创建一个实现`AuthenticationProvider`接口的类`CustomAuthenticationProvider`,用于自定义用户的认证和授权规则。在该类中,我们需要注入`UserDetailsService`和`PasswordEncoder`对象,并实现`authenticate()`方法和`supports()`方法。 ```java @Component public class CustomAuthenticationProvider implements AuthenticationProvider { @Autowired private UserDetailsService userDetailsService; @Autowired private PasswordEncoder passwordEncoder; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (userDetails == null) { throw new UsernameNotFoundException("User not found with username: " + username); } if (!passwordEncoder.matches(password, userDetails.getPassword())) { throw new BadCredentialsException("Invalid password"); } Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new CustomGrantedAuthority("ROLE_USER")); return new UsernamePasswordAuthenticationToken(username, password, authorities); } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } } ``` 7. 创建自定义登录页面和控制器 在`resources/templates`目录下创建一个`login.html`文件,用于自定义登录页面。在`com.example.demo.controller`包下创建一个`LoginController`类,用于处理登录请求。 ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Login Page</title> </head> <body> <h3>Login Page</h3> <form action="/login" method="post"> <input type="text" name="username" placeholder="Username" required/><br> <input type="password" name="password" placeholder="Password" required/><br> <input type="submit" value="Login"/> </form> </body> </html> ``` ```java @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; } @GetMapping("/home") public String home() { return "home"; } } ``` 8. 创建自定义授权规则配置类 创建一个实现`WebSecurityConfigurerAdapter`类的`CustomWebSecurityConfigurer`类,用于自定义授权规则。在该类中,我们需要注入`CustomAuthenticationProvider`对象,并重写`configure()`方法。 ```java @Configuration @EnableWebSecurity public class CustomWebSecurityConfigurer extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthenticationProvider customAuthenticationProvider; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(customAuthenticationProvider); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/home").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Bean public PasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(); } } ``` 9. 运行程序 启动应用程序后,访问`http://localhost:8080/login`,将跳转到自定义登录页面。输入正确的用户名和密码,将跳转到自定义的`home`页面。如果输入错误的用户名或密码,将返回错误信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值