使用AJAX实现SpringSecurity登录(不禁用csrf )

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。使用AJAX实现SpringSecurity登录(不禁用csrf ),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

SpringSecurity配置类代码:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WelfareSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LoginAuthenticationFailureHandler loginAuthenticationFailureHandler;

    @Autowired
    private LoginAuthenticationSuccessHandler loginAuthenticationSuccessHandler;

    
    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security.authorizeRequests()
                //放行首页
                .antMatchers("/index.jsp")
                .permitAll()
                //放行静态资源
                .antMatchers("/assets/**")
                .permitAll()
               //除此之外其他请求都需要进行授权
                .anyRequest()
                .authenticated()
                //登录请求授权
                .and()
                .formLogin()
                .loginPage("/admin/to/login.html")
                .loginProcessingUrl("/security/login.json")
                .permitAll()
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(loginAuthenticationSuccessHandler)
                .failureHandler(loginAuthenticationFailureHandler)
                //开启退出登录功能
                .and()
                .logout()
                .logoutUrl("/security/logout.json")
                .logoutSuccessUrl("/admin/to/login.html");
    }

    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
			auth.inMemoryAuthentication().
			withUser("vinci").password("lmy9901").roles("Admin");
    }

}

重写认证成功、失败处理器
其中的ResultEntity为封装的统一返回类型

@Component
public class LoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        ResultEntity<Object> resultEntity = ResultEntity.successWithoutData();
        String json = new Gson().toJson(resultEntity);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }

}
@Component
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        ResultEntity<Object> resultEntity = ResultEntity.failed(WelfareConstant.MESSAGE_LOGIN_FAILED);
        String json = new Gson().toJson(resultEntity);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }

}

前端页面表单:

<form class="form-horizontal" action="return false"  id="adminLoginForm">
                    <div class="form-group row">
                        <div class="col-12">
                            <input value="vinci" class="form-control" name="username" type="text" required="" placeholder="请输入账号">
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-12">
                            <input value="lmy9901" class="form-control" name="password" type="password" required="" placeholder="请输入密码">
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-12">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" id="customCheck1">
                                <label class="custom-control-label" for="customCheck1">记住我</label>
                            </div>
                        </div>
                    </div>

                    <div class="form-group text-center row m-t-20">
                        <div class="col-12">
                            <button id="adminLoginBtn" class="btn btn-info btn-block waves-effect waves-light" type="button">登录</button>
                        </div>
                    </div>
                </form>

注意:在head标签内一定要加入以下代码

 	<meta name="_csrf" content="${_csrf.token}" />
    <meta name="_csrf_header" content="${_csrf.headerName}" />

最后:向服务器发送AJAX请求

$(function(){

    //获取登录表单数据
    $("#adminLoginBtn").on('click', function () {
        let username = $("#adminLoginForm input[name='username']").val();
        let password = $("#adminLoginForm input[name='password']").val();
        adminLogin(username, password);
    })


})


//管理员登录方法
function adminLogin(username, password) {

    if (username == null || username == "") {
        layer.msg("请输入账号");
        return;
    }
    if (password == null || password == "") {
        layer.msg("请输入密码");
        return;
    }

    let token = $("meta[name='_csrf']").attr("content");
    let header = $("meta[name='_csrf_header']").attr("content");


    $.ajax({
        type: "post",
        url: "/security/login.json",
        data: {
            "username": username,
            "password": password
        },
        dataType: "json",
        beforeSend: function(request) {
            request.setRequestHeader(header, token);
        },
        success(response) {
            let result = response.operationResult;
            let msg = response.operationMessage;
            if (result == "success") {
                layer.msg("登录成功");
                setTimeout(function () {
                    window.location.href = "admin/to/main.html"
                }, 1000)
            }
            if (result == "failed") {
                layer.msg(msg);
            }
        },
        error(response) {
            layer.alert(response);
        }
    })

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/204371.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!