04-登录表单详细配置

重写 HttpSecurity configure

@Override
protected void configure(HttpSecurity http) throws Exception {
    // 开启配置
    http.authorizeRequests()
            // 访问路径以: /admin/开头的 需要具备哪些角色
            .antMatchers("/admin/**").hasRole("admin")
            // 访问路径以: /user/开头的 需要具备 hasAnyRole中的任意一个角色即可
            .antMatchers("/user/**").hasAnyRole("admin", "user")
            //.antMatchers("/user/**").access("hasAnyRole('admin','admin')")
            //.antMatchers("/user/**").access("hasRole('admin') and hasRole('user')")
            // 剩下的其它请求,都是登录之后就能访问
            .anyRequest().authenticated()
            .and()
            // 表单登陆
            .formLogin()
            // 处理登陆请求的Url
            .loginProcessingUrl("/doLogin")
            // 比如说你访问一个,但是这个借口需要登录之后才可以访问,那么Security会自动的给你跳转到登录页面去,前后端分离的话登录页面就是一个接口而已
            .loginPage("/login")
            // usernameParameter就相当于你前端表单上面的name属性的值 默认为username
            .usernameParameter("uname")
            // passwordParameter就相当于你前端表单上面的name属性的值 默认为password
            .passwordParameter("pwd")
            // 如果是前后端不分的登录的话,登录成功之后服务端会自动给你跳转到项目首页去,这个时候你就可以使用successForwardUrl给你来一个服务端跳转给你跳转到某个页面去
            .successForwardUrl("")
            // 如果是前后端分离的情况下,你只需要告诉前端登录成功还是失败就行了,接下来的就是前端的处理了你不用管,你就可以使用 successHandler; successHandler登录成功的处理器
            .successHandler(new AuthenticationSuccessHandler() {
                @Override
                public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                    // Authentication 保存了你刚刚登录成功的用户信息
                    resp.setContentType("application/json;charset=utf-8");

                    PrintWriter out = resp.getWriter();
                    Map<String, Object> map = new HashMap<>();
                    map.put("status", 200);
                    map.put("msg", authentication.getPrincipal());
                    out.write(new ObjectMapper().writeValueAsString(map));
                    out.flush();
                    out.close();
                }
            })
            // failureForwardUrl 登录失败服务端给你跳转到某个页面去
            .failureForwardUrl("登录失败服务端给你跳转到某个页面")
            // failureHandler 登录失败的处理器
            .failureHandler(new AuthenticationFailureHandler() {
                @Override
                public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                    // 登录失败的原因 AuthenticationException 异常
                    resp.setContentType("application/json;charset=utf-8");

                    PrintWriter out = resp.getWriter();
                    Map<String, Object> map = new HashMap<>();
                    map.put("status", 401);

                    if (e instanceof LockedException) {
                        map.put("msg", "账号被锁定,请联系管理员!");
                    } else if (e instanceof BadCredentialsException) {
                        map.put("msg", "用户名或密码错误!");
                    } else if (e instanceof DisabledException) {
                        map.put("msg", "账号被禁用,请联系管理员!");
                    } else if (e instanceof AccountExpiredException) {
                        map.put("msg", "账号过期,请联系管理员!");
                    } else if (e instanceof CredentialsExpiredException) {
                        map.put("msg", "密码过期,请联系管理员!");
                    } else {
                        map.put("msg", "登录失败!");
                    }

                    out.write(new ObjectMapper().writeValueAsString(map));
                    out.flush();
                    out.close();
                }
            })

            // 登陆相关的接口可以直接访问,直接过
            .permitAll()
            .and()
            // postman测试,关闭csrf攻击
            .csrf().disable();
}

PostMan测试

msg 剩下属性的含义

源码下载地址:https://github.com/XiaoHuiHuiT/SpringSecurity-case/releases/tag/4.0

posted @ 2020-05-16 20:18  Leader_TBlog  阅读(126)  评论(0编辑  收藏  举报