天天看点

springboot 整合 security 实现自定义登陆页面

自定义登陆页面 和踢出在线用户

  1. 引入 jar
<!--页面使用-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
         </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
           
  1. 创建用户接口
import org.springframework.security.core.userdetails.UserDetailsService;
public interface UserService extends UserDetailsService {
}
           
  1. 实现用户接口
package com.gupaoedu.security.service.impl;

import com.gupaoedu.security.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

 
@Service
public class UserServiceImpl implements UserService {



    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    /**
     * 实现自定义的认证流程
     *
     * @param 
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       
        List<GrantedAuthority> authorities = new ArrayList<>();
        SimpleGrantedAuthority auth = new SimpleGrantedAuthority("ROLE_ROOT");
        authorities.add(auth);
        // 数据库操作
        //.....根据username查询对应用户 role 和密码...
        //这里密码 直接写死了
        //bCryptPasswordEncoder  在MyWebSecurityConfigurer类中 实现了
        String password=bCryptPasswordEncoder.encode("123");
        UserDetails user = new User(username
                , password
                , true
                , true
                , true
                , true
                , authorities);


        return user;
    }
}

           
  1. 重写 MyWebSecurityConfigurer 类
import com.gupaoedu.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@Configuration
public class MyWebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private  BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
       //         .loginPage("/login.html")  
       //        .loginProcessingUrl("/login.do1")   这两行注释则使用默认的登陆页面
       
        http.authorizeRequests() // 设置哪些页面可以直接访问,哪些需要验证
            .antMatchers("/login.html","/error.html").permitAll() // 放过
            .anyRequest().authenticated() // 剩下的所有的地址都是需要在认证状态下才可以访问
            .and()
                .formLogin()
                .loginPage("/login.html") // 指定指定要的登录页面
                .loginProcessingUrl("/login.do1") // 处理认证路径的请求
                //认证成功后的跳转页面 默认是get方式提交 自定义成功页面post方式提交
				//在 controller中处理时要注意
                .defaultSuccessUrl("/home.html")
                .failureForwardUrl("/error.html")
            .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login.html")
            .and().csrf().disable() //关闭跨域保护
                .sessionManagement()
                .maximumSessions(1);// 同一用户 只允许一个在线 自动踢出在线用户
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }




}

           
  1. 控制器
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class BaseController {

    @GetMapping("/login.html")
    public String loginPage(){
        return "/login.html";
    }

    @RequestMapping("/home.html")
    public String home(){
        return "/home.html";
    }

    @GetMapping("/")
    public String basePage(){
        return "/home.html";
    }

    @GetMapping("/error.html")
    public String error(){
        return "/error.html";
    }
}

           
  1. 登陆页面 login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登录管理</h1>

    <form th:action="@{/login.do1}" method="post">
        账号:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="submit" value="登录"><br>
    </form>
</body>
</html>
           
  1. home.html页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
        <h1>首页</h1>
</body>
</html>