自定义用户登录验证

1.自定义用户登录验证

把自带的登录逻辑改写以及界面的改写

1.1 UserDetailServiceImpl

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("UserDetail");
        //1.根据用户名数据库查询 不存在抛UsernameNotFound异常
        if(!"admin".equals(username)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //2.比较密码
        String password = passwordEncoder.encode("123");

        return new User(username,password,
                AuthorityUtils.createAuthorityList("admin,normal"));
    }
}

1.2 配置类SecurityConfig

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder getPassword(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //表单提交 自定义界面
        http.formLogin()
                .loginPage("/login.html")
                //必须和表单action一样
                .loginProcessingUrl("/login")
                //登录成功后的界面 只能POST请求
                .successForwardUrl("/toIndex")
                .failureForwardUrl("/toError");

        //授权 
        http.authorizeRequests()
                //放行登录界面
                .antMatchers("/login.html").permitAll()
                .antMatchers("/error.html").permitAll()
                //有请求必须认证才能访问
                .anyRequest().authenticated();

        http.csrf().disable();
    }
}

1.3 LoginController

@Controller
public class LoginController {

    //配置完后不再起作用
    @PostMapping("/login")
    public String login(){
        return "redirect:index.html";
    }

    @PostMapping("/toIndex")
    public String toIndex(){
        return "redirect:index.html";
    }

    @PostMapping("/toError")
    public String toError(){
        return "redirect:error.html";
    }
}

1.4 login.html

<!-- 走UsernamePasswordAuthenticationFilter 有参数name和method 规定-->
    <form action="/login" method="post">
        Username : <input type="text" name="username"><br>
        Password : <input type="password" name="password"><br>
        <input type="submit" value="login">
    </form>

2.自定义登录成功失败处理器

2.1 登录成功处理器

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private String url;

    public MyAuthenticationSuccessHandler(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();
        System.out.println(user.getUsername());
        System.out.println(user.getAuthorities());
        response.sendRedirect(url);
    }
}

2.2 登录失败处理器

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private String url;

    public MyAuthenticationFailureHandler(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.sendRedirect(url);
    }
}

2.3 配置类

@Override
    protected void configure(HttpSecurity http) throws Exception {
        //表单提交 自定义界面
        http.formLogin()
                //自定义参数
                .usernameParameter("Username")
                .passwordParameter("Password")
                .loginPage("/login.html")
                //必须和表单action一样
                .loginProcessingUrl("/login")
                //自定义跳转
                .successHandler(new MyAuthenticationSuccessHandler("http://www.baidu.com"))
                .failureHandler(new MyAuthenticationFailureHandler("error.html"));


        //授权
        http.authorizeRequests()
                //放行登录界面
                .antMatchers("/login.html").permitAll()
                .antMatchers("/error.html").permitAll()
                //有请求必须认证才能访问
                .anyRequest().authenticated();

        http.csrf().disable();
    }
}

3.目录结构

posted @   lwx_R  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示