首页 > 其他分享 >自定义用户登录验证

自定义用户登录验证

时间:2023-01-14 20:23:36浏览次数:34  
标签:http 自定义 登录 验证 url html login public String

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.目录结构

标签:http,自定义,登录,验证,url,html,login,public,String
From: https://www.cnblogs.com/lwx11111/p/17052476.html

相关文章

  • arcgis api for 自定义zoom
    1.需求自定义UI,实现对地图的zoom操作,在view缩放的时候,带动画效果2.分析问题UI视图一般情况,可能大部分初学者会使用以下代码对zoom进行操作,这个方法是可以放大缩小,但是......
  • iisexpress 绑定自定义域名
    1、项目根目录找到    2、添加绑定域名  3、host映射  4、以管理员身份运行vs,以管理员身份运行vs,以管理员身份运行vs,重要的事情说三遍。。。不然域名无......
  • 初次登录MySQL
    对于linux中刚安装的mysql来说,初始用户是root,这个root不是linux中的root,而是mysql的root,而初始密码是没有的。1.登录MySQL登录MySQL的命令是mysql,mysql的使用语法如下:my......
  • 8-综合 & 形式验证
    来自:《综合与DesignCompiler》1.什么是综合在满足设计电路的功能、速度及面积等限制条件下,将行为级描述转化为电路网表的过程。分为三个步骤:转换(translation)、映射......
  • VMware下配置Ubuntu为静态IP地址并使用SSH登录
    安装虚拟机之后,经常需要使用xshell进行远程连接登录,但是安装后的虚拟机默认为DHCP动态分配IP地址,每次重启虚拟机IP就会改变,很不方便,所以这里我们需要将其设置为静态IP1......
  • JS_6_自定义对象
    JS中万事万物皆对象,灵活! 对象:可以调用不存在的属性方法(自动扩充),值为undefined。可以直接新增属性方法。创建自定义对象://创建一个自定义对象var对象名......
  • JS_5_自定义类
    JS万事万物皆对象,灵活!可以调用不存在的属性和方法。(即为undefined。)  创建一个类:格式:function类名(形参){this.属性名=形参;...this.属性名......
  • 使用go自定义生成项目LISENSE(授权协议)
    需要使用一个使用go开发的工具,叫license,在Windows下安装这个工具,请确保你使用的gosdk是1.16以上的版本,然后执行下面的命令:goinstallgithub.com/nishanths/license/v5@......
  • Vue3 自定义指令执行了两次的问题
    下面是我注册全局指令的代码:app.directive("parse-code",(el:any,binding:any)=>{//......console.log("execute!!!");});似乎没有问题,控制台打印一下,看......
  • Flex/AS3/flash player支持屏蔽右键菜单,自定义菜单,并设置相应的菜单事件(示例,图解)
    播放器版本11.2以后支持右键菜单屏蔽及自定义菜单1.更新播放器,11.2以上版本​​http://download.macromedia.com/get/flashplayer/updaters/11/playerglobal11_3.swc......